exonum-client-cis
Version:
Light Client for Exonum CIS Blockchain
43,724 lines • 1.8 MB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Exonum = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
module.exports = _arrayWithHoles;
},{}],2:[function(require,module,exports){
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
module.exports = _arrayWithoutHoles;
},{}],3:[function(require,module,exports){
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized;
},{}],4:[function(require,module,exports){
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator;
},{}],5:[function(require,module,exports){
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck;
},{}],6:[function(require,module,exports){
var setPrototypeOf = require("./setPrototypeOf");
function isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (isNativeReflectConstruct()) {
module.exports = _construct = Reflect.construct;
} else {
module.exports = _construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
module.exports = _construct;
},{"./setPrototypeOf":19}],7:[function(require,module,exports){
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
module.exports = _createClass;
},{}],8:[function(require,module,exports){
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
},{}],9:[function(require,module,exports){
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
},{}],10:[function(require,module,exports){
var setPrototypeOf = require("./setPrototypeOf");
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits;
},{"./setPrototypeOf":19}],11:[function(require,module,exports){
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
}
module.exports = _interopRequireDefault;
},{}],12:[function(require,module,exports){
var _typeof = require("../helpers/typeof");
function _getRequireWildcardCache() {
if (typeof WeakMap !== "function") return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
return {
"default": obj
};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj["default"] = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
module.exports = _interopRequireWildcard;
},{"../helpers/typeof":22}],13:[function(require,module,exports){
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
module.exports = _isNativeFunction;
},{}],14:[function(require,module,exports){
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
module.exports = _iterableToArray;
},{}],15:[function(require,module,exports){
function _iterableToArrayLimit(arr, i) {
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
return;
}
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
module.exports = _iterableToArrayLimit;
},{}],16:[function(require,module,exports){
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
module.exports = _nonIterableRest;
},{}],17:[function(require,module,exports){
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
module.exports = _nonIterableSpread;
},{}],18:[function(require,module,exports){
var _typeof = require("../helpers/typeof");
var assertThisInitialized = require("./assertThisInitialized");
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
},{"../helpers/typeof":22,"./assertThisInitialized":3}],19:[function(require,module,exports){
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
},{}],20:[function(require,module,exports){
var arrayWithHoles = require("./arrayWithHoles");
var iterableToArrayLimit = require("./iterableToArrayLimit");
var nonIterableRest = require("./nonIterableRest");
function _slicedToArray(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || nonIterableRest();
}
module.exports = _slicedToArray;
},{"./arrayWithHoles":1,"./iterableToArrayLimit":15,"./nonIterableRest":16}],21:[function(require,module,exports){
var arrayWithoutHoles = require("./arrayWithoutHoles");
var iterableToArray = require("./iterableToArray");
var nonIterableSpread = require("./nonIterableSpread");
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || nonIterableSpread();
}
module.exports = _toConsumableArray;
},{"./arrayWithoutHoles":2,"./iterableToArray":14,"./nonIterableSpread":17}],22:[function(require,module,exports){
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
module.exports = _typeof;
},{}],23:[function(require,module,exports){
var getPrototypeOf = require("./getPrototypeOf");
var setPrototypeOf = require("./setPrototypeOf");
var isNativeFunction = require("./isNativeFunction");
var construct = require("./construct");
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return construct(Class, arguments, getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
module.exports = _wrapNativeSuper;
},{"./construct":6,"./getPrototypeOf":9,"./isNativeFunction":13,"./setPrototypeOf":19}],24:[function(require,module,exports){
module.exports = require("regenerator-runtime");
},{"regenerator-runtime":78}],25:[function(require,module,exports){
"use strict";
module.exports = asPromise;
/**
* Callback as used by {@link util.asPromise}.
* @typedef asPromiseCallback
* @type {function}
* @param {Error|null} error Error, if any
* @param {...*} params Additional arguments
* @returns {undefined}
*/
/**
* Returns a promise from a node-style callback function.
* @memberof util
* @param {asPromiseCallback} fn Function to call
* @param {*} ctx Function context
* @param {...*} params Function arguments
* @returns {Promise<*>} Promisified function
*/
function asPromise(fn, ctx/*, varargs */) {
var params = new Array(arguments.length - 1),
offset = 0,
index = 2,
pending = true;
while (index < arguments.length)
params[offset++] = arguments[index++];
return new Promise(function executor(resolve, reject) {
params[offset] = function callback(err/*, varargs */) {
if (pending) {
pending = false;
if (err)
reject(err);
else {
var params = new Array(arguments.length - 1),
offset = 0;
while (offset < params.length)
params[offset++] = arguments[offset];
resolve.apply(null, params);
}
}
};
try {
fn.apply(ctx || null, params);
} catch (err) {
if (pending) {
pending = false;
reject(err);
}
}
});
}
},{}],26:[function(require,module,exports){
"use strict";
/**
* A minimal base64 implementation for number arrays.
* @memberof util
* @namespace
*/
var base64 = exports;
/**
* Calculates the byte length of a base64 encoded string.
* @param {string} string Base64 encoded string
* @returns {number} Byte length
*/
base64.length = function length(string) {
var p = string.length;
if (!p)
return 0;
var n = 0;
while (--p % 4 > 1 && string.charAt(p) === "=")
++n;
return Math.ceil(string.length * 3) / 4 - n;
};
// Base64 encoding table
var b64 = new Array(64);
// Base64 decoding table
var s64 = new Array(123);
// 65..90, 97..122, 48..57, 43, 47
for (var i = 0; i < 64;)
s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
/**
* Encodes a buffer to a base64 encoded string.
* @param {Uint8Array} buffer Source buffer
* @param {number} start Source start
* @param {number} end Source end
* @returns {string} Base64 encoded string
*/
base64.encode = function encode(buffer, start, end) {
var parts = null,
chunk = [];
var i = 0, // output index
j = 0, // goto index
t; // temporary
while (start < end) {
var b = buffer[start++];
switch (j) {
case 0:
chunk[i++] = b64[b >> 2];
t = (b & 3) << 4;
j = 1;
break;
case 1:
chunk[i++] = b64[t | b >> 4];
t = (b & 15) << 2;
j = 2;
break;
case 2:
chunk[i++] = b64[t | b >> 6];
chunk[i++] = b64[b & 63];
j = 0;
break;
}
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
i = 0;
}
}
if (j) {
chunk[i++] = b64[t];
chunk[i++] = 61;
if (j === 1)
chunk[i++] = 61;
}
if (parts) {
if (i)
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
return parts.join("");
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
};
var invalidEncoding = "invalid encoding";
/**
* Decodes a base64 encoded string to a buffer.
* @param {string} string Source string
* @param {Uint8Array} buffer Destination buffer
* @param {number} offset Destination offset
* @returns {number} Number of bytes written
* @throws {Error} If encoding is invalid
*/
base64.decode = function decode(string, buffer, offset) {
var start = offset;
var j = 0, // goto index
t; // temporary
for (var i = 0; i < string.length;) {
var c = string.charCodeAt(i++);
if (c === 61 && j > 1)
break;
if ((c = s64[c]) === undefined)
throw Error(invalidEncoding);
switch (j) {
case 0:
t = c;
j = 1;
break;
case 1:
buffer[offset++] = t << 2 | (c & 48) >> 4;
t = c;
j = 2;
break;
case 2:
buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
t = c;
j = 3;
break;
case 3:
buffer[offset++] = (t & 3) << 6 | c;
j = 0;
break;
}
}
if (j === 1)
throw Error(invalidEncoding);
return offset - start;
};
/**
* Tests if the specified string appears to be base64 encoded.
* @param {string} string String to test
* @returns {boolean} `true` if probably base64 encoded, otherwise false
*/
base64.test = function test(string) {
return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
};
},{}],27:[function(require,module,exports){
"use strict";
module.exports = EventEmitter;
/**
* Constructs a new event emitter instance.
* @classdesc A minimal event emitter.
* @memberof util
* @constructor
*/
function EventEmitter() {
/**
* Registered listeners.
* @type {Object.<string,*>}
* @private
*/
this._listeners = {};
}
/**
* Registers an event listener.
* @param {string} evt Event name
* @param {function} fn Listener
* @param {*} [ctx] Listener context
* @returns {util.EventEmitter} `this`
*/
EventEmitter.prototype.on = function on(evt, fn, ctx) {
(this._listeners[evt] || (this._listeners[evt] = [])).push({
fn : fn,
ctx : ctx || this
});
return this;
};
/**
* Removes an event listener or any matching listeners if arguments are omitted.
* @param {string} [evt] Event name. Removes all listeners if omitted.
* @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
* @returns {util.EventEmitter} `this`
*/
EventEmitter.prototype.off = function off(evt, fn) {
if (evt === undefined)
this._listeners = {};
else {
if (fn === undefined)
this._listeners[evt] = [];
else {
var listeners = this._listeners[evt];
for (var i = 0; i < listeners.length;)
if (listeners[i].fn === fn)
listeners.splice(i, 1);
else
++i;
}
}
return this;
};
/**
* Emits an event by calling its listeners with the specified arguments.
* @param {string} evt Event name
* @param {...*} args Arguments
* @returns {util.EventEmitter} `this`
*/
EventEmitter.prototype.emit = function emit(evt) {
var listeners = this._listeners[evt];
if (listeners) {
var args = [],
i = 1;
for (; i < arguments.length;)
args.push(arguments[i++]);
for (i = 0; i < listeners.length;)
listeners[i].fn.apply(listeners[i++].ctx, args);
}
return this;
};
},{}],28:[function(require,module,exports){
"use strict";
module.exports = factory(factory);
/**
* Reads / writes floats / doubles from / to buffers.
* @name util.float
* @namespace
*/
/**
* Writes a 32 bit float to a buffer using little endian byte order.
* @name util.float.writeFloatLE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Writes a 32 bit float to a buffer using big endian byte order.
* @name util.float.writeFloatBE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Reads a 32 bit float from a buffer using little endian byte order.
* @name util.float.readFloatLE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
/**
* Reads a 32 bit float from a buffer using big endian byte order.
* @name util.float.readFloatBE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
/**
* Writes a 64 bit double to a buffer using little endian byte order.
* @name util.float.writeDoubleLE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Writes a 64 bit double to a buffer using big endian byte order.
* @name util.float.writeDoubleBE
* @function
* @param {number} val Value to write
* @param {Uint8Array} buf Target buffer
* @param {number} pos Target buffer offset
* @returns {undefined}
*/
/**
* Reads a 64 bit double from a buffer using little endian byte order.
* @name util.float.readDoubleLE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
/**
* Reads a 64 bit double from a buffer using big endian byte order.
* @name util.float.readDoubleBE
* @function
* @param {Uint8Array} buf Source buffer
* @param {number} pos Source buffer offset
* @returns {number} Value read
*/
// Factory function for the purpose of node-based testing in modified global environments
function factory(exports) {
// float: typed array
if (typeof Float32Array !== "undefined") (function() {
var f32 = new Float32Array([ -0 ]),
f8b = new Uint8Array(f32.buffer),
le = f8b[3] === 128;
function writeFloat_f32_cpy(val, buf, pos) {
f32[0] = val;
buf[pos ] = f8b[0];
buf[pos + 1] = f8b[1];
buf[pos + 2] = f8b[2];
buf[pos + 3] = f8b[3];
}
function writeFloat_f32_rev(val, buf, pos) {
f32[0] = val;
buf[pos ] = f8b[3];
buf[pos + 1] = f8b[2];
buf[pos + 2] = f8b[1];
buf[pos + 3] = f8b[0];
}
/* istanbul ignore next */
exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
/* istanbul ignore next */
exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
function readFloat_f32_cpy(buf, pos) {
f8b[0] = buf[pos ];
f8b[1] = buf[pos + 1];
f8b[2] = buf[pos + 2];
f8b[3] = buf[pos + 3];
return f32[0];
}
function readFloat_f32_rev(buf, pos) {
f8b[3] = buf[pos ];
f8b[2] = buf[pos + 1];
f8b[1] = buf[pos + 2];
f8b[0] = buf[pos + 3];
return f32[0];
}
/* istanbul ignore next */
exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
/* istanbul ignore next */
exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
// float: ieee754
})(); else (function() {
function writeFloat_ieee754(writeUint, val, buf, pos) {
var sign = val < 0 ? 1 : 0;
if (sign)
val = -val;
if (val === 0)
writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
else if (isNaN(val))
writeUint(2143289344, buf, pos);
else if (val > 3.4028234663852886e+38) // +-Infinity
writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
else if (val < 1.1754943508222875e-38) // denormal
writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
else {
var exponent = Math.floor(Math.log(val) / Math.LN2),
mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
}
}
exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
function readFloat_ieee754(readUint, buf, pos) {
var uint = readUint(buf, pos),
sign = (uint >> 31) * 2 + 1,
exponent = uint >>> 23 & 255,
mantissa = uint & 8388607;
return exponent === 255
? mantissa
? NaN
: sign * Infinity
: exponent === 0 // denormal
? sign * 1.401298464324817e-45 * mantissa
: sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
}
exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
})();
// double: typed array
if (typeof Float64Array !== "undefined") (function() {
var f64 = new Float64Array([-0]),
f8b = new Uint8Array(f64.buffer),
le = f8b[7] === 128;
function writeDouble_f64_cpy(val, buf, pos) {
f64[0] = val;
buf[pos ] = f8b[0];
buf[pos + 1] = f8b[1];
buf[pos + 2] = f8b[2];
buf[pos + 3] = f8b[3];
buf[pos + 4] = f8b[4];
buf[pos + 5] = f8b[5];
buf[pos + 6] = f8b[6];
buf[pos + 7] = f8b[7];
}
function writeDouble_f64_rev(val, buf, pos) {
f64[0] = val;
buf[pos ] = f8b[7];
buf[pos + 1] = f8b[6];
buf[pos + 2] = f8b[5];
buf[pos + 3] = f8b[4];
buf[pos + 4] = f8b[3];
buf[pos + 5] = f8b[2];
buf[pos + 6] = f8b[1];
buf[pos + 7] = f8b[0];
}
/* istanbul ignore next */
exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
/* istanbul ignore next */
exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
function readDouble_f64_cpy(buf, pos) {
f8b[0] = buf[pos ];
f8b[1] = buf[pos + 1];
f8b[2] = buf[pos + 2];
f8b[3] = buf[pos + 3];
f8b[4] = buf[pos + 4];
f8b[5] = buf[pos + 5];
f8b[6] = buf[pos + 6];
f8b[7] = buf[pos + 7];
return f64[0];
}
function readDouble_f64_rev(buf, pos) {
f8b[7] = buf[pos ];
f8b[6] = buf[pos + 1];
f8b[5] = buf[pos + 2];
f8b[4] = buf[pos + 3];
f8b[3] = buf[pos + 4];
f8b[2] = buf[pos + 5];
f8b[1] = buf[pos + 6];
f8b[0] = buf[pos + 7];
return f64[0];
}
/* istanbul ignore next */
exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
/* istanbul ignore next */
exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
// double: ieee754
})(); else (function() {
function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
var sign = val < 0 ? 1 : 0;
if (sign)
val = -val;
if (val === 0) {
writeUint(0, buf, pos + off0);
writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
} else if (isNaN(val)) {
writeUint(0, buf, pos + off0);
writeUint(2146959360, buf, pos + off1);
} else if (val > 1.7976931348623157e+308) { // +-Infinity
writeUint(0, buf, pos + off0);
writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
} else {
var mantissa;
if (val < 2.2250738585072014e-308) { // denormal
mantissa = val / 5e-324;
writeUint(mantissa >>> 0, buf, pos + off0);
writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
} else {
var exponent = Math.floor(Math.log(val) / Math.LN2);
if (exponent === 1024)
exponent = 1023;
mantissa = val * Math.pow(2, -exponent);
writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
}
}
}
exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
function readDouble_ieee754(readUint, off0, off1, buf, pos) {
var lo = readUint(buf, pos + off0),
hi = readUint(buf, pos + off1);
var sign = (hi >> 31) * 2 + 1,
exponent = hi >>> 20 & 2047,
mantissa = 4294967296 * (hi & 1048575) + lo;
return exponent === 2047
? mantissa
? NaN
: sign * Infinity
: exponent === 0 // denormal
? sign * 5e-324 * mantissa
: sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
}
exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
})();
return exports;
}
// uint helpers
function writeUintLE(val, buf, pos) {
buf[pos ] = val & 255;
buf[pos + 1] = val >>> 8 & 255;
buf[pos + 2] = val >>> 16 & 255;
buf[pos + 3] = val >>> 24;
}
function writeUintBE(val, buf, pos) {
buf[pos ] = val >>> 24;
buf[pos + 1] = val >>> 16 & 255;
buf[pos + 2] = val >>> 8 & 255;
buf[pos + 3] = val & 255;
}
function readUintLE(buf, pos) {
return (buf[pos ]
| buf[pos + 1] << 8
| buf[pos + 2] << 16
| buf[pos + 3] << 24) >>> 0;
}
function readUintBE(buf, pos) {
return (buf[pos ] << 24
| buf[pos + 1] << 16
| buf[pos + 2] << 8
| buf[pos + 3]) >>> 0;
}
},{}],29:[function(require,module,exports){
"use strict";
module.exports = inquire;
/**
* Requires a module only if available.
* @memberof util
* @param {string} moduleName Module to require
* @returns {?Object} Required module if available and not empty, otherwise `null`
*/
function inquire(moduleName) {
try {
var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval
if (mod && (mod.length || Object.keys(mod).length))
return mod;
} catch (e) {} // eslint-disable-line no-empty
return null;
}
},{}],30:[function(require,module,exports){
"use strict";
module.exports = pool;
/**
* An allocator as used by {@link util.pool}.
* @typedef PoolAllocator
* @type {function}
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
/**
* A slicer as used by {@link util.pool}.
* @typedef PoolSlicer
* @type {function}
* @param {number} start Start offset
* @param {number} end End offset
* @returns {Uint8Array} Buffer slice
* @this {Uint8Array}
*/
/**
* A general purpose buffer pool.
* @memberof util
* @function
* @param {PoolAllocator} alloc Allocator
* @param {PoolSlicer} slice Slicer
* @param {number} [size=8192] Slab size
* @returns {PoolAllocator} Pooled allocator
*/
function pool(alloc, slice, size) {
var SIZE = size || 8192;
var MAX = SIZE >>> 1;
var slab = null;
var offset = SIZE;
return function pool_alloc(size) {
if (size < 1 || size > MAX)
return alloc(size);
if (offset + size > SIZE) {
slab = alloc(SIZE);
offset = 0;
}
var buf = slice.call(slab, offset, offset += size);
if (offset & 7) // align to 32 bit
offset = (offset | 7) + 1;
return buf;
};
}
},{}],31:[function(require,module,exports){
"use strict";
/**
* A minimal UTF8 implementation for number arrays.
* @memberof util
* @namespace
*/
var utf8 = exports;
/**
* Calculates the UTF8 byte length of a string.
* @param {string} string String
* @returns {number} Byte length
*/
utf8.length = function utf8_length(string) {
var len = 0,
c = 0;
for (var i = 0; i < string.length; ++i) {
c = string.charCodeAt(i);
if (c < 128)
len += 1;
else if (c < 2048)
len += 2;
else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
++i;
len += 4;
} else
len += 3;
}
return len;
};
/**
* Reads UTF8 bytes as a string.
* @param {Uint8Array} buffer Source buffer
* @param {number} start Source start
* @param {number} end Source end
* @returns {string} String read
*/
utf8.read = function utf8_read(buffer, start, end) {
var len = end - start;
if (len < 1)
return "";
var parts = null,
chunk = [],
i = 0, // char offset
t; // temporary
while (start < end) {
t = buffer[start++];
if (t < 128)
chunk[i++] = t;
else if (t > 191 && t < 224)
chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
else if (t > 239 && t < 365) {
t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
chunk[i++] = 0xD800 + (t >> 10);
chunk[i++] = 0xDC00 + (t & 1023);
} else
chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
if (i > 8191) {
(parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
i = 0;
}
}
if (parts) {
if (i)
parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
return parts.join("");
}
return String.fromCharCode.apply(String, chunk.slice(0, i));
};
/**
* Writes a string as UTF8 bytes.
* @param {string} string Source string
* @param {Uint8Array} buffer Destination buffer
* @param {number} offset Destination offset
* @returns {number} Bytes written
*/
utf8.write = function utf8_write(string, buffer, offset) {
var start = offset,
c1, // character 1
c2; // character 2
for (var i = 0; i < string.length; ++i) {
c1 = string.charCodeAt(i);
if (c1 < 128) {
buffer[offset++] = c1;
} else if (c1 < 2048) {
buffer[offset++] = c1 >> 6 | 192;
buffer[offset++] = c1 & 63 | 128;
} else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
++i;
buffer[offset++] = c1 >> 18 | 240;
buffer[offset++] = c1 >> 12 & 63 | 128;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
} else {
buffer[offset++] = c1 >> 12 | 224;
buffer[offset++] = c1 >> 6 & 63 | 128;
buffer[offset++] = c1 & 63 | 128;
}
}
return offset - start;
};
},{}],32:[function(require,module,exports){
module.exports = require('./lib/axios');
},{"./lib/axios":34}],33:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var buildURL = require('./../helpers/buildURL');
var buildFullPath = require('../core/buildFullPath');
var parseHeaders = require('./../helpers/parseHeaders');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var createError = require('../core/createError');
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
};
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = require('./../helpers/cookies');
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
if (config.responseType !== 'json') {
throw e;
}
}
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken) {
// Handle cancellation
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
request.abort();
reject(cancel);
// Clean up request
request = null;
});
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
},{"../core/buildFullPath":40,"../core/createError":41,"./../core/settle":45,"./../helpers/buildURL":49,"./../helpers/cookies":51,"./../helpers/isURLSameOrigin":53,"./../helpers/parseHeaders":55,"./../utils":57}],34:[function(require,module,exports){
'use strict';
var utils = require('./utils');
var bind = require('./helpers/bind');
var Axios = require('./core/Axios');
var mergeConfig = require('./core/mergeConfig');
var defaults = require('./defaults');
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Factory for creating new instances
axios.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios.defaults, instanceConfig));
};
// Expose Cancel & CancelToken
axios.Cancel = require('./cancel/Cancel');
axios.CancelToken = require('./cancel/CancelToken');
axios.isCancel = require('./cancel/isCancel');
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = require('./helpers/spread');
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
},{"./cancel/Cancel":35,"./cancel/CancelToken":36,"./cancel/isCancel":37,"./core/Axios":38,"./core/mergeConfig":44,"./defaults":47,"./helpers/bind":48,"./helpers/spread":56,"./utils":57}],35:[function(require,module,exports){
'use strict';
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
},{}],36:[function(require,module,exports){
'use strict';
var Cancel = require('./Cancel');
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
},{"./Cancel":35}],37:[function(require,module,exports){
'use strict';
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
},{}],38:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
var buildURL = require('../helpers/buildURL');
var InterceptorManager = require('./InterceptorManager');
var dispatchRequest = require('./dispatchRequest');
var mergeConfig = require('./mergeConfig');
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
},{"../helpers/buildURL":49,"./../utils":57,"./InterceptorManager":39,"./dispatchRequest":42,"./mergeConfig":44}],39:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
},{"./../utils":57}],40:[function(require,module,exports){
'use strict';
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
},{"../helpers/combineURLs":50,"../helpers/isAbsoluteURL":52}],41:[function(require,module,exports){
'use strict';
var enhanceError = require('./enhanceError');
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
},{"./enhanceError":43}],42:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData(
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData(
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
},{"../cancel/isCancel":37,"../defaults":47,"./../utils":57,"./transformData":46}],43:[function(require,module,exports){
'use strict';
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code
};
};
return error;
};
},{}],44:[function(require,module,exports){
'use strict';
var utils = require('../utils');
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var defaultToConfig2Keys = [
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath'
];
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
}
});
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
} else if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (utils.isObject(config1[prop])) {
config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys);
var otherKeys = Object
.keys(config2)
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
return config;
};
},{"../utils":57}],45:[function(require,module,exports){
'use strict';
var createError = require('./createError');
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
},{"./createError":41}],46:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
},{"./../utils":57}],47:[function(require,module,exports){
(function (process){
'use strict';
var utils = require('./utils');
var normalizeHeaderName = require('./helpers/normalizeHeaderName');
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = require('./adapters/xhr');
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = require('./adapters/http');
}
return adapter;
}
var defaults = {
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults.headers = {
common: {
'Accept': 'application/json, text/plain, */*'
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
}).call(this,require('_process'))
},{"./adapters/http":33,"./adapters/xhr":33,"./helpers/normalizeHeaderName":54,"./utils":57,"_process":66}],48:[function(require,module,exports){
'use strict';
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
},{}],49:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
},{"./../utils":57}],50:[function(require,module,exports){
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
},{}],51:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
},{"./../utils":57}],52:[function(require,module,exports){
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
},{}],53:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
},{"./../utils":57}],54:[function(require,module,exports){
'use strict';
var utils = require('../utils');
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
},{"../utils":57}],55:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
},{"./../utils":57}],56:[function(require,module,exports){
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
},{}],57:[function(require,module,exports){
'use strict';
var bind = require('./helpers/bind');
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
deepMerge: deepMerge,
extend: extend,
trim: trim
};
},{"./helpers/bind":48}],58:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
for (var i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],59:[function(require,module,exports){
var bigInt = (function (undefined) {
"use strict";
var BASE = 1e7,
LOG_BASE = 7,
MAX_INT = 9007199254740992,
MAX_INT_ARR = smallToArray(MAX_INT),
DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
var supportsNativeBigInt = typeof BigInt === "function";
function Integer(v, radix, alphabet, caseSensitive) {
if (typeof v === "undefined") return Integer[0];
if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);
return parseValue(v);
}
function BigInteger(value, sign) {
this.value = value;
this.sign = sign;
this.isSmall = false;
}
BigInteger.prototype = Object.create(Integer.prototype);
function SmallInteger(value) {
this.value = value;
this.sign = value < 0;
this.isSmall = true;
}
SmallInteger.prototype = Object.create(Integer.prototype);
function NativeBigInt(value) {
this.value = value;
}
NativeBigInt.prototype = Object.create(Integer.prototype);
function isPrecise(n) {
return -MAX_INT < n && n < MAX_INT;
}
function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
if (n < 1e7)
return [n];
if (n < 1e14)
return [n % 1e7, Math.floor(n / 1e7)];
return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
}
function arrayToSmall(arr) { // If BASE changes this function may need to change
trim(arr);
var length = arr.length;
if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
switch (length) {
case 0: return 0;
case 1: return arr[0];
case 2: return arr[0] + arr[1] * BASE;
default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
}
}
return arr;
}
function trim(v) {
var i = v.length;
while (v[--i] === 0);
v.length = i + 1;
}
function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
var x = new Array(length);
var i = -1;
while (++i < length) {
x[i] = 0;
}
return x;
}
function truncate(n) {
if (n > 0) return Math.floor(n);
return Math.ceil(n);
}
function add(a, b) { // assumes a and b are arrays with a.length >= b.length
var l_a = a.length,
l_b = b.length,
r = new Array(l_a),
carry = 0,
base = BASE,
sum, i;
for (i = 0; i < l_b; i++) {
sum = a[i] + b[i] + carry;
carry = sum >= base ? 1 : 0;
r[i] = sum - carry * base;
}
while (i < l_a) {
sum = a[i] + carry;
carry = sum === base ? 1 : 0;
r[i++] = sum - carry * base;
}
if (carry > 0) r.push(carry);
return r;
}
function addAny(a, b) {
if (a.length >= b.length) return add(a, b);
return add(b, a);
}
function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
var l = a.length,
r = new Array(l),
base = BASE,
sum, i;
for (i = 0; i < l; i++) {
sum = a[i] - base + carry;
carry = Math.floor(sum / base);
r[i] = sum - carry * base;
carry += 1;
}
while (carry > 0) {
r[i++] = carry % base;
carry = Math.floor(carry / base);
}
return r;
}
BigInteger.prototype.add = function (v) {
var n = parseValue(v);
if (this.sign !== n.sign) {
return this.subtract(n.negate());
}
var a = this.value, b = n.value;
if (n.isSmall) {
return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
}
return new BigInteger(addAny(a, b), this.sign);
};
BigInteger.prototype.plus = BigInteger.prototype.add;
SmallInteger.prototype.add = function (v) {
var n = parseValue(v);
var a = this.value;
if (a < 0 !== n.sign) {
return this.subtract(n.negate());
}
var b = n.value;
if (n.isSmall) {
if (isPrecise(a + b)) return new SmallInteger(a + b);
b = smallToArray(Math.abs(b));
}
return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
};
SmallInteger.prototype.plus = SmallInteger.prototype.add;
NativeBigInt.prototype.add = function (v) {
return new NativeBigInt(this.value + parseValue(v).value);
}
NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
function subtract(a, b) { // assumes a and b are arrays with a >= b
var a_l = a.length,
b_l = b.length,
r = new Array(a_l),
borrow = 0,
base = BASE,
i, difference;
for (i = 0; i < b_l; i++) {
difference = a[i] - borrow - b[i];
if (difference < 0) {
difference += base;
borrow = 1;
} else borrow = 0;
r[i] = difference;
}
for (i = b_l; i < a_l; i++) {
difference = a[i] - borrow;
if (difference < 0) difference += base;
else {
r[i++] = difference;
break;
}
r[i] = difference;
}
for (; i < a_l; i++) {
r[i] = a[i];
}
trim(r);
return r;
}
function subtractAny(a, b, sign) {
var value;
if (compareAbs(a, b) >= 0) {
value = subtract(a, b);
} else {
value = subtract(b, a);
sign = !sign;
}
value = arrayToSmall(value);
if (typeof value === "number") {
if (sign) value = -value;
return new SmallInteger(value);
}
return new BigInteger(value, sign);
}
function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
var l = a.length,
r = new Array(l),
carry = -b,
base = BASE,
i, difference;
for (i = 0; i < l; i++) {
difference = a[i] + carry;
carry = Math.floor(difference / base);
difference %= base;
r[i] = difference < 0 ? difference + base : difference;
}
r = arrayToSmall(r);
if (typeof r === "number") {
if (sign) r = -r;
return new SmallInteger(r);
} return new BigInteger(r, sign);
}
BigInteger.prototype.subtract = function (v) {
var n = parseValue(v);
if (this.sign !== n.sign) {
return this.add(n.negate());
}
var a = this.value, b = n.value;
if (n.isSmall)
return subtractSmall(a, Math.abs(b), this.sign);
return subtractAny(a, b, this.sign);
};
BigInteger.prototype.minus = BigInteger.prototype.subtract;
SmallInteger.prototype.subtract = function (v) {
var n = parseValue(v);
var a = this.value;
if (a < 0 !== n.sign) {
return this.add(n.negate());
}
var b = n.value;
if (n.isSmall) {
return new SmallInteger(a - b);
}
return subtractSmall(b, Math.abs(a), a >= 0);
};
SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
NativeBigInt.prototype.subtract = function (v) {
return new NativeBigInt(this.value - parseValue(v).value);
}
NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
BigInteger.prototype.negate = function () {
return new BigInteger(this.value, !this.sign);
};
SmallInteger.prototype.negate = function () {
var sign = this.sign;
var small = new SmallInteger(-this.value);
small.sign = !sign;
return small;
};
NativeBigInt.prototype.negate = function () {
return new NativeBigInt(-this.value);
}
BigInteger.prototype.abs = function () {
return new BigInteger(this.value, false);
};
SmallInteger.prototype.abs = function () {
return new SmallInteger(Math.abs(this.value));
};
NativeBigInt.prototype.abs = function () {
return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
}
function multiplyLong(a, b) {
var a_l = a.length,
b_l = b.length,
l = a_l + b_l,
r = createArray(l),
base = BASE,
product, carry, i, a_i, b_j;
for (i = 0; i < a_l; ++i) {
a_i = a[i];
for (var j = 0; j < b_l; ++j) {
b_j = b[j];
product = a_i * b_j + r[i + j];
carry = Math.floor(product / base);
r[i + j] = product - carry * base;
r[i + j + 1] += carry;
}
}
trim(r);
return r;
}
function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
var l = a.length,
r = new Array(l),
base = BASE,
carry = 0,
product, i;
for (i = 0; i < l; i++) {
product = a[i] * b + carry;
carry = Math.floor(product / base);
r[i] = product - carry * base;
}
while (carry > 0) {
r[i++] = carry % base;
carry = Math.floor(carry / base);
}
return r;
}
function shiftLeft(x, n) {
var r = [];
while (n-- > 0) r.push(0);
return r.concat(x);
}
function multiplyKaratsuba(x, y) {
var n = Math.max(x.length, y.length);
if (n <= 30) return multiplyLong(x, y);
n = Math.ceil(n / 2);
var b = x.slice(n),
a = x.slice(0, n),
d = y.slice(n),
c = y.slice(0, n);
var ac = multiplyKaratsuba(a, c),
bd = multiplyKaratsuba(b, d),
abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
trim(product);
return product;
}
// The following function is derived from a surface fit of a graph plotting the performance difference
// between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
function useKaratsuba(l1, l2) {
return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
}
BigInteger.prototype.multiply = function (v) {
var n = parseValue(v),
a = this.value, b = n.value,
sign = this.sign !== n.sign,
abs;
if (n.isSmall) {
if (b === 0) return Integer[0];
if (b === 1) return this;
if (b === -1) return this.negate();
abs = Math.abs(b);
if (abs < BASE) {
return new BigInteger(multiplySmall(a, abs), sign);
}
b = smallToArray(abs);
}
if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
return new BigInteger(multiplyKaratsuba(a, b), sign);
return new BigInteger(multiplyLong(a, b), sign);
};
BigInteger.prototype.times = BigInteger.prototype.multiply;
function multiplySmallAndArray(a, b, sign) { // a >= 0
if (a < BASE) {
return new BigInteger(multiplySmall(b, a), sign);
}
return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
}
SmallInteger.prototype._multiplyBySmall = function (a) {
if (isPrecise(a.value * this.value)) {
return new SmallInteger(a.value * this.value);
}
return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
};
BigInteger.prototype._multiplyBySmall = function (a) {
if (a.value === 0) return Integer[0];
if (a.value === 1) return this;
if (a.value === -1) return this.negate();
return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
};
SmallInteger.prototype.multiply = function (v) {
return parseValue(v)._multiplyBySmall(this);
};
SmallInteger.prototype.times = SmallInteger.prototype.multiply;
NativeBigInt.prototype.multiply = function (v) {
return new NativeBigInt(this.value * parseValue(v).value);
}
NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
function square(a) {
//console.assert(2 * BASE * BASE < MAX_INT);
var l = a.length,
r = createArray(l + l),
base = BASE,
product, carry, i, a_i, a_j;
for (i = 0; i < l; i++) {
a_i = a[i];
carry = 0 - a_i * a_i;
for (var j = i; j < l; j++) {
a_j = a[j];
product = 2 * (a_i * a_j) + r[i + j] + carry;
carry = Math.floor(product / base);
r[i + j] = product - carry * base;
}
r[i + l] = carry;
}
trim(r);
return r;
}
BigInteger.prototype.square = function () {
return new BigInteger(square(this.value), false);
};
SmallInteger.prototype.square = function () {
var value = this.value * this.value;
if (isPrecise(value)) return new SmallInteger(value);
return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
};
NativeBigInt.prototype.square = function (v) {
return new NativeBigInt(this.value * this.value);
}
function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
var a_l = a.length,
b_l = b.length,
base = BASE,
result = createArray(b.length),
divisorMostSignificantDigit = b[b_l - 1],
// normalization
lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
remainder = multiplySmall(a, lambda),
divisor = multiplySmall(b, lambda),
quotientDigit, shift, carry, borrow, i, l, q;
if (remainder.length <= a_l) remainder.push(0);
divisor.push(0);
divisorMostSignificantDigit = divisor[b_l - 1];
for (shift = a_l - b_l; shift >= 0; shift--) {
quotientDigit = base - 1;
if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
}
// quotientDigit <= base - 1
carry = 0;
borrow = 0;
l = divisor.length;
for (i = 0; i < l; i++) {
carry += quotientDigit * divisor[i];
q = Math.floor(carry / base);
borrow += remainder[shift + i] - (carry - q * base);
carry = q;
if (borrow < 0) {
remainder[shift + i] = borrow + base;
borrow = -1;
} else {
remainder[shift + i] = borrow;
borrow = 0;
}
}
while (borrow !== 0) {
quotientDigit -= 1;
carry = 0;
for (i = 0; i < l; i++) {
carry += remainder[shift + i] - base + divisor[i];
if (carry < 0) {
remainder[shift + i] = carry + base;
carry = 0;
} else {
remainder[shift + i] = carry;
carry = 1;
}
}
borrow += carry;
}
result[shift] = quotientDigit;
}
// denormalization
remainder = divModSmall(remainder, lambda)[0];
return [arrayToSmall(result), arrayToSmall(remainder)];
}
function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
// Performs faster than divMod1 on larger input sizes.
var a_l = a.length,
b_l = b.length,
result = [],
part = [],
base = BASE,
guess, xlen, highx, highy, check;
while (a_l) {
part.unshift(a[--a_l]);
trim(part);
if (compareAbs(part, b) < 0) {
result.push(0);
continue;
}
xlen = part.length;
highx = part[xlen - 1] * base + part[xlen - 2];
highy = b[b_l - 1] * base + b[b_l - 2];
if (xlen > b_l) {
highx = (highx + 1) * base;
}
guess = Math.ceil(highx / highy);
do {
check = multiplySmall(b, guess);
if (compareAbs(check, part) <= 0) break;
guess--;
} while (guess);
result.push(guess);
part = subtract(part, check);
}
result.reverse();
return [arrayToSmall(result), arrayToSmall(part)];
}
function divModSmall(value, lambda) {
var length = value.length,
quotient = createArray(length),
base = BASE,
i, q, remainder, divisor;
remainder = 0;
for (i = length - 1; i >= 0; --i) {
divisor = remainder * base + value[i];
q = truncate(divisor / lambda);
remainder = divisor - q * lambda;
quotient[i] = q | 0;
}
return [quotient, remainder | 0];
}
function divModAny(self, v) {
var value, n = parseValue(v);
if (supportsNativeBigInt) {
return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];
}
var a = self.value, b = n.value;
var quotient;
if (b === 0) throw new Error("Cannot divide by zero");
if (self.isSmall) {
if (n.isSmall) {
return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
}
return [Integer[0], self];
}
if (n.isSmall) {
if (b === 1) return [self, Integer[0]];
if (b == -1) return [self.negate(), Integer[0]];
var abs = Math.abs(b);
if (abs < BASE) {
value = divModSmall(a, abs);
quotient = arrayToSmall(value[0]);
var remainder = value[1];
if (self.sign) remainder = -remainder;
if (typeof quotient === "number") {
if (self.sign !== n.sign) quotient = -quotient;
return [new SmallInteger(quotient), new SmallInteger(remainder)];
}
return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
}
b = smallToArray(abs);
}
var comparison = compareAbs(a, b);
if (comparison === -1) return [Integer[0], self];
if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
// divMod1 is faster on smaller input sizes
if (a.length + b.length <= 200)
value = divMod1(a, b);
else value = divMod2(a, b);
quotient = value[0];
var qSign = self.sign !== n.sign,
mod = value[1],
mSign = self.sign;
if (typeof quotient === "number") {
if (qSign) quotient = -quotient;
quotient = new SmallInteger(quotient);
} else quotient = new BigInteger(quotient, qSign);
if (typeof mod === "number") {
if (mSign) mod = -mod;
mod = new SmallInteger(mod);
} else mod = new BigInteger(mod, mSign);
return [quotient, mod];
}
BigInteger.prototype.divmod = function (v) {
var result = divModAny(this, v);
return {
quotient: result[0],
remainder: result[1]
};
};
NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
BigInteger.prototype.divide = function (v) {
return divModAny(this, v)[0];
};
NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {
return new NativeBigInt(this.value / parseValue(v).value);
};
SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
BigInteger.prototype.mod = function (v) {
return divModAny(this, v)[1];
};
NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {
return new NativeBigInt(this.value % parseValue(v).value);
};
SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
BigInteger.prototype.pow = function (v) {
var n = parseValue(v),
a = this.value,
b = n.value,
value, x, y;
if (b === 0) return Integer[1];
if (a === 0) return Integer[0];
if (a === 1) return Integer[1];
if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
if (n.sign) {
return Integer[0];
}
if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
if (this.isSmall) {
if (isPrecise(value = Math.pow(a, b)))
return new SmallInteger(truncate(value));
}
x = this;
y = Integer[1];
while (true) {
if (b & 1 === 1) {
y = y.times(x);
--b;
}
if (b === 0) break;
b /= 2;
x = x.square();
}
return y;
};
SmallInteger.prototype.pow = BigInteger.prototype.pow;
NativeBigInt.prototype.pow = function (v) {
var n = parseValue(v);
var a = this.value, b = n.value;
var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
if (b === _0) return Integer[1];
if (a === _0) return Integer[0];
if (a === _1) return Integer[1];
if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];
if (n.isNegative()) return new NativeBigInt(_0);
var x = this;
var y = Integer[1];
while (true) {
if ((b & _1) === _1) {
y = y.times(x);
--b;
}
if (b === _0) break;
b /= _2;
x = x.square();
}
return y;
}
BigInteger.prototype.modPow = function (exp, mod) {
exp = parseValue(exp);
mod = parseValue(mod);
if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
var r = Integer[1],
base = this.mod(mod);
if (exp.isNegative()) {
exp = exp.multiply(Integer[-1]);
base = base.modInv(mod);
}
while (exp.isPositive()) {
if (base.isZero()) return Integer[0];
if (exp.isOdd()) r = r.multiply(base).mod(mod);
exp = exp.divide(2);
base = base.square().mod(mod);
}
return r;
};
NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
function compareAbs(a, b) {
if (a.length !== b.length) {
return a.length > b.length ? 1 : -1;
}
for (var i = a.length - 1; i >= 0; i--) {
if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
}
return 0;
}
BigInteger.prototype.compareAbs = function (v) {
var n = parseValue(v),
a = this.value,
b = n.value;
if (n.isSmall) return 1;
return compareAbs(a, b);
};
SmallInteger.prototype.compareAbs = function (v) {
var n = parseValue(v),
a = Math.abs(this.value),
b = n.value;
if (n.isSmall) {
b = Math.abs(b);
return a === b ? 0 : a > b ? 1 : -1;
}
return -1;
};
NativeBigInt.prototype.compareAbs = function (v) {
var a = this.value;
var b = parseValue(v).value;
a = a >= 0 ? a : -a;
b = b >= 0 ? b : -b;
return a === b ? 0 : a > b ? 1 : -1;
}
BigInteger.prototype.compare = function (v) {
// See discussion about comparison with Infinity:
// https://github.com/peterolson/BigInteger.js/issues/61
if (v === Infinity) {
return -1;
}
if (v === -Infinity) {
return 1;
}
var n = parseValue(v),
a = this.value,
b = n.value;
if (this.sign !== n.sign) {
return n.sign ? 1 : -1;
}
if (n.isSmall) {
return this.sign ? -1 : 1;
}
return compareAbs(a, b) * (this.sign ? -1 : 1);
};
BigInteger.prototype.compareTo = BigInteger.prototype.compare;
SmallInteger.prototype.compare = function (v) {
if (v === Infinity) {
return -1;
}
if (v === -Infinity) {
return 1;
}
var n = parseValue(v),
a = this.value,
b = n.value;
if (n.isSmall) {
return a == b ? 0 : a > b ? 1 : -1;
}
if (a < 0 !== n.sign) {
return a < 0 ? -1 : 1;
}
return a < 0 ? 1 : -1;
};
SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
NativeBigInt.prototype.compare = function (v) {
if (v === Infinity) {
return -1;
}
if (v === -Infinity) {
return 1;
}
var a = this.value;
var b = parseValue(v).value;
return a === b ? 0 : a > b ? 1 : -1;
}
NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
BigInteger.prototype.equals = function (v) {
return this.compare(v) === 0;
};
NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
BigInteger.prototype.notEquals = function (v) {
return this.compare(v) !== 0;
};
NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
BigInteger.prototype.greater = function (v) {
return this.compare(v) > 0;
};
NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
BigInteger.prototype.lesser = function (v) {
return this.compare(v) < 0;
};
NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
BigInteger.prototype.greaterOrEquals = function (v) {
return this.compare(v) >= 0;
};
NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
BigInteger.prototype.lesserOrEquals = function (v) {
return this.compare(v) <= 0;
};
NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
BigInteger.prototype.isEven = function () {
return (this.value[0] & 1) === 0;
};
SmallInteger.prototype.isEven = function () {
return (this.value & 1) === 0;
};
NativeBigInt.prototype.isEven = function () {
return (this.value & BigInt(1)) === BigInt(0);
}
BigInteger.prototype.isOdd = function () {
return (this.value[0] & 1) === 1;
};
SmallInteger.prototype.isOdd = function () {
return (this.value & 1) === 1;
};
NativeBigInt.prototype.isOdd = function () {
return (this.value & BigInt(1)) === BigInt(1);
}
BigInteger.prototype.isPositive = function () {
return !this.sign;
};
SmallInteger.prototype.isPositive = function () {
return this.value > 0;
};
NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
BigInteger.prototype.isNegative = function () {
return this.sign;
};
SmallInteger.prototype.isNegative = function () {
return this.value < 0;
};
NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
BigInteger.prototype.isUnit = function () {
return false;
};
SmallInteger.prototype.isUnit = function () {
return Math.abs(this.value) === 1;
};
NativeBigInt.prototype.isUnit = function () {
return this.abs().value === BigInt(1);
}
BigInteger.prototype.isZero = function () {
return false;
};
SmallInteger.prototype.isZero = function () {
return this.value === 0;
};
NativeBigInt.prototype.isZero = function () {
return this.value === BigInt(0);
}
BigInteger.prototype.isDivisibleBy = function (v) {
var n = parseValue(v);
if (n.isZero()) return false;
if (n.isUnit()) return true;
if (n.compareAbs(2) === 0) return this.isEven();
return this.mod(n).isZero();
};
NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
function isBasicPrime(v) {
var n = v.abs();
if (n.isUnit()) return false;
if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
if (n.lesser(49)) return true;
// we don't know if it's prime: let the other functions figure it out
}
function millerRabinTest(n, a) {
var nPrev = n.prev(),
b = nPrev,
r = 0,
d, t, i, x;
while (b.isEven()) b = b.divide(2), r++;
next: for (i = 0; i < a.length; i++) {
if (n.lesser(a[i])) continue;
x = bigInt(a[i]).modPow(b, n);
if (x.isUnit() || x.equals(nPrev)) continue;
for (d = r - 1; d != 0; d--) {
x = x.square().mod(n);
if (x.isUnit()) return false;
if (x.equals(nPrev)) continue next;
}
return false;
}
return true;
}
// Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
BigInteger.prototype.isPrime = function (strict) {
var isPrime = isBasicPrime(this);
if (isPrime !== undefined) return isPrime;
var n = this.abs();
var bits = n.bitLength();
if (bits <= 64)
return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
var logN = Math.log(2) * bits.toJSNumber();
var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
for (var a = [], i = 0; i < t; i++) {
a.push(bigInt(i + 2));
}
return millerRabinTest(n, a);
};
NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
BigInteger.prototype.isProbablePrime = function (iterations, rng) {
var isPrime = isBasicPrime(this);
if (isPrime !== undefined) return isPrime;
var n = this.abs();
var t = iterations === undefined ? 5 : iterations;
for (var a = [], i = 0; i < t; i++) {
a.push(bigInt.randBetween(2, n.minus(2), rng));
}
return millerRabinTest(n, a);
};
NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
BigInteger.prototype.modInv = function (n) {
var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
while (!newR.isZero()) {
q = r.divide(newR);
lastT = t;
lastR = r;
t = newT;
r = newR;
newT = lastT.subtract(q.multiply(newT));
newR = lastR.subtract(q.multiply(newR));
}
if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
if (t.compare(0) === -1) {
t = t.add(n);
}
if (this.isNegative()) {
return t.negate();
}
return t;
};
NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
BigInteger.prototype.next = function () {
var value = this.value;
if (this.sign) {
return subtractSmall(value, 1, this.sign);
}
return new BigInteger(addSmall(value, 1), this.sign);
};
SmallInteger.prototype.next = function () {
var value = this.value;
if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
return new BigInteger(MAX_INT_ARR, false);
};
NativeBigInt.prototype.next = function () {
return new NativeBigInt(this.value + BigInt(1));
}
BigInteger.prototype.prev = function () {
var value = this.value;
if (this.sign) {
return new BigInteger(addSmall(value, 1), true);
}
return subtractSmall(value, 1, this.sign);
};
SmallInteger.prototype.prev = function () {
var value = this.value;
if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
return new BigInteger(MAX_INT_ARR, true);
};
NativeBigInt.prototype.prev = function () {
return new NativeBigInt(this.value - BigInt(1));
}
var powersOfTwo = [1];
while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
function shift_isSmall(n) {
return Math.abs(n) <= BASE;
}
BigInteger.prototype.shiftLeft = function (v) {
var n = parseValue(v).toJSNumber();
if (!shift_isSmall(n)) {
throw new Error(String(n) + " is too large for shifting.");
}
if (n < 0) return this.shiftRight(-n);
var result = this;
if (result.isZero()) return result;
while (n >= powers2Length) {
result = result.multiply(highestPower2);
n -= powers2Length - 1;
}
return result.multiply(powersOfTwo[n]);
};
NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
BigInteger.prototype.shiftRight = function (v) {
var remQuo;
var n = parseValue(v).toJSNumber();
if (!shift_isSmall(n)) {
throw new Error(String(n) + " is too large for shifting.");
}
if (n < 0) return this.shiftLeft(-n);
var result = this;
while (n >= powers2Length) {
if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
remQuo = divModAny(result, highestPower2);
result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
n -= powers2Length - 1;
}
remQuo = divModAny(result, powersOfTwo[n]);
return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
};
NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
function bitwise(x, y, fn) {
y = parseValue(y);
var xSign = x.isNegative(), ySign = y.isNegative();
var xRem = xSign ? x.not() : x,
yRem = ySign ? y.not() : y;
var xDigit = 0, yDigit = 0;
var xDivMod = null, yDivMod = null;
var result = [];
while (!xRem.isZero() || !yRem.isZero()) {
xDivMod = divModAny(xRem, highestPower2);
xDigit = xDivMod[1].toJSNumber();
if (xSign) {
xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
}
yDivMod = divModAny(yRem, highestPower2);
yDigit = yDivMod[1].toJSNumber();
if (ySign) {
yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
}
xRem = xDivMod[0];
yRem = yDivMod[0];
result.push(fn(xDigit, yDigit));
}
var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
for (var i = result.length - 1; i >= 0; i -= 1) {
sum = sum.multiply(highestPower2).add(bigInt(result[i]));
}
return sum;
}
BigInteger.prototype.not = function () {
return this.negate().prev();
};
NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
BigInteger.prototype.and = function (n) {
return bitwise(this, n, function (a, b) { return a & b; });
};
NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
BigInteger.prototype.or = function (n) {
return bitwise(this, n, function (a, b) { return a | b; });
};
NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
BigInteger.prototype.xor = function (n) {
return bitwise(this, n, function (a, b) { return a ^ b; });
};
NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
function roughLOB(n) { // get lowestOneBit (rough)
// SmallInteger: return Min(lowestOneBit(n), 1 << 30)
// BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
var v = n.value,
x = typeof v === "number" ? v | LOBMASK_I :
typeof v === "bigint" ? v | BigInt(LOBMASK_I) :
v[0] + v[1] * BASE | LOBMASK_BI;
return x & -x;
}
function integerLogarithm(value, base) {
if (base.compareTo(value) <= 0) {
var tmp = integerLogarithm(value, base.square(base));
var p = tmp.p;
var e = tmp.e;
var t = p.multiply(base);
return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
}
return { p: bigInt(1), e: 0 };
}
BigInteger.prototype.bitLength = function () {
var n = this;
if (n.compareTo(bigInt(0)) < 0) {
n = n.negate().subtract(bigInt(1));
}
if (n.compareTo(bigInt(0)) === 0) {
return bigInt(0);
}
return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
}
NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
function max(a, b) {
a = parseValue(a);
b = parseValue(b);
return a.greater(b) ? a : b;
}
function min(a, b) {
a = parseValue(a);
b = parseValue(b);
return a.lesser(b) ? a : b;
}
function gcd(a, b) {
a = parseValue(a).abs();
b = parseValue(b).abs();
if (a.equals(b)) return a;
if (a.isZero()) return b;
if (b.isZero()) return a;
var c = Integer[1], d, t;
while (a.isEven() && b.isEven()) {
d = min(roughLOB(a), roughLOB(b));
a = a.divide(d);
b = b.divide(d);
c = c.multiply(d);
}
while (a.isEven()) {
a = a.divide(roughLOB(a));
}
do {
while (b.isEven()) {
b = b.divide(roughLOB(b));
}
if (a.greater(b)) {
t = b; b = a; a = t;
}
b = b.subtract(a);
} while (!b.isZero());
return c.isUnit() ? a : a.multiply(c);
}
function lcm(a, b) {
a = parseValue(a).abs();
b = parseValue(b).abs();
return a.divide(gcd(a, b)).multiply(b);
}
function randBetween(a, b, rng) {
a = parseValue(a);
b = parseValue(b);
var usedRNG = rng || Math.random;
var low = min(a, b), high = max(a, b);
var range = high.subtract(low).add(1);
if (range.isSmall) return low.add(Math.floor(usedRNG() * range));
var digits = toBase(range, BASE).value;
var result = [], restricted = true;
for (var i = 0; i < digits.length; i++) {
var top = restricted ? digits[i] : BASE;
var digit = truncate(usedRNG() * top);
result.push(digit);
if (digit < top) restricted = false;
}
return low.add(Integer.fromArray(result, BASE, false));
}
var parseBase = function (text, base, alphabet, caseSensitive) {
alphabet = alphabet || DEFAULT_ALPHABET;
text = String(text);
if (!caseSensitive) {
text = text.toLowerCase();
alphabet = alphabet.toLowerCase();
}
var length = text.length;
var i;
var absBase = Math.abs(base);
var alphabetValues = {};
for (i = 0; i < alphabet.length; i++) {
alphabetValues[alphabet[i]] = i;
}
for (i = 0; i < length; i++) {
var c = text[i];
if (c === "-") continue;
if (c in alphabetValues) {
if (alphabetValues[c] >= absBase) {
if (c === "1" && absBase === 1) continue;
throw new Error(c + " is not a valid digit in base " + base + ".");
}
}
}
base = parseValue(base);
var digits = [];
var isNegative = text[0] === "-";
for (i = isNegative ? 1 : 0; i < text.length; i++) {
var c = text[i];
if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));
else if (c === "<") {
var start = i;
do { i++; } while (text[i] !== ">" && i < text.length);
digits.push(parseValue(text.slice(start + 1, i)));
}
else throw new Error(c + " is not a valid character");
}
return parseBaseFromArray(digits, base, isNegative);
};
function parseBaseFromArray(digits, base, isNegative) {
var val = Integer[0], pow = Integer[1], i;
for (i = digits.length - 1; i >= 0; i--) {
val = val.add(digits[i].times(pow));
pow = pow.times(base);
}
return isNegative ? val.negate() : val;
}
function stringify(digit, alphabet) {
alphabet = alphabet || DEFAULT_ALPHABET;
if (digit < alphabet.length) {
return alphabet[digit];
}
return "<" + digit + ">";
}
function toBase(n, base) {
base = bigInt(base);
if (base.isZero()) {
if (n.isZero()) return { value: [0], isNegative: false };
throw new Error("Cannot convert nonzero numbers to base 0.");
}
if (base.equals(-1)) {
if (n.isZero()) return { value: [0], isNegative: false };
if (n.isNegative())
return {
value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))
.map(Array.prototype.valueOf, [1, 0])
),
isNegative: false
};
var arr = Array.apply(null, Array(n.toJSNumber() - 1))
.map(Array.prototype.valueOf, [0, 1]);
arr.unshift([1]);
return {
value: [].concat.apply([], arr),
isNegative: false
};
}
var neg = false;
if (n.isNegative() && base.isPositive()) {
neg = true;
n = n.abs();
}
if (base.isUnit()) {
if (n.isZero()) return { value: [0], isNegative: false };
return {
value: Array.apply(null, Array(n.toJSNumber()))
.map(Number.prototype.valueOf, 1),
isNegative: neg
};
}
var out = [];
var left = n, divmod;
while (left.isNegative() || left.compareAbs(base) >= 0) {
divmod = left.divmod(base);
left = divmod.quotient;
var digit = divmod.remainder;
if (digit.isNegative()) {
digit = base.minus(digit).abs();
left = left.next();
}
out.push(digit.toJSNumber());
}
out.push(left.toJSNumber());
return { value: out.reverse(), isNegative: neg };
}
function toBaseString(n, base, alphabet) {
var arr = toBase(n, base);
return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {
return stringify(x, alphabet);
}).join('');
}
BigInteger.prototype.toArray = function (radix) {
return toBase(this, radix);
};
SmallInteger.prototype.toArray = function (radix) {
return toBase(this, radix);
};
NativeBigInt.prototype.toArray = function (radix) {
return toBase(this, radix);
};
BigInteger.prototype.toString = function (radix, alphabet) {
if (radix === undefined) radix = 10;
if (radix !== 10) return toBaseString(this, radix, alphabet);
var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
while (--l >= 0) {
digit = String(v[l]);
str += zeros.slice(digit.length) + digit;
}
var sign = this.sign ? "-" : "";
return sign + str;
};
SmallInteger.prototype.toString = function (radix, alphabet) {
if (radix === undefined) radix = 10;
if (radix != 10) return toBaseString(this, radix, alphabet);
return String(this.value);
};
NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }
BigInteger.prototype.valueOf = function () {
return parseInt(this.toString(), 10);
};
BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
SmallInteger.prototype.valueOf = function () {
return this.value;
};
SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {
return parseInt(this.toString(), 10);
}
function parseStringValue(v) {
if (isPrecise(+v)) {
var x = +v;
if (x === truncate(x))
return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
throw new Error("Invalid integer: " + v);
}
var sign = v[0] === "-";
if (sign) v = v.slice(1);
var split = v.split(/e/i);
if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
if (split.length === 2) {
var exp = split[1];
if (exp[0] === "+") exp = exp.slice(1);
exp = +exp;
if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
var text = split[0];
var decimalPlace = text.indexOf(".");
if (decimalPlace >= 0) {
exp -= text.length - decimalPlace - 1;
text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
}
if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
text += (new Array(exp + 1)).join("0");
v = text;
}
var isValid = /^([0-9][0-9]*)$/.test(v);
if (!isValid) throw new Error("Invalid integer: " + v);
if (supportsNativeBigInt) {
return new NativeBigInt(BigInt(sign ? "-" + v : v));
}
var r = [], max = v.length, l = LOG_BASE, min = max - l;
while (max > 0) {
r.push(+v.slice(min, max));
min -= l;
if (min < 0) min = 0;
max -= l;
}
trim(r);
return new BigInteger(r, sign);
}
function parseNumberValue(v) {
if (supportsNativeBigInt) {
return new NativeBigInt(BigInt(v));
}
if (isPrecise(v)) {
if (v !== truncate(v)) throw new Error(v + " is not an integer.");
return new SmallInteger(v);
}
return parseStringValue(v.toString());
}
function parseValue(v) {
if (typeof v === "number") {
return parseNumberValue(v);
}
if (typeof v === "string") {
return parseStringValue(v);
}
if (typeof v === "bigint") {
return new NativeBigInt(v);
}
return v;
}
// Pre-define numbers in range [-999,999]
for (var i = 0; i < 1000; i++) {
Integer[i] = parseValue(i);
if (i > 0) Integer[-i] = parseValue(-i);
}
// Backwards compatibility
Integer.one = Integer[1];
Integer.zero = Integer[0];
Integer.minusOne = Integer[-1];
Integer.max = max;
Integer.min = min;
Integer.gcd = gcd;
Integer.lcm = lcm;
Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };
Integer.randBetween = randBetween;
Integer.fromArray = function (digits, base, isNegative) {
return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
};
return Integer;
})();
// Node.js check
if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
module.exports = bigInt;
}
//amd check
if (typeof define === "function" && define.amd) {
define( function () {
return bigInt;
});
}
},{}],60:[function(require,module,exports){
module.exports = function(haystack, needle, comparator, low, high) {
var mid, cmp;
if(low === undefined)
low = 0;
else {
low = low|0;
if(low < 0 || low >= haystack.length)
throw new RangeError("invalid lower bound");
}
if(high === undefined)
high = haystack.length - 1;
else {
high = high|0;
if(high < low || high >= haystack.length)
throw new RangeError("invalid upper bound");
}
while(low <= high) {
// The naive `low + high >>> 1` could fail for array lengths > 2**31
// because `>>>` converts its operands to int32. `low + (high - low >>> 1)`
// works for array lengths <= 2**32-1 which is also Javascript's max array
// length.
mid = low + ((high - low) >>> 1);
cmp = +comparator(haystack[mid], needle, mid, haystack);
// Too low.
if(cmp < 0.0)
low = mid + 1;
// Too high.
else if(cmp > 0.0)
high = mid - 1;
// Key found.
else
return mid;
}
// Key not found.
return ~low;
}
},{}],61:[function(require,module,exports){
},{}],62:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
},{"base64-js":58,"ieee754":63}],63:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],64:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],65:[function(require,module,exports){
module.exports = Long;
/**
* wasm optimizations, to do native i64 multiplication and divide
*/
var wasm = null;
try {
wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11
])), {}).exports;
} catch (e) {
// no wasm support :(
}
/**
* Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
* See the from* functions below for more convenient ways of constructing Longs.
* @exports Long
* @class A Long class for representing a 64 bit two's-complement integer value.
* @param {number} low The low (signed) 32 bits of the long
* @param {number} high The high (signed) 32 bits of the long
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @constructor
*/
function Long(low, high, unsigned) {
/**
* The low 32 bits as a signed value.
* @type {number}
*/
this.low = low | 0;
/**
* The high 32 bits as a signed value.
* @type {number}
*/
this.high = high | 0;
/**
* Whether unsigned or not.
* @type {boolean}
*/
this.unsigned = !!unsigned;
}
// The internal representation of a long is the two given signed, 32-bit values.
// We use 32-bit pieces because these are the size of integers on which
// Javascript performs bit-operations. For operations like addition and
// multiplication, we split each number into 16 bit pieces, which can easily be
// multiplied within Javascript's floating-point representation without overflow
// or change in sign.
//
// In the algorithms below, we frequently reduce the negative case to the
// positive case by negating the input(s) and then post-processing the result.
// Note that we must ALWAYS check specially whether those values are MIN_VALUE
// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
// a positive number, it overflows back into a negative). Not handling this
// case would often result in infinite recursion.
//
// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
// methods on which they depend.
/**
* An indicator used to reliably determine if an object is a Long or not.
* @type {boolean}
* @const
* @private
*/
Long.prototype.__isLong__;
Object.defineProperty(Long.prototype, "__isLong__", { value: true });
/**
* @function
* @param {*} obj Object
* @returns {boolean}
* @inner
*/
function isLong(obj) {
return (obj && obj["__isLong__"]) === true;
}
/**
* Tests if the specified object is a Long.
* @function
* @param {*} obj Object
* @returns {boolean}
*/
Long.isLong = isLong;
/**
* A cache of the Long representations of small integer values.
* @type {!Object}
* @inner
*/
var INT_CACHE = {};
/**
* A cache of the Long representations of small unsigned integer values.
* @type {!Object}
* @inner
*/
var UINT_CACHE = {};
/**
* @param {number} value
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromInt(value, unsigned) {
var obj, cachedObj, cache;
if (unsigned) {
value >>>= 0;
if (cache = (0 <= value && value < 256)) {
cachedObj = UINT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
if (cache)
UINT_CACHE[value] = obj;
return obj;
} else {
value |= 0;
if (cache = (-128 <= value && value < 128)) {
cachedObj = INT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = fromBits(value, value < 0 ? -1 : 0, false);
if (cache)
INT_CACHE[value] = obj;
return obj;
}
}
/**
* Returns a Long representing the given 32 bit integer value.
* @function
* @param {number} value The 32 bit integer in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromInt = fromInt;
/**
* @param {number} value
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromNumber(value, unsigned) {
if (isNaN(value))
return unsigned ? UZERO : ZERO;
if (unsigned) {
if (value < 0)
return UZERO;
if (value >= TWO_PWR_64_DBL)
return MAX_UNSIGNED_VALUE;
} else {
if (value <= -TWO_PWR_63_DBL)
return MIN_VALUE;
if (value + 1 >= TWO_PWR_63_DBL)
return MAX_VALUE;
}
if (value < 0)
return fromNumber(-value, unsigned).neg();
return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
}
/**
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
* @function
* @param {number} value The number in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromNumber = fromNumber;
/**
* @param {number} lowBits
* @param {number} highBits
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromBits(lowBits, highBits, unsigned) {
return new Long(lowBits, highBits, unsigned);
}
/**
* Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
* assumed to use 32 bits.
* @function
* @param {number} lowBits The low 32 bits
* @param {number} highBits The high 32 bits
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long} The corresponding Long value
*/
Long.fromBits = fromBits;
/**
* @function
* @param {number} base
* @param {number} exponent
* @returns {number}
* @inner
*/
var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
/**
* @param {string} str
* @param {(boolean|number)=} unsigned
* @param {number=} radix
* @returns {!Long}
* @inner
*/
function fromString(str, unsigned, radix) {
if (str.length === 0)
throw Error('empty string');
if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
return ZERO;
if (typeof unsigned === 'number') {
// For goog.math.long compatibility
radix = unsigned,
unsigned = false;
} else {
unsigned = !! unsigned;
}
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw RangeError('radix');
var p;
if ((p = str.indexOf('-')) > 0)
throw Error('interior hyphen');
else if (p === 0) {
return fromString(str.substring(1), unsigned, radix).neg();
}
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = fromNumber(pow_dbl(radix, 8));
var result = ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i),
value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = fromNumber(pow_dbl(radix, size));
result = result.mul(power).add(fromNumber(value));
} else {
result = result.mul(radixToPower);
result = result.add(fromNumber(value));
}
}
result.unsigned = unsigned;
return result;
}
/**
* Returns a Long representation of the given string, written using the specified radix.
* @function
* @param {string} str The textual representation of the Long
* @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed
* @param {number=} radix The radix in which the text is written (2-36), defaults to 10
* @returns {!Long} The corresponding Long value
*/
Long.fromString = fromString;
/**
* @function
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
* @param {boolean=} unsigned
* @returns {!Long}
* @inner
*/
function fromValue(val, unsigned) {
if (typeof val === 'number')
return fromNumber(val, unsigned);
if (typeof val === 'string')
return fromString(val, unsigned);
// Throws for non-objects, converts non-instanceof Long:
return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
}
/**
* Converts the specified value to a Long using the appropriate from* function for its type.
* @function
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {!Long}
*/
Long.fromValue = fromValue;
// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
// no runtime penalty for these.
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_16_DBL = 1 << 16;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_24_DBL = 1 << 24;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
/**
* @type {!Long}
* @const
* @inner
*/
var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
/**
* @type {!Long}
* @inner
*/
var ZERO = fromInt(0);
/**
* Signed zero.
* @type {!Long}
*/
Long.ZERO = ZERO;
/**
* @type {!Long}
* @inner
*/
var UZERO = fromInt(0, true);
/**
* Unsigned zero.
* @type {!Long}
*/
Long.UZERO = UZERO;
/**
* @type {!Long}
* @inner
*/
var ONE = fromInt(1);
/**
* Signed one.
* @type {!Long}
*/
Long.ONE = ONE;
/**
* @type {!Long}
* @inner
*/
var UONE = fromInt(1, true);
/**
* Unsigned one.
* @type {!Long}
*/
Long.UONE = UONE;
/**
* @type {!Long}
* @inner
*/
var NEG_ONE = fromInt(-1);
/**
* Signed negative one.
* @type {!Long}
*/
Long.NEG_ONE = NEG_ONE;
/**
* @type {!Long}
* @inner
*/
var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
/**
* Maximum signed value.
* @type {!Long}
*/
Long.MAX_VALUE = MAX_VALUE;
/**
* @type {!Long}
* @inner
*/
var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
/**
* Maximum unsigned value.
* @type {!Long}
*/
Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
/**
* @type {!Long}
* @inner
*/
var MIN_VALUE = fromBits(0, 0x80000000|0, false);
/**
* Minimum signed value.
* @type {!Long}
*/
Long.MIN_VALUE = MIN_VALUE;
/**
* @alias Long.prototype
* @inner
*/
var LongPrototype = Long.prototype;
/**
* Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
* @returns {number}
*/
LongPrototype.toInt = function toInt() {
return this.unsigned ? this.low >>> 0 : this.low;
};
/**
* Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
* @returns {number}
*/
LongPrototype.toNumber = function toNumber() {
if (this.unsigned)
return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
};
/**
* Converts the Long to a string written in the specified radix.
* @param {number=} radix Radix (2-36), defaults to 10
* @returns {string}
* @override
* @throws {RangeError} If `radix` is out of range
*/
LongPrototype.toString = function toString(radix) {
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw RangeError('radix');
if (this.isZero())
return '0';
if (this.isNegative()) { // Unsigned Longs are never negative
if (this.eq(MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = fromNumber(radix),
div = this.div(radixLong),
rem1 = div.mul(radixLong).sub(this);
return div.toString(radix) + rem1.toInt().toString(radix);
} else
return '-' + this.neg().toString(radix);
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
rem = this;
var result = '';
while (true) {
var remDiv = rem.div(radixToPower),
intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero())
return digits + result;
else {
while (digits.length < 6)
digits = '0' + digits;
result = '' + digits + result;
}
}
};
/**
* Gets the high 32 bits as a signed integer.
* @returns {number} Signed high bits
*/
LongPrototype.getHighBits = function getHighBits() {
return this.high;
};
/**
* Gets the high 32 bits as an unsigned integer.
* @returns {number} Unsigned high bits
*/
LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
return this.high >>> 0;
};
/**
* Gets the low 32 bits as a signed integer.
* @returns {number} Signed low bits
*/
LongPrototype.getLowBits = function getLowBits() {
return this.low;
};
/**
* Gets the low 32 bits as an unsigned integer.
* @returns {number} Unsigned low bits
*/
LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
return this.low >>> 0;
};
/**
* Gets the number of bits needed to represent the absolute value of this Long.
* @returns {number}
*/
LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
if (this.isNegative()) // Unsigned Longs are never negative
return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
var val = this.high != 0 ? this.high : this.low;
for (var bit = 31; bit > 0; bit--)
if ((val & (1 << bit)) != 0)
break;
return this.high != 0 ? bit + 33 : bit + 1;
};
/**
* Tests if this Long's value equals zero.
* @returns {boolean}
*/
LongPrototype.isZero = function isZero() {
return this.high === 0 && this.low === 0;
};
/**
* Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.
* @returns {boolean}
*/
LongPrototype.eqz = LongPrototype.isZero;
/**
* Tests if this Long's value is negative.
* @returns {boolean}
*/
LongPrototype.isNegative = function isNegative() {
return !this.unsigned && this.high < 0;
};
/**
* Tests if this Long's value is positive.
* @returns {boolean}
*/
LongPrototype.isPositive = function isPositive() {
return this.unsigned || this.high >= 0;
};
/**
* Tests if this Long's value is odd.
* @returns {boolean}
*/
LongPrototype.isOdd = function isOdd() {
return (this.low & 1) === 1;
};
/**
* Tests if this Long's value is even.
* @returns {boolean}
*/
LongPrototype.isEven = function isEven() {
return (this.low & 1) === 0;
};
/**
* Tests if this Long's value equals the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.equals = function equals(other) {
if (!isLong(other))
other = fromValue(other);
if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
return false;
return this.high === other.high && this.low === other.low;
};
/**
* Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.eq = LongPrototype.equals;
/**
* Tests if this Long's value differs from the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.notEquals = function notEquals(other) {
return !this.eq(/* validates */ other);
};
/**
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.neq = LongPrototype.notEquals;
/**
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.ne = LongPrototype.notEquals;
/**
* Tests if this Long's value is less than the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lessThan = function lessThan(other) {
return this.comp(/* validates */ other) < 0;
};
/**
* Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lt = LongPrototype.lessThan;
/**
* Tests if this Long's value is less than or equal the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
return this.comp(/* validates */ other) <= 0;
};
/**
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.lte = LongPrototype.lessThanOrEqual;
/**
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.le = LongPrototype.lessThanOrEqual;
/**
* Tests if this Long's value is greater than the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.greaterThan = function greaterThan(other) {
return this.comp(/* validates */ other) > 0;
};
/**
* Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.gt = LongPrototype.greaterThan;
/**
* Tests if this Long's value is greater than or equal the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
return this.comp(/* validates */ other) >= 0;
};
/**
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.gte = LongPrototype.greaterThanOrEqual;
/**
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
*/
LongPrototype.ge = LongPrototype.greaterThanOrEqual;
/**
* Compares this Long's value with the specified's.
* @param {!Long|number|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
*/
LongPrototype.compare = function compare(other) {
if (!isLong(other))
other = fromValue(other);
if (this.eq(other))
return 0;
var thisNeg = this.isNegative(),
otherNeg = other.isNegative();
if (thisNeg && !otherNeg)
return -1;
if (!thisNeg && otherNeg)
return 1;
// At this point the sign bits are the same
if (!this.unsigned)
return this.sub(other).isNegative() ? -1 : 1;
// Both are positive if at least one is unsigned
return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
};
/**
* Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
* @function
* @param {!Long|number|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
*/
LongPrototype.comp = LongPrototype.compare;
/**
* Negates this Long's value.
* @returns {!Long} Negated Long
*/
LongPrototype.negate = function negate() {
if (!this.unsigned && this.eq(MIN_VALUE))
return MIN_VALUE;
return this.not().add(ONE);
};
/**
* Negates this Long's value. This is an alias of {@link Long#negate}.
* @function
* @returns {!Long} Negated Long
*/
LongPrototype.neg = LongPrototype.negate;
/**
* Returns the sum of this and the specified Long.
* @param {!Long|number|string} addend Addend
* @returns {!Long} Sum
*/
LongPrototype.add = function add(addend) {
if (!isLong(addend))
addend = fromValue(addend);
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high >>> 16;
var a32 = this.high & 0xFFFF;
var a16 = this.low >>> 16;
var a00 = this.low & 0xFFFF;
var b48 = addend.high >>> 16;
var b32 = addend.high & 0xFFFF;
var b16 = addend.low >>> 16;
var b00 = addend.low & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 + b48;
c48 &= 0xFFFF;
return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the difference of this and the specified Long.
* @param {!Long|number|string} subtrahend Subtrahend
* @returns {!Long} Difference
*/
LongPrototype.subtract = function subtract(subtrahend) {
if (!isLong(subtrahend))
subtrahend = fromValue(subtrahend);
return this.add(subtrahend.neg());
};
/**
* Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
* @function
* @param {!Long|number|string} subtrahend Subtrahend
* @returns {!Long} Difference
*/
LongPrototype.sub = LongPrototype.subtract;
/**
* Returns the product of this and the specified Long.
* @param {!Long|number|string} multiplier Multiplier
* @returns {!Long} Product
*/
LongPrototype.multiply = function multiply(multiplier) {
if (this.isZero())
return ZERO;
if (!isLong(multiplier))
multiplier = fromValue(multiplier);
// use wasm support if present
if (wasm) {
var low = wasm.mul(this.low,
this.high,
multiplier.low,
multiplier.high);
return fromBits(low, wasm.get_high(), this.unsigned);
}
if (multiplier.isZero())
return ZERO;
if (this.eq(MIN_VALUE))
return multiplier.isOdd() ? MIN_VALUE : ZERO;
if (multiplier.eq(MIN_VALUE))
return this.isOdd() ? MIN_VALUE : ZERO;
if (this.isNegative()) {
if (multiplier.isNegative())
return this.neg().mul(multiplier.neg());
else
return this.neg().mul(multiplier).neg();
} else if (multiplier.isNegative())
return this.mul(multiplier.neg()).neg();
// If both longs are small, use float multiplication
if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high >>> 16;
var a32 = this.high & 0xFFFF;
var a16 = this.low >>> 16;
var a00 = this.low & 0xFFFF;
var b48 = multiplier.high >>> 16;
var b32 = multiplier.high & 0xFFFF;
var b16 = multiplier.low >>> 16;
var b00 = multiplier.low & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xFFFF;
return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
* @function
* @param {!Long|number|string} multiplier Multiplier
* @returns {!Long} Product
*/
LongPrototype.mul = LongPrototype.multiply;
/**
* Returns this Long divided by the specified. The result is signed if this Long is signed or
* unsigned if this Long is unsigned.
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Quotient
*/
LongPrototype.divide = function divide(divisor) {
if (!isLong(divisor))
divisor = fromValue(divisor);
if (divisor.isZero())
throw Error('division by zero');
// use wasm support if present
if (wasm) {
// guard against signed division overflow: the largest
// negative number / -1 would be 1 larger than the largest
// positive number, due to two's complement.
if (!this.unsigned &&
this.high === -0x80000000 &&
divisor.low === -1 && divisor.high === -1) {
// be consistent with non-wasm code path
return this;
}
var low = (this.unsigned ? wasm.div_u : wasm.div_s)(
this.low,
this.high,
divisor.low,
divisor.high
);
return fromBits(low, wasm.get_high(), this.unsigned);
}
if (this.isZero())
return this.unsigned ? UZERO : ZERO;
var approx, rem, res;
if (!this.unsigned) {
// This section is only relevant for signed longs and is derived from the
// closure library as a whole.
if (this.eq(MIN_VALUE)) {
if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
else if (divisor.eq(MIN_VALUE))
return ONE;
else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shr(1);
approx = halfThis.div(divisor).shl(1);
if (approx.eq(ZERO)) {
return divisor.isNegative() ? ONE : NEG_ONE;
} else {
rem = this.sub(divisor.mul(approx));
res = approx.add(rem.div(divisor));
return res;
}
}
} else if (divisor.eq(MIN_VALUE))
return this.unsigned ? UZERO : ZERO;
if (this.isNegative()) {
if (divisor.isNegative())
return this.neg().div(divisor.neg());
return this.neg().div(divisor).neg();
} else if (divisor.isNegative())
return this.div(divisor.neg()).neg();
res = ZERO;
} else {
// The algorithm below has not been made for unsigned longs. It's therefore
// required to take special care of the MSB prior to running it.
if (!divisor.unsigned)
divisor = divisor.toUnsigned();
if (divisor.gt(this))
return UZERO;
if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
return UONE;
res = UZERO;
}
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
rem = this;
while (rem.gte(divisor)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2),
delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
approxRes = fromNumber(approx),
approxRem = approxRes.mul(divisor);
while (approxRem.isNegative() || approxRem.gt(rem)) {
approx -= delta;
approxRes = fromNumber(approx, this.unsigned);
approxRem = approxRes.mul(divisor);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero())
approxRes = ONE;
res = res.add(approxRes);
rem = rem.sub(approxRem);
}
return res;
};
/**
* Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Quotient
*/
LongPrototype.div = LongPrototype.divide;
/**
* Returns this Long modulo the specified.
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.modulo = function modulo(divisor) {
if (!isLong(divisor))
divisor = fromValue(divisor);
// use wasm support if present
if (wasm) {
var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(
this.low,
this.high,
divisor.low,
divisor.high
);
return fromBits(low, wasm.get_high(), this.unsigned);
}
return this.sub(this.div(divisor).mul(divisor));
};
/**
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.mod = LongPrototype.modulo;
/**
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
*/
LongPrototype.rem = LongPrototype.modulo;
/**
* Returns the bitwise NOT of this Long.
* @returns {!Long}
*/
LongPrototype.not = function not() {
return fromBits(~this.low, ~this.high, this.unsigned);
};
/**
* Returns the bitwise AND of this Long and the specified.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
*/
LongPrototype.and = function and(other) {
if (!isLong(other))
other = fromValue(other);
return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
};
/**
* Returns the bitwise OR of this Long and the specified.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
*/
LongPrototype.or = function or(other) {
if (!isLong(other))
other = fromValue(other);
return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
};
/**
* Returns the bitwise XOR of this Long and the given one.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
*/
LongPrototype.xor = function xor(other) {
if (!isLong(other))
other = fromValue(other);
return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
};
/**
* Returns this Long with bits shifted to the left by the given amount.
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shiftLeft = function shiftLeft(numBits) {
if (isLong(numBits))
numBits = numBits.toInt();
if ((numBits &= 63) === 0)
return this;
else if (numBits < 32)
return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
else
return fromBits(0, this.low << (numBits - 32), this.unsigned);
};
/**
* Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shl = LongPrototype.shiftLeft;
/**
* Returns this Long with bits arithmetically shifted to the right by the given amount.
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shiftRight = function shiftRight(numBits) {
if (isLong(numBits))
numBits = numBits.toInt();
if ((numBits &= 63) === 0)
return this;
else if (numBits < 32)
return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
else
return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
};
/**
* Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shr = LongPrototype.shiftRight;
/**
* Returns this Long with bits logically shifted to the right by the given amount.
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
if (isLong(numBits))
numBits = numBits.toInt();
numBits &= 63;
if (numBits === 0)
return this;
else {
var high = this.high;
if (numBits < 32) {
var low = this.low;
return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
} else if (numBits === 32)
return fromBits(high, 0, this.unsigned);
else
return fromBits(high >>> (numBits - 32), 0, this.unsigned);
}
};
/**
* Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shru = LongPrototype.shiftRightUnsigned;
/**
* Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
*/
LongPrototype.shr_u = LongPrototype.shiftRightUnsigned;
/**
* Converts this Long to signed.
* @returns {!Long} Signed long
*/
LongPrototype.toSigned = function toSigned() {
if (!this.unsigned)
return this;
return fromBits(this.low, this.high, false);
};
/**
* Converts this Long to unsigned.
* @returns {!Long} Unsigned long
*/
LongPrototype.toUnsigned = function toUnsigned() {
if (this.unsigned)
return this;
return fromBits(this.low, this.high, true);
};
/**
* Converts this Long to its byte representation.
* @param {boolean=} le Whether little or big endian, defaults to big endian
* @returns {!Array.<number>} Byte representation
*/
LongPrototype.toBytes = function toBytes(le) {
return le ? this.toBytesLE() : this.toBytesBE();
};
/**
* Converts this Long to its little endian byte representation.
* @returns {!Array.<number>} Little endian byte representation
*/
LongPrototype.toBytesLE = function toBytesLE() {
var hi = this.high,
lo = this.low;
return [
lo & 0xff,
lo >>> 8 & 0xff,
lo >>> 16 & 0xff,
lo >>> 24 ,
hi & 0xff,
hi >>> 8 & 0xff,
hi >>> 16 & 0xff,
hi >>> 24
];
};
/**
* Converts this Long to its big endian byte representation.
* @returns {!Array.<number>} Big endian byte representation
*/
LongPrototype.toBytesBE = function toBytesBE() {
var hi = this.high,
lo = this.low;
return [
hi >>> 24 ,
hi >>> 16 & 0xff,
hi >>> 8 & 0xff,
hi & 0xff,
lo >>> 24 ,
lo >>> 16 & 0xff,
lo >>> 8 & 0xff,
lo & 0xff
];
};
/**
* Creates a Long from its byte representation.
* @param {!Array.<number>} bytes Byte representation
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @param {boolean=} le Whether little or big endian, defaults to big endian
* @returns {Long} The corresponding Long value
*/
Long.fromBytes = function fromBytes(bytes, unsigned, le) {
return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
};
/**
* Creates a Long from its little endian byte representation.
* @param {!Array.<number>} bytes Little endian byte representation
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {Long} The corresponding Long value
*/
Long.fromBytesLE = function fromBytesLE(bytes, unsigned) {
return new Long(
bytes[0] |
bytes[1] << 8 |
bytes[2] << 16 |
bytes[3] << 24,
bytes[4] |
bytes[5] << 8 |
bytes[6] << 16 |
bytes[7] << 24,
unsigned
);
};
/**
* Creates a Long from its big endian byte representation.
* @param {!Array.<number>} bytes Big endian byte representation
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {Long} The corresponding Long value
*/
Long.fromBytesBE = function fromBytesBE(bytes, unsigned) {
return new Long(
bytes[4] << 24 |
bytes[5] << 16 |
bytes[6] << 8 |
bytes[7],
bytes[0] << 24 |
bytes[1] << 16 |
bytes[2] << 8 |
bytes[3],
unsigned
);
};
},{}],66:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],67:[function(require,module,exports){
// minimal library entry point.
"use strict";
module.exports = require("./src/index-minimal");
},{"./src/index-minimal":68}],68:[function(require,module,exports){
"use strict";
var protobuf = exports;
/**
* Build type, one of `"full"`, `"light"` or `"minimal"`.
* @name build
* @type {string}
* @const
*/
protobuf.build = "minimal";
// Serialization
protobuf.Writer = require("./writer");
protobuf.BufferWriter = require("./writer_buffer");
protobuf.Reader = require("./reader");
protobuf.BufferReader = require("./reader_buffer");
// Utility
protobuf.util = require("./util/minimal");
protobuf.rpc = require("./rpc");
protobuf.roots = require("./roots");
protobuf.configure = configure;
/* istanbul ignore next */
/**
* Reconfigures the library according to the environment.
* @returns {undefined}
*/
function configure() {
protobuf.Reader._configure(protobuf.BufferReader);
protobuf.util._configure();
}
// Set up buffer utility according to the environment
protobuf.Writer._configure(protobuf.BufferWriter);
configure();
},{"./reader":69,"./reader_buffer":70,"./roots":71,"./rpc":72,"./util/minimal":75,"./writer":76,"./writer_buffer":77}],69:[function(require,module,exports){
"use strict";
module.exports = Reader;
var util = require("./util/minimal");
var BufferReader; // cyclic
var LongBits = util.LongBits,
utf8 = util.utf8;
/* istanbul ignore next */
function indexOutOfRange(reader, writeLength) {
return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
}
/**
* Constructs a new reader instance using the specified buffer.
* @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
* @constructor
* @param {Uint8Array} buffer Buffer to read from
*/
function Reader(buffer) {
/**
* Read buffer.
* @type {Uint8Array}
*/
this.buf = buffer;
/**
* Read buffer position.
* @type {number}
*/
this.pos = 0;
/**
* Read buffer length.
* @type {number}
*/
this.len = buffer.length;
}
var create_array = typeof Uint8Array !== "undefined"
? function create_typed_array(buffer) {
if (buffer instanceof Uint8Array || Array.isArray(buffer))
return new Reader(buffer);
throw Error("illegal buffer");
}
/* istanbul ignore next */
: function create_array(buffer) {
if (Array.isArray(buffer))
return new Reader(buffer);
throw Error("illegal buffer");
};
/**
* Creates a new reader using the specified buffer.
* @function
* @param {Uint8Array|Buffer} buffer Buffer to read from
* @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
* @throws {Error} If `buffer` is not a valid buffer
*/
Reader.create = util.Buffer
? function create_buffer_setup(buffer) {
return (Reader.create = function create_buffer(buffer) {
return util.Buffer.isBuffer(buffer)
? new BufferReader(buffer)
/* istanbul ignore next */
: create_array(buffer);
})(buffer);
}
/* istanbul ignore next */
: create_array;
Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
/**
* Reads a varint as an unsigned 32 bit value.
* @function
* @returns {number} Value read
*/
Reader.prototype.uint32 = (function read_uint32_setup() {
var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
return function read_uint32() {
value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;
/* istanbul ignore if */
if ((this.pos += 5) > this.len) {
this.pos = this.len;
throw indexOutOfRange(this, 10);
}
return value;
};
})();
/**
* Reads a varint as a signed 32 bit value.
* @returns {number} Value read
*/
Reader.prototype.int32 = function read_int32() {
return this.uint32() | 0;
};
/**
* Reads a zig-zag encoded varint as a signed 32 bit value.
* @returns {number} Value read
*/
Reader.prototype.sint32 = function read_sint32() {
var value = this.uint32();
return value >>> 1 ^ -(value & 1) | 0;
};
/* eslint-disable no-invalid-this */
function readLongVarint() {
// tends to deopt with local vars for octet etc.
var bits = new LongBits(0, 0);
var i = 0;
if (this.len - this.pos > 4) { // fast route (lo)
for (; i < 4; ++i) {
// 1st..4th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
// 5th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
i = 0;
} else {
for (; i < 3; ++i) {
/* istanbul ignore if */
if (this.pos >= this.len)
throw indexOutOfRange(this);
// 1st..3th
bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
// 4th
bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
return bits;
}
if (this.len - this.pos > 4) { // fast route (hi)
for (; i < 5; ++i) {
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
} else {
for (; i < 5; ++i) {
/* istanbul ignore if */
if (this.pos >= this.len)
throw indexOutOfRange(this);
// 6th..10th
bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
if (this.buf[this.pos++] < 128)
return bits;
}
}
/* istanbul ignore next */
throw Error("invalid varint encoding");
}
/* eslint-enable no-invalid-this */
/**
* Reads a varint as a signed 64 bit value.
* @name Reader#int64
* @function
* @returns {Long} Value read
*/
/**
* Reads a varint as an unsigned 64 bit value.
* @name Reader#uint64
* @function
* @returns {Long} Value read
*/
/**
* Reads a zig-zag encoded varint as a signed 64 bit value.
* @name Reader#sint64
* @function
* @returns {Long} Value read
*/
/**
* Reads a varint as a boolean.
* @returns {boolean} Value read
*/
Reader.prototype.bool = function read_bool() {
return this.uint32() !== 0;
};
function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
return (buf[end - 4]
| buf[end - 3] << 8
| buf[end - 2] << 16
| buf[end - 1] << 24) >>> 0;
}
/**
* Reads fixed 32 bits as an unsigned 32 bit integer.
* @returns {number} Value read
*/
Reader.prototype.fixed32 = function read_fixed32() {
/* istanbul ignore if */
if (this.pos + 4 > this.len)
throw indexOutOfRange(this, 4);
return readFixed32_end(this.buf, this.pos += 4);
};
/**
* Reads fixed 32 bits as a signed 32 bit integer.
* @returns {number} Value read
*/
Reader.prototype.sfixed32 = function read_sfixed32() {
/* istanbul ignore if */
if (this.pos + 4 > this.len)
throw indexOutOfRange(this, 4);
return readFixed32_end(this.buf, this.pos += 4) | 0;
};
/* eslint-disable no-invalid-this */
function readFixed64(/* this: Reader */) {
/* istanbul ignore if */
if (this.pos + 8 > this.len)
throw indexOutOfRange(this, 8);
return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
}
/* eslint-enable no-invalid-this */
/**
* Reads fixed 64 bits.
* @name Reader#fixed64
* @function
* @returns {Long} Value read
*/
/**
* Reads zig-zag encoded fixed 64 bits.
* @name Reader#sfixed64
* @function
* @returns {Long} Value read
*/
/**
* Reads a float (32 bit) as a number.
* @function
* @returns {number} Value read
*/
Reader.prototype.float = function read_float() {
/* istanbul ignore if */
if (this.pos + 4 > this.len)
throw indexOutOfRange(this, 4);
var value = util.float.readFloatLE(this.buf, this.pos);
this.pos += 4;
return value;
};
/**
* Reads a double (64 bit float) as a number.
* @function
* @returns {number} Value read
*/
Reader.prototype.double = function read_double() {
/* istanbul ignore if */
if (this.pos + 8 > this.len)
throw indexOutOfRange(this, 4);
var value = util.float.readDoubleLE(this.buf, this.pos);
this.pos += 8;
return value;
};
/**
* Reads a sequence of bytes preceeded by its length as a varint.
* @returns {Uint8Array} Value read
*/
Reader.prototype.bytes = function read_bytes() {
var length = this.uint32(),
start = this.pos,
end = this.pos + length;
/* istanbul ignore if */
if (end > this.len)
throw indexOutOfRange(this, length);
this.pos += length;
if (Array.isArray(this.buf)) // plain array
return this.buf.slice(start, end);
return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
? new this.buf.constructor(0)
: this._slice.call(this.buf, start, end);
};
/**
* Reads a string preceeded by its byte length as a varint.
* @returns {string} Value read
*/
Reader.prototype.string = function read_string() {
var bytes = this.bytes();
return utf8.read(bytes, 0, bytes.length);
};
/**
* Skips the specified number of bytes if specified, otherwise skips a varint.
* @param {number} [length] Length if known, otherwise a varint is assumed
* @returns {Reader} `this`
*/
Reader.prototype.skip = function skip(length) {
if (typeof length === "number") {
/* istanbul ignore if */
if (this.pos + length > this.len)
throw indexOutOfRange(this, length);
this.pos += length;
} else {
do {
/* istanbul ignore if */
if (this.pos >= this.len)
throw indexOutOfRange(this);
} while (this.buf[this.pos++] & 128);
}
return this;
};
/**
* Skips the next element of the specified wire type.
* @param {number} wireType Wire type received
* @returns {Reader} `this`
*/
Reader.prototype.skipType = function(wireType) {
switch (wireType) {
case 0:
this.skip();
break;
case 1:
this.skip(8);
break;
case 2:
this.skip(this.uint32());
break;
case 3:
while ((wireType = this.uint32() & 7) !== 4) {
this.skipType(wireType);
}
break;
case 5:
this.skip(4);
break;
/* istanbul ignore next */
default:
throw Error("invalid wire type " + wireType + " at offset " + this.pos);
}
return this;
};
Reader._configure = function(BufferReader_) {
BufferReader = BufferReader_;
var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
util.merge(Reader.prototype, {
int64: function read_int64() {
return readLongVarint.call(this)[fn](false);
},
uint64: function read_uint64() {
return readLongVarint.call(this)[fn](true);
},
sint64: function read_sint64() {
return readLongVarint.call(this).zzDecode()[fn](false);
},
fixed64: function read_fixed64() {
return readFixed64.call(this)[fn](true);
},
sfixed64: function read_sfixed64() {
return readFixed64.call(this)[fn](false);
}
});
};
},{"./util/minimal":75}],70:[function(require,module,exports){
"use strict";
module.exports = BufferReader;
// extends Reader
var Reader = require("./reader");
(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
var util = require("./util/minimal");
/**
* Constructs a new buffer reader instance.
* @classdesc Wire format reader using node buffers.
* @extends Reader
* @constructor
* @param {Buffer} buffer Buffer to read from
*/
function BufferReader(buffer) {
Reader.call(this, buffer);
/**
* Read buffer.
* @name BufferReader#buf
* @type {Buffer}
*/
}
/* istanbul ignore else */
if (util.Buffer)
BufferReader.prototype._slice = util.Buffer.prototype.slice;
/**
* @override
*/
BufferReader.prototype.string = function read_string_buffer() {
var len = this.uint32(); // modifies pos
return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len));
};
/**
* Reads a sequence of bytes preceeded by its length as a varint.
* @name BufferReader#bytes
* @function
* @returns {Buffer} Value read
*/
},{"./reader":69,"./util/minimal":75}],71:[function(require,module,exports){
"use strict";
module.exports = {};
/**
* Named roots.
* This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
* Can also be used manually to make roots available accross modules.
* @name roots
* @type {Object.<string,Root>}
* @example
* // pbjs -r myroot -o compiled.js ...
*
* // in another module:
* require("./compiled.js");
*
* // in any subsequent module:
* var root = protobuf.roots["myroot"];
*/
},{}],72:[function(require,module,exports){
"use strict";
/**
* Streaming RPC helpers.
* @namespace
*/
var rpc = exports;
/**
* RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
* @typedef RPCImpl
* @type {function}
* @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
* @param {Uint8Array} requestData Request data
* @param {RPCImplCallback} callback Callback function
* @returns {undefined}
* @example
* function rpcImpl(method, requestData, callback) {
* if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
* throw Error("no such method");
* asynchronouslyObtainAResponse(requestData, function(err, responseData) {
* callback(err, responseData);
* });
* }
*/
/**
* Node-style callback as used by {@link RPCImpl}.
* @typedef RPCImplCallback
* @type {function}
* @param {Error|null} error Error, if any, otherwise `null`
* @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
* @returns {undefined}
*/
rpc.Service = require("./rpc/service");
},{"./rpc/service":73}],73:[function(require,module,exports){
"use strict";
module.exports = Service;
var util = require("../util/minimal");
// Extends EventEmitter
(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
/**
* A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
*
* Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
* @typedef rpc.ServiceMethodCallback
* @template TRes extends Message<TRes>
* @type {function}
* @param {Error|null} error Error, if any
* @param {TRes} [response] Response message
* @returns {undefined}
*/
/**
* A service method part of a {@link rpc.Service} as created by {@link Service.create}.
* @typedef rpc.ServiceMethod
* @template TReq extends Message<TReq>
* @template TRes extends Message<TRes>
* @type {function}
* @param {TReq|Properties<TReq>} request Request message or plain object
* @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
* @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
*/
/**
* Constructs a new RPC service instance.
* @classdesc An RPC service as returned by {@link Service#create}.
* @exports rpc.Service
* @extends util.EventEmitter
* @constructor
* @param {RPCImpl} rpcImpl RPC implementation
* @param {boolean} [requestDelimited=false] Whether requests are length-delimited
* @param {boolean} [responseDelimited=false] Whether responses are length-delimited
*/
function Service(rpcImpl, requestDelimited, responseDelimited) {
if (typeof rpcImpl !== "function")
throw TypeError("rpcImpl must be a function");
util.EventEmitter.call(this);
/**
* RPC implementation. Becomes `null` once the service is ended.
* @type {RPCImpl|null}
*/
this.rpcImpl = rpcImpl;
/**
* Whether requests are length-delimited.
* @type {boolean}
*/
this.requestDelimited = Boolean(requestDelimited);
/**
* Whether responses are length-delimited.
* @type {boolean}
*/
this.responseDelimited = Boolean(responseDelimited);
}
/**
* Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
* @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
* @param {Constructor<TReq>} requestCtor Request constructor
* @param {Constructor<TRes>} responseCtor Response constructor
* @param {TReq|Properties<TReq>} request Request message or plain object
* @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
* @returns {undefined}
* @template TReq extends Message<TReq>
* @template TRes extends Message<TRes>
*/
Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
if (!request)
throw TypeError("request must be specified");
var self = this;
if (!callback)
return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
if (!self.rpcImpl) {
setTimeout(function() { callback(Error("already ended")); }, 0);
return undefined;
}
try {
return self.rpcImpl(
method,
requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
function rpcCallback(err, response) {
if (err) {
self.emit("error", err, method);
return callback(err);
}
if (response === null) {
self.end(/* endedByRPC */ true);
return undefined;
}
if (!(response instanceof responseCtor)) {
try {
response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
} catch (err) {
self.emit("error", err, method);
return callback(err);
}
}
self.emit("data", response, method);
return callback(null, response);
}
);
} catch (err) {
self.emit("error", err, method);
setTimeout(function() { callback(err); }, 0);
return undefined;
}
};
/**
* Ends this service and emits the `end` event.
* @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
* @returns {rpc.Service} `this`
*/
Service.prototype.end = function end(endedByRPC) {
if (this.rpcImpl) {
if (!endedByRPC) // signal end to rpcImpl
this.rpcImpl(null, null, null);
this.rpcImpl = null;
this.emit("end").off();
}
return this;
};
},{"../util/minimal":75}],74:[function(require,module,exports){
"use strict";
module.exports = LongBits;
var util = require("../util/minimal");
/**
* Constructs new long bits.
* @classdesc Helper class for working with the low and high bits of a 64 bit value.
* @memberof util
* @constructor
* @param {number} lo Low 32 bits, unsigned
* @param {number} hi High 32 bits, unsigned
*/
function LongBits(lo, hi) {
// note that the casts below are theoretically unnecessary as of today, but older statically
// generated converter code might still call the ctor with signed 32bits. kept for compat.
/**
* Low bits.
* @type {number}
*/
this.lo = lo >>> 0;
/**
* High bits.
* @type {number}
*/
this.hi = hi >>> 0;
}
/**
* Zero bits.
* @memberof util.LongBits
* @type {util.LongBits}
*/
var zero = LongBits.zero = new LongBits(0, 0);
zero.toNumber = function() { return 0; };
zero.zzEncode = zero.zzDecode = function() { return this; };
zero.length = function() { return 1; };
/**
* Zero hash.
* @memberof util.LongBits
* @type {string}
*/
var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
/**
* Constructs new long bits from the specified number.
* @param {number} value Value
* @returns {util.LongBits} Instance
*/
LongBits.fromNumber = function fromNumber(value) {
if (value === 0)
return zero;
var sign = value < 0;
if (sign)
value = -value;
var lo = value >>> 0,
hi = (value - lo) / 4294967296 >>> 0;
if (sign) {
hi = ~hi >>> 0;
lo = ~lo >>> 0;
if (++lo > 4294967295) {
lo = 0;
if (++hi > 4294967295)
hi = 0;
}
}
return new LongBits(lo, hi);
};
/**
* Constructs new long bits from a number, long or string.
* @param {Long|number|string} value Value
* @returns {util.LongBits} Instance
*/
LongBits.from = function from(value) {
if (typeof value === "number")
return LongBits.fromNumber(value);
if (util.isString(value)) {
/* istanbul ignore else */
if (util.Long)
value = util.Long.fromString(value);
else
return LongBits.fromNumber(parseInt(value, 10));
}
return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
};
/**
* Converts this long bits to a possibly unsafe JavaScript number.
* @param {boolean} [unsigned=false] Whether unsigned or not
* @returns {number} Possibly unsafe number
*/
LongBits.prototype.toNumber = function toNumber(unsigned) {
if (!unsigned && this.hi >>> 31) {
var lo = ~this.lo + 1 >>> 0,
hi = ~this.hi >>> 0;
if (!lo)
hi = hi + 1 >>> 0;
return -(lo + hi * 4294967296);
}
return this.lo + this.hi * 4294967296;
};
/**
* Converts this long bits to a long.
* @param {boolean} [unsigned=false] Whether unsigned or not
* @returns {Long} Long
*/
LongBits.prototype.toLong = function toLong(unsigned) {
return util.Long
? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
/* istanbul ignore next */
: { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
};
var charCodeAt = String.prototype.charCodeAt;
/**
* Constructs new long bits from the specified 8 characters long hash.
* @param {string} hash Hash
* @returns {util.LongBits} Bits
*/
LongBits.fromHash = function fromHash(hash) {
if (hash === zeroHash)
return zero;
return new LongBits(
( charCodeAt.call(hash, 0)
| charCodeAt.call(hash, 1) << 8
| charCodeAt.call(hash, 2) << 16
| charCodeAt.call(hash, 3) << 24) >>> 0
,
( charCodeAt.call(hash, 4)
| charCodeAt.call(hash, 5) << 8
| charCodeAt.call(hash, 6) << 16
| charCodeAt.call(hash, 7) << 24) >>> 0
);
};
/**
* Converts this long bits to a 8 characters long hash.
* @returns {string} Hash
*/
LongBits.prototype.toHash = function toHash() {
return String.fromCharCode(
this.lo & 255,
this.lo >>> 8 & 255,
this.lo >>> 16 & 255,
this.lo >>> 24 ,
this.hi & 255,
this.hi >>> 8 & 255,
this.hi >>> 16 & 255,
this.hi >>> 24
);
};
/**
* Zig-zag encodes this long bits.
* @returns {util.LongBits} `this`
*/
LongBits.prototype.zzEncode = function zzEncode() {
var mask = this.hi >> 31;
this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
this.lo = ( this.lo << 1 ^ mask) >>> 0;
return this;
};
/**
* Zig-zag decodes this long bits.
* @returns {util.LongBits} `this`
*/
LongBits.prototype.zzDecode = function zzDecode() {
var mask = -(this.lo & 1);
this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
return this;
};
/**
* Calculates the length of this longbits when encoded as a varint.
* @returns {number} Length
*/
LongBits.prototype.length = function length() {
var part0 = this.lo,
part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
part2 = this.hi >>> 24;
return part2 === 0
? part1 === 0
? part0 < 16384
? part0 < 128 ? 1 : 2
: part0 < 2097152 ? 3 : 4
: part1 < 16384
? part1 < 128 ? 5 : 6
: part1 < 2097152 ? 7 : 8
: part2 < 128 ? 9 : 10;
};
},{"../util/minimal":75}],75:[function(require,module,exports){
(function (global){
"use strict";
var util = exports;
// used to return a Promise where callback is omitted
util.asPromise = require("@protobufjs/aspromise");
// converts to / from base64 encoded strings
util.base64 = require("@protobufjs/base64");
// base class of rpc.Service
util.EventEmitter = require("@protobufjs/eventemitter");
// float handling accross browsers
util.float = require("@protobufjs/float");
// requires modules optionally and hides the call from bundlers
util.inquire = require("@protobufjs/inquire");
// converts to / from utf8 encoded strings
util.utf8 = require("@protobufjs/utf8");
// provides a node-like buffer pool in the browser
util.pool = require("@protobufjs/pool");
// utility to work with the low and high bits of a 64 bit value
util.LongBits = require("./longbits");
// global object reference
util.global = typeof window !== "undefined" && window
|| typeof global !== "undefined" && global
|| typeof self !== "undefined" && self
|| this; // eslint-disable-line no-invalid-this
/**
* An immuable empty array.
* @memberof util
* @type {Array.<*>}
* @const
*/
util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
/**
* An immutable empty object.
* @type {Object}
* @const
*/
util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
/**
* Whether running within node or not.
* @memberof util
* @type {boolean}
* @const
*/
util.isNode = Boolean(util.global.process && util.global.process.versions && util.global.process.versions.node);
/**
* Tests if the specified value is an integer.
* @function
* @param {*} value Value to test
* @returns {boolean} `true` if the value is an integer
*/
util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};
/**
* Tests if the specified value is a string.
* @param {*} value Value to test
* @returns {boolean} `true` if the value is a string
*/
util.isString = function isString(value) {
return typeof value === "string" || value instanceof String;
};
/**
* Tests if the specified value is a non-null object.
* @param {*} value Value to test
* @returns {boolean} `true` if the value is a non-null object
*/
util.isObject = function isObject(value) {
return value && typeof value === "object";
};
/**
* Checks if a property on a message is considered to be present.
* This is an alias of {@link util.isSet}.
* @function
* @param {Object} obj Plain object or message instance
* @param {string} prop Property name
* @returns {boolean} `true` if considered to be present, otherwise `false`
*/
util.isset =
/**
* Checks if a property on a message is considered to be present.
* @param {Object} obj Plain object or message instance
* @param {string} prop Property name
* @returns {boolean} `true` if considered to be present, otherwise `false`
*/
util.isSet = function isSet(obj, prop) {
var value = obj[prop];
if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
return false;
};
/**
* Any compatible Buffer instance.
* This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
* @interface Buffer
* @extends Uint8Array
*/
/**
* Node's Buffer class if available.
* @type {Constructor<Buffer>}
*/
util.Buffer = (function() {
try {
var Buffer = util.inquire("buffer").Buffer;
// refuse to use non-node buffers if not explicitly assigned (perf reasons):
return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
} catch (e) {
/* istanbul ignore next */
return null;
}
})();
// Internal alias of or polyfull for Buffer.from.
util._Buffer_from = null;
// Internal alias of or polyfill for Buffer.allocUnsafe.
util._Buffer_allocUnsafe = null;
/**
* Creates a new buffer of whatever type supported by the environment.
* @param {number|number[]} [sizeOrArray=0] Buffer size or number array
* @returns {Uint8Array|Buffer} Buffer
*/
util.newBuffer = function newBuffer(sizeOrArray) {
/* istanbul ignore next */
return typeof sizeOrArray === "number"
? util.Buffer
? util._Buffer_allocUnsafe(sizeOrArray)
: new util.Array(sizeOrArray)
: util.Buffer
? util._Buffer_from(sizeOrArray)
: typeof Uint8Array === "undefined"
? sizeOrArray
: new Uint8Array(sizeOrArray);
};
/**
* Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
* @type {Constructor<Uint8Array>}
*/
util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
/**
* Any compatible Long instance.
* This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
* @interface Long
* @property {number} low Low bits
* @property {number} high High bits
* @property {boolean} unsigned Whether unsigned or not
*/
/**
* Long.js's Long class if available.
* @type {Constructor<Long>}
*/
util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long
|| /* istanbul ignore next */ util.global.Long
|| util.inquire("long");
/**
* Regular expression used to verify 2 bit (`bool`) map keys.
* @type {RegExp}
* @const
*/
util.key2Re = /^true|false|0|1$/;
/**
* Regular expression used to verify 32 bit (`int32` etc.) map keys.
* @type {RegExp}
* @const
*/
util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
/**
* Regular expression used to verify 64 bit (`int64` etc.) map keys.
* @type {RegExp}
* @const
*/
util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
/**
* Converts a number or long to an 8 characters long hash string.
* @param {Long|number} value Value to convert
* @returns {string} Hash
*/
util.longToHash = function longToHash(value) {
return value
? util.LongBits.from(value).toHash()
: util.LongBits.zeroHash;
};
/**
* Converts an 8 characters long hash string to a long or number.
* @param {string} hash Hash
* @param {boolean} [unsigned=false] Whether unsigned or not
* @returns {Long|number} Original value
*/
util.longFromHash = function longFromHash(hash, unsigned) {
var bits = util.LongBits.fromHash(hash);
if (util.Long)
return util.Long.fromBits(bits.lo, bits.hi, unsigned);
return bits.toNumber(Boolean(unsigned));
};
/**
* Merges the properties of the source object into the destination object.
* @memberof util
* @param {Object.<string,*>} dst Destination object
* @param {Object.<string,*>} src Source object
* @param {boolean} [ifNotSet=false] Merges only if the key is not already set
* @returns {Object.<string,*>} Destination object
*/
function merge(dst, src, ifNotSet) { // used by converters
for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
if (dst[keys[i]] === undefined || !ifNotSet)
dst[keys[i]] = src[keys[i]];
return dst;
}
util.merge = merge;
/**
* Converts the first character of a string to lower case.
* @param {string} str String to convert
* @returns {string} Converted string
*/
util.lcFirst = function lcFirst(str) {
return str.charAt(0).toLowerCase() + str.substring(1);
};
/**
* Creates a custom error constructor.
* @memberof util
* @param {string} name Error name
* @returns {Constructor<Error>} Custom error constructor
*/
function newError(name) {
function CustomError(message, properties) {
if (!(this instanceof CustomError))
return new CustomError(message, properties);
// Error.call(this, message);
// ^ just returns a new error instance because the ctor can be called as a function
Object.defineProperty(this, "message", { get: function() { return message; } });
/* istanbul ignore next */
if (Error.captureStackTrace) // node
Error.captureStackTrace(this, CustomError);
else
Object.defineProperty(this, "stack", { value: (new Error()).stack || "" });
if (properties)
merge(this, properties);
}
(CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;
Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });
CustomError.prototype.toString = function toString() {
return this.name + ": " + this.message;
};
return CustomError;
}
util.newError = newError;
/**
* Constructs a new protocol error.
* @classdesc Error subclass indicating a protocol specifc error.
* @memberof util
* @extends Error
* @template T extends Message<T>
* @constructor
* @param {string} message Error message
* @param {Object.<string,*>} [properties] Additional properties
* @example
* try {
* MyMessage.decode(someBuffer); // throws if required fields are missing
* } catch (e) {
* if (e instanceof ProtocolError && e.instance)
* console.log("decoded so far: " + JSON.stringify(e.instance));
* }
*/
util.ProtocolError = newError("ProtocolError");
/**
* So far decoded message instance.
* @name util.ProtocolError#instance
* @type {Message<T>}
*/
/**
* A OneOf getter as returned by {@link util.oneOfGetter}.
* @typedef OneOfGetter
* @type {function}
* @returns {string|undefined} Set field name, if any
*/
/**
* Builds a getter for a oneof's present field name.
* @param {string[]} fieldNames Field names
* @returns {OneOfGetter} Unbound getter
*/
util.oneOfGetter = function getOneOf(fieldNames) {
var fieldMap = {};
for (var i = 0; i < fieldNames.length; ++i)
fieldMap[fieldNames[i]] = 1;
/**
* @returns {string|undefined} Set field name, if any
* @this Object
* @ignore
*/
return function() { // eslint-disable-line consistent-return
for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
return keys[i];
};
};
/**
* A OneOf setter as returned by {@link util.oneOfSetter}.
* @typedef OneOfSetter
* @type {function}
* @param {string|undefined} value Field name
* @returns {undefined}
*/
/**
* Builds a setter for a oneof's present field name.
* @param {string[]} fieldNames Field names
* @returns {OneOfSetter} Unbound setter
*/
util.oneOfSetter = function setOneOf(fieldNames) {
/**
* @param {string} name Field name
* @returns {undefined}
* @this Object
* @ignore
*/
return function(name) {
for (var i = 0; i < fieldNames.length; ++i)
if (fieldNames[i] !== name)
delete this[fieldNames[i]];
};
};
/**
* Default conversion options used for {@link Message#toJSON} implementations.
*
* These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
*
* - Longs become strings
* - Enums become string keys
* - Bytes become base64 encoded strings
* - (Sub-)Messages become plain objects
* - Maps become plain objects with all string keys
* - Repeated fields become arrays
* - NaN and Infinity for float and double fields become strings
*
* @type {IConversionOptions}
* @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
*/
util.toJSONOptions = {
longs: String,
enums: String,
bytes: String,
json: true
};
// Sets up buffer utility according to the environment (called in index-minimal)
util._configure = function() {
var Buffer = util.Buffer;
/* istanbul ignore if */
if (!Buffer) {
util._Buffer_from = util._Buffer_allocUnsafe = null;
return;
}
// because node 4.x buffers are incompatible & immutable
// see: https://github.com/dcodeIO/protobuf.js/pull/665
util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
/* istanbul ignore next */
function Buffer_from(value, encoding) {
return new Buffer(value, encoding);
};
util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
/* istanbul ignore next */
function Buffer_allocUnsafe(size) {
return new Buffer(size);
};
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./longbits":74,"@protobufjs/aspromise":25,"@protobufjs/base64":26,"@protobufjs/eventemitter":27,"@protobufjs/float":28,"@protobufjs/inquire":29,"@protobufjs/pool":30,"@protobufjs/utf8":31}],76:[function(require,module,exports){
"use strict";
module.exports = Writer;
var util = require("./util/minimal");
var BufferWriter; // cyclic
var LongBits = util.LongBits,
base64 = util.base64,
utf8 = util.utf8;
/**
* Constructs a new writer operation instance.
* @classdesc Scheduled writer operation.
* @constructor
* @param {function(*, Uint8Array, number)} fn Function to call
* @param {number} len Value byte length
* @param {*} val Value to write
* @ignore
*/
function Op(fn, len, val) {
/**
* Function to call.
* @type {function(Uint8Array, number, *)}
*/
this.fn = fn;
/**
* Value byte length.
* @type {number}
*/
this.len = len;
/**
* Next operation.
* @type {Writer.Op|undefined}
*/
this.next = undefined;
/**
* Value to write.
* @type {*}
*/
this.val = val; // type varies
}
/* istanbul ignore next */
function noop() {} // eslint-disable-line no-empty-function
/**
* Constructs a new writer state instance.
* @classdesc Copied writer state.
* @memberof Writer
* @constructor
* @param {Writer} writer Writer to copy state from
* @ignore
*/
function State(writer) {
/**
* Current head.
* @type {Writer.Op}
*/
this.head = writer.head;
/**
* Current tail.
* @type {Writer.Op}
*/
this.tail = writer.tail;
/**
* Current buffer length.
* @type {number}
*/
this.len = writer.len;
/**
* Next state.
* @type {State|null}
*/
this.next = writer.states;
}
/**
* Constructs a new writer instance.
* @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
* @constructor
*/
function Writer() {
/**
* Current length.
* @type {number}
*/
this.len = 0;
/**
* Operations head.
* @type {Object}
*/
this.head = new Op(noop, 0, 0);
/**
* Operations tail
* @type {Object}
*/
this.tail = this.head;
/**
* Linked forked states.
* @type {Object|null}
*/
this.states = null;
// When a value is written, the writer calculates its byte length and puts it into a linked
// list of operations to perform when finish() is called. This both allows us to allocate
// buffers of the exact required size and reduces the amount of work we have to do compared
// to first calculating over objects and then encoding over objects. In our case, the encoding
// part is just a linked list walk calling operations with already prepared values.
}
/**
* Creates a new writer.
* @function
* @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
*/
Writer.create = util.Buffer
? function create_buffer_setup() {
return (Writer.create = function create_buffer() {
return new BufferWriter();
})();
}
/* istanbul ignore next */
: function create_array() {
return new Writer();
};
/**
* Allocates a buffer of the specified size.
* @param {number} size Buffer size
* @returns {Uint8Array} Buffer
*/
Writer.alloc = function alloc(size) {
return new util.Array(size);
};
// Use Uint8Array buffer pool in the browser, just like node does with buffers
/* istanbul ignore else */
if (util.Array !== Array)
Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
/**
* Pushes a new operation to the queue.
* @param {function(Uint8Array, number, *)} fn Function to call
* @param {number} len Value byte length
* @param {number} val Value to write
* @returns {Writer} `this`
* @private
*/
Writer.prototype._push = function push(fn, len, val) {
this.tail = this.tail.next = new Op(fn, len, val);
this.len += len;
return this;
};
function writeByte(val, buf, pos) {
buf[pos] = val & 255;
}
function writeVarint32(val, buf, pos) {
while (val > 127) {
buf[pos++] = val & 127 | 128;
val >>>= 7;
}
buf[pos] = val;
}
/**
* Constructs a new varint writer operation instance.
* @classdesc Scheduled varint writer operation.
* @extends Op
* @constructor
* @param {number} len Value byte length
* @param {number} val Value to write
* @ignore
*/
function VarintOp(len, val) {
this.len = len;
this.next = undefined;
this.val = val;
}
VarintOp.prototype = Object.create(Op.prototype);
VarintOp.prototype.fn = writeVarint32;
/**
* Writes an unsigned 32 bit value as a varint.
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.uint32 = function write_uint32(value) {
// here, the call to this.push has been inlined and a varint specific Op subclass is used.
// uint32 is by far the most frequently used operation and benefits significantly from this.
this.len += (this.tail = this.tail.next = new VarintOp(
(value = value >>> 0)
< 128 ? 1
: value < 16384 ? 2
: value < 2097152 ? 3
: value < 268435456 ? 4
: 5,
value)).len;
return this;
};
/**
* Writes a signed 32 bit value as a varint.
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.int32 = function write_int32(value) {
return value < 0
? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
: this.uint32(value);
};
/**
* Writes a 32 bit value as a varint, zig-zag encoded.
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.sint32 = function write_sint32(value) {
return this.uint32((value << 1 ^ value >> 31) >>> 0);
};
function writeVarint64(val, buf, pos) {
while (val.hi) {
buf[pos++] = val.lo & 127 | 128;
val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
val.hi >>>= 7;
}
while (val.lo > 127) {
buf[pos++] = val.lo & 127 | 128;
val.lo = val.lo >>> 7;
}
buf[pos++] = val.lo;
}
/**
* Writes an unsigned 64 bit value as a varint.
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.uint64 = function write_uint64(value) {
var bits = LongBits.from(value);
return this._push(writeVarint64, bits.length(), bits);
};
/**
* Writes a signed 64 bit value as a varint.
* @function
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.int64 = Writer.prototype.uint64;
/**
* Writes a signed 64 bit value as a varint, zig-zag encoded.
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.sint64 = function write_sint64(value) {
var bits = LongBits.from(value).zzEncode();
return this._push(writeVarint64, bits.length(), bits);
};
/**
* Writes a boolish value as a varint.
* @param {boolean} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.bool = function write_bool(value) {
return this._push(writeByte, 1, value ? 1 : 0);
};
function writeFixed32(val, buf, pos) {
buf[pos ] = val & 255;
buf[pos + 1] = val >>> 8 & 255;
buf[pos + 2] = val >>> 16 & 255;
buf[pos + 3] = val >>> 24;
}
/**
* Writes an unsigned 32 bit value as fixed 32 bits.
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.fixed32 = function write_fixed32(value) {
return this._push(writeFixed32, 4, value >>> 0);
};
/**
* Writes a signed 32 bit value as fixed 32 bits.
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.sfixed32 = Writer.prototype.fixed32;
/**
* Writes an unsigned 64 bit value as fixed 64 bits.
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.fixed64 = function write_fixed64(value) {
var bits = LongBits.from(value);
return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
};
/**
* Writes a signed 64 bit value as fixed 64 bits.
* @function
* @param {Long|number|string} value Value to write
* @returns {Writer} `this`
* @throws {TypeError} If `value` is a string and no long library is present.
*/
Writer.prototype.sfixed64 = Writer.prototype.fixed64;
/**
* Writes a float (32 bit).
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.float = function write_float(value) {
return this._push(util.float.writeFloatLE, 4, value);
};
/**
* Writes a double (64 bit float).
* @function
* @param {number} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.double = function write_double(value) {
return this._push(util.float.writeDoubleLE, 8, value);
};
var writeBytes = util.Array.prototype.set
? function writeBytes_set(val, buf, pos) {
buf.set(val, pos); // also works for plain array values
}
/* istanbul ignore next */
: function writeBytes_for(val, buf, pos) {
for (var i = 0; i < val.length; ++i)
buf[pos + i] = val[i];
};
/**
* Writes a sequence of bytes.
* @param {Uint8Array|string} value Buffer or base64 encoded string to write
* @returns {Writer} `this`
*/
Writer.prototype.bytes = function write_bytes(value) {
var len = value.length >>> 0;
if (!len)
return this._push(writeByte, 1, 0);
if (util.isString(value)) {
var buf = Writer.alloc(len = base64.length(value));
base64.decode(value, buf, 0);
value = buf;
}
return this.uint32(len)._push(writeBytes, len, value);
};
/**
* Writes a string.
* @param {string} value Value to write
* @returns {Writer} `this`
*/
Writer.prototype.string = function write_string(value) {
var len = utf8.length(value);
return len
? this.uint32(len)._push(utf8.write, len, value)
: this._push(writeByte, 1, 0);
};
/**
* Forks this writer's state by pushing it to a stack.
* Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
* @returns {Writer} `this`
*/
Writer.prototype.fork = function fork() {
this.states = new State(this);
this.head = this.tail = new Op(noop, 0, 0);
this.len = 0;
return this;
};
/**
* Resets this instance to the last state.
* @returns {Writer} `this`
*/
Writer.prototype.reset = function reset() {
if (this.states) {
this.head = this.states.head;
this.tail = this.states.tail;
this.len = this.states.len;
this.states = this.states.next;
} else {
this.head = this.tail = new Op(noop, 0, 0);
this.len = 0;
}
return this;
};
/**
* Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
* @returns {Writer} `this`
*/
Writer.prototype.ldelim = function ldelim() {
var head = this.head,
tail = this.tail,
len = this.len;
this.reset().uint32(len);
if (len) {
this.tail.next = head.next; // skip noop
this.tail = tail;
this.len += len;
}
return this;
};
/**
* Finishes the write operation.
* @returns {Uint8Array} Finished buffer
*/
Writer.prototype.finish = function finish() {
var head = this.head.next, // skip noop
buf = this.constructor.alloc(this.len),
pos = 0;
while (head) {
head.fn(head.val, buf, pos);
pos += head.len;
head = head.next;
}
// this.head = this.tail = null;
return buf;
};
Writer._configure = function(BufferWriter_) {
BufferWriter = BufferWriter_;
};
},{"./util/minimal":75}],77:[function(require,module,exports){
"use strict";
module.exports = BufferWriter;
// extends Writer
var Writer = require("./writer");
(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
var util = require("./util/minimal");
var Buffer = util.Buffer;
/**
* Constructs a new buffer writer instance.
* @classdesc Wire format writer using node buffers.
* @extends Writer
* @constructor
*/
function BufferWriter() {
Writer.call(this);
}
/**
* Allocates a buffer of the specified size.
* @param {number} size Buffer size
* @returns {Buffer} Buffer
*/
BufferWriter.alloc = function alloc_buffer(size) {
return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);
};
var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"
? function writeBytesBuffer_set(val, buf, pos) {
buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
// also works for plain array values
}
/* istanbul ignore next */
: function writeBytesBuffer_copy(val, buf, pos) {
if (val.copy) // Buffer values
val.copy(buf, pos, 0, val.length);
else for (var i = 0; i < val.length;) // plain array values
buf[pos++] = val[i++];
};
/**
* @override
*/
BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
if (util.isString(value))
value = util._Buffer_from(value, "base64");
var len = value.length >>> 0;
this.uint32(len);
if (len)
this._push(writeBytesBuffer, len, value);
return this;
};
function writeStringBuffer(val, buf, pos) {
if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
util.utf8.write(val, buf, pos);
else
buf.utf8Write(val, pos);
}
/**
* @override
*/
BufferWriter.prototype.string = function write_string_buffer(value) {
var len = Buffer.byteLength(value);
this.uint32(len);
if (len)
this._push(writeStringBuffer, len, value);
return this;
};
/**
* Finishes the write operation.
* @name BufferWriter#finish
* @function
* @returns {Buffer} Finished buffer
*/
},{"./util/minimal":75,"./writer":76}],78:[function(require,module,exports){
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []);
// The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(innerFn, self, context);
return generator;
}
exports.wrap = wrap;
// Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return { type: "normal", arg: fn.call(obj, arg) };
} catch (err) {
return { type: "throw", arg: err };
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed";
// Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {};
// Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
// This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
if (NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp = GeneratorFunctionPrototype.prototype =
Generator.prototype = Object.create(IteratorPrototype);
GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction";
// Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
exports.isGeneratorFunction = function(genFun) {
var ctor = typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction ||
// For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) === "GeneratorFunction"
: false;
};
exports.mark = function(genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
};
// Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function(arg) {
return { __await: arg };
};
function AsyncIterator(generator) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (value &&
typeof value === "object" &&
hasOwn.call(value, "__await")) {
return Promise.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
});
}
return Promise.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new Promise(function(resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise =
// If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(
callInvokeWithMethodAndArg,
// Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
) : callInvokeWithMethodAndArg();
}
// Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator;
// Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function(innerFn, outerFn, self, tryLocsList) {
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList)
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
}
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
} else if (record.type === "throw") {
state = GenStateCompleted;
// Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
}
// Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (! info) {
context.method = "throw";
context.arg = new TypeError("iterator result is not an object");
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value;
// Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc;
// If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
}
// The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
}
// Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator";
// A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
};
Gp.toString = function() {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = { tryLoc: locs[0] };
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [{ tryLoc: "root" }];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function(object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse();
// Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
}
// To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return next.next = next;
}
}
// Return an iterator with no values.
return { next: doneResult };
}
exports.values = values;
function doneResult() {
return { value: undefined, done: true };
}
Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
this.prev = 0;
this.next = 0;
// Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))) {
this[name] = undefined;
}
}
}
},
stop: function() {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function(exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !! caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc");
var hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error("try statement without catch or finally");
}
}
}
},
abrupt: function(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
if (finallyEntry &&
(type === "break" ||
type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry ? finallyEntry.completion : {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (record.type === "break" ||
record.type === "continue") {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(entry.completion, entry.afterLoc);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
"catch": function(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
// The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
}
};
// Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
}(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
typeof module === "object" ? module.exports : {}
));
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
},{}],79:[function(require,module,exports){
/* eslint-disable node/no-deprecated-api */
var buffer = require('buffer')
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
},{"buffer":62}],80:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
// prototype class for hash functions
function Hash (blockSize, finalSize) {
this._block = Buffer.alloc(blockSize)
this._finalSize = finalSize
this._blockSize = blockSize
this._len = 0
}
Hash.prototype.update = function (data, enc) {
if (typeof data === 'string') {
enc = enc || 'utf8'
data = Buffer.from(data, enc)
}
var block = this._block
var blockSize = this._blockSize
var length = data.length
var accum = this._len
for (var offset = 0; offset < length;) {
var assigned = accum % blockSize
var remainder = Math.min(length - offset, blockSize - assigned)
for (var i = 0; i < remainder; i++) {
block[assigned + i] = data[offset + i]
}
accum += remainder
offset += remainder
if ((accum % blockSize) === 0) {
this._update(block)
}
}
this._len += length
return this
}
Hash.prototype.digest = function (enc) {
var rem = this._len % this._blockSize
this._block[rem] = 0x80
// zero (rem + 1) trailing bits, where (rem + 1) is the smallest
// non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
this._block.fill(0, rem + 1)
if (rem >= this._finalSize) {
this._update(this._block)
this._block.fill(0)
}
var bits = this._len * 8
// uint32
if (bits <= 0xffffffff) {
this._block.writeUInt32BE(bits, this._blockSize - 4)
// uint64
} else {
var lowBits = (bits & 0xffffffff) >>> 0
var highBits = (bits - lowBits) / 0x100000000
this._block.writeUInt32BE(highBits, this._blockSize - 8)
this._block.writeUInt32BE(lowBits, this._blockSize - 4)
}
this._update(this._block)
var hash = this._hash()
return enc ? hash.toString(enc) : hash
}
Hash.prototype._update = function () {
throw new Error('_update must be implemented by subclass')
}
module.exports = Hash
},{"safe-buffer":79}],81:[function(require,module,exports){
var exports = module.exports = function SHA (algorithm) {
algorithm = algorithm.toLowerCase()
var Algorithm = exports[algorithm]
if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
return new Algorithm()
}
exports.sha = require('./sha')
exports.sha1 = require('./sha1')
exports.sha224 = require('./sha224')
exports.sha256 = require('./sha256')
exports.sha384 = require('./sha384')
exports.sha512 = require('./sha512')
},{"./sha":82,"./sha1":83,"./sha224":84,"./sha256":85,"./sha384":86,"./sha512":87}],82:[function(require,module,exports){
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
* in FIPS PUB 180-1
* This source code is derived from sha1.js of the same repository.
* The difference between SHA-0 and SHA-1 is just a bitwise rotate left
* operation was added.
*/
var inherits = require('inherits')
var Hash = require('./hash')
var Buffer = require('safe-buffer').Buffer
var K = [
0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]
var W = new Array(80)
function Sha () {
this.init()
this._w = W
Hash.call(this, 64, 56)
}
inherits(Sha, Hash)
Sha.prototype.init = function () {
this._a = 0x67452301
this._b = 0xefcdab89
this._c = 0x98badcfe
this._d = 0x10325476
this._e = 0xc3d2e1f0
return this
}
function rotl5 (num) {
return (num << 5) | (num >>> 27)
}
function rotl30 (num) {
return (num << 30) | (num >>> 2)
}
function ft (s, b, c, d) {
if (s === 0) return (b & c) | ((~b) & d)
if (s === 2) return (b & c) | (b & d) | (c & d)
return b ^ c ^ d
}
Sha.prototype._update = function (M) {
var W = this._w
var a = this._a | 0
var b = this._b | 0
var c = this._c | 0
var d = this._d | 0
var e = this._e | 0
for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
for (var j = 0; j < 80; ++j) {
var s = ~~(j / 20)
var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
e = d
d = c
c = rotl30(b)
b = a
a = t
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
}
Sha.prototype._hash = function () {
var H = Buffer.allocUnsafe(20)
H.writeInt32BE(this._a | 0, 0)
H.writeInt32BE(this._b | 0, 4)
H.writeInt32BE(this._c | 0, 8)
H.writeInt32BE(this._d | 0, 12)
H.writeInt32BE(this._e | 0, 16)
return H
}
module.exports = Sha
},{"./hash":80,"inherits":64,"safe-buffer":79}],83:[function(require,module,exports){
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
var inherits = require('inherits')
var Hash = require('./hash')
var Buffer = require('safe-buffer').Buffer
var K = [
0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]
var W = new Array(80)
function Sha1 () {
this.init()
this._w = W
Hash.call(this, 64, 56)
}
inherits(Sha1, Hash)
Sha1.prototype.init = function () {
this._a = 0x67452301
this._b = 0xefcdab89
this._c = 0x98badcfe
this._d = 0x10325476
this._e = 0xc3d2e1f0
return this
}
function rotl1 (num) {
return (num << 1) | (num >>> 31)
}
function rotl5 (num) {
return (num << 5) | (num >>> 27)
}
function rotl30 (num) {
return (num << 30) | (num >>> 2)
}
function ft (s, b, c, d) {
if (s === 0) return (b & c) | ((~b) & d)
if (s === 2) return (b & c) | (b & d) | (c & d)
return b ^ c ^ d
}
Sha1.prototype._update = function (M) {
var W = this._w
var a = this._a | 0
var b = this._b | 0
var c = this._c | 0
var d = this._d | 0
var e = this._e | 0
for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
for (var j = 0; j < 80; ++j) {
var s = ~~(j / 20)
var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
e = d
d = c
c = rotl30(b)
b = a
a = t
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
}
Sha1.prototype._hash = function () {
var H = Buffer.allocUnsafe(20)
H.writeInt32BE(this._a | 0, 0)
H.writeInt32BE(this._b | 0, 4)
H.writeInt32BE(this._c | 0, 8)
H.writeInt32BE(this._d | 0, 12)
H.writeInt32BE(this._e | 0, 16)
return H
}
module.exports = Sha1
},{"./hash":80,"inherits":64,"safe-buffer":79}],84:[function(require,module,exports){
/**
* A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
* in FIPS 180-2
* Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
*
*/
var inherits = require('inherits')
var Sha256 = require('./sha256')
var Hash = require('./hash')
var Buffer = require('safe-buffer').Buffer
var W = new Array(64)
function Sha224 () {
this.init()
this._w = W // new Array(64)
Hash.call(this, 64, 56)
}
inherits(Sha224, Sha256)
Sha224.prototype.init = function () {
this._a = 0xc1059ed8
this._b = 0x367cd507
this._c = 0x3070dd17
this._d = 0xf70e5939
this._e = 0xffc00b31
this._f = 0x68581511
this._g = 0x64f98fa7
this._h = 0xbefa4fa4
return this
}
Sha224.prototype._hash = function () {
var H = Buffer.allocUnsafe(28)
H.writeInt32BE(this._a, 0)
H.writeInt32BE(this._b, 4)
H.writeInt32BE(this._c, 8)
H.writeInt32BE(this._d, 12)
H.writeInt32BE(this._e, 16)
H.writeInt32BE(this._f, 20)
H.writeInt32BE(this._g, 24)
return H
}
module.exports = Sha224
},{"./hash":80,"./sha256":85,"inherits":64,"safe-buffer":79}],85:[function(require,module,exports){
/**
* A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
* in FIPS 180-2
* Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
*
*/
var inherits = require('inherits')
var Hash = require('./hash')
var Buffer = require('safe-buffer').Buffer
var K = [
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
]
var W = new Array(64)
function Sha256 () {
this.init()
this._w = W // new Array(64)
Hash.call(this, 64, 56)
}
inherits(Sha256, Hash)
Sha256.prototype.init = function () {
this._a = 0x6a09e667
this._b = 0xbb67ae85
this._c = 0x3c6ef372
this._d = 0xa54ff53a
this._e = 0x510e527f
this._f = 0x9b05688c
this._g = 0x1f83d9ab
this._h = 0x5be0cd19
return this
}
function ch (x, y, z) {
return z ^ (x & (y ^ z))
}
function maj (x, y, z) {
return (x & y) | (z & (x | y))
}
function sigma0 (x) {
return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
}
function sigma1 (x) {
return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
}
function gamma0 (x) {
return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
}
function gamma1 (x) {
return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
}
Sha256.prototype._update = function (M) {
var W = this._w
var a = this._a | 0
var b = this._b | 0
var c = this._c | 0
var d = this._d | 0
var e = this._e | 0
var f = this._f | 0
var g = this._g | 0
var h = this._h | 0
for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
for (var j = 0; j < 64; ++j) {
var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
var T2 = (sigma0(a) + maj(a, b, c)) | 0
h = g
g = f
f = e
e = (d + T1) | 0
d = c
c = b
b = a
a = (T1 + T2) | 0
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
this._f = (f + this._f) | 0
this._g = (g + this._g) | 0
this._h = (h + this._h) | 0
}
Sha256.prototype._hash = function () {
var H = Buffer.allocUnsafe(32)
H.writeInt32BE(this._a, 0)
H.writeInt32BE(this._b, 4)
H.writeInt32BE(this._c, 8)
H.writeInt32BE(this._d, 12)
H.writeInt32BE(this._e, 16)
H.writeInt32BE(this._f, 20)
H.writeInt32BE(this._g, 24)
H.writeInt32BE(this._h, 28)
return H
}
module.exports = Sha256
},{"./hash":80,"inherits":64,"safe-buffer":79}],86:[function(require,module,exports){
var inherits = require('inherits')
var SHA512 = require('./sha512')
var Hash = require('./hash')
var Buffer = require('safe-buffer').Buffer
var W = new Array(160)
function Sha384 () {
this.init()
this._w = W
Hash.call(this, 128, 112)
}
inherits(Sha384, SHA512)
Sha384.prototype.init = function () {
this._ah = 0xcbbb9d5d
this._bh = 0x629a292a
this._ch = 0x9159015a
this._dh = 0x152fecd8
this._eh = 0x67332667
this._fh = 0x8eb44a87
this._gh = 0xdb0c2e0d
this._hh = 0x47b5481d
this._al = 0xc1059ed8
this._bl = 0x367cd507
this._cl = 0x3070dd17
this._dl = 0xf70e5939
this._el = 0xffc00b31
this._fl = 0x68581511
this._gl = 0x64f98fa7
this._hl = 0xbefa4fa4
return this
}
Sha384.prototype._hash = function () {
var H = Buffer.allocUnsafe(48)
function writeInt64BE (h, l, offset) {
H.writeInt32BE(h, offset)
H.writeInt32BE(l, offset + 4)
}
writeInt64BE(this._ah, this._al, 0)
writeInt64BE(this._bh, this._bl, 8)
writeInt64BE(this._ch, this._cl, 16)
writeInt64BE(this._dh, this._dl, 24)
writeInt64BE(this._eh, this._el, 32)
writeInt64BE(this._fh, this._fl, 40)
return H
}
module.exports = Sha384
},{"./hash":80,"./sha512":87,"inherits":64,"safe-buffer":79}],87:[function(require,module,exports){
var inherits = require('inherits')
var Hash = require('./hash')
var Buffer = require('safe-buffer').Buffer
var K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
]
var W = new Array(160)
function Sha512 () {
this.init()
this._w = W
Hash.call(this, 128, 112)
}
inherits(Sha512, Hash)
Sha512.prototype.init = function () {
this._ah = 0x6a09e667
this._bh = 0xbb67ae85
this._ch = 0x3c6ef372
this._dh = 0xa54ff53a
this._eh = 0x510e527f
this._fh = 0x9b05688c
this._gh = 0x1f83d9ab
this._hh = 0x5be0cd19
this._al = 0xf3bcc908
this._bl = 0x84caa73b
this._cl = 0xfe94f82b
this._dl = 0x5f1d36f1
this._el = 0xade682d1
this._fl = 0x2b3e6c1f
this._gl = 0xfb41bd6b
this._hl = 0x137e2179
return this
}
function Ch (x, y, z) {
return z ^ (x & (y ^ z))
}
function maj (x, y, z) {
return (x & y) | (z & (x | y))
}
function sigma0 (x, xl) {
return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
}
function sigma1 (x, xl) {
return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
}
function Gamma0 (x, xl) {
return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
}
function Gamma0l (x, xl) {
return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
}
function Gamma1 (x, xl) {
return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
}
function Gamma1l (x, xl) {
return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
}
function getCarry (a, b) {
return (a >>> 0) < (b >>> 0) ? 1 : 0
}
Sha512.prototype._update = function (M) {
var W = this._w
var ah = this._ah | 0
var bh = this._bh | 0
var ch = this._ch | 0
var dh = this._dh | 0
var eh = this._eh | 0
var fh = this._fh | 0
var gh = this._gh | 0
var hh = this._hh | 0
var al = this._al | 0
var bl = this._bl | 0
var cl = this._cl | 0
var dl = this._dl | 0
var el = this._el | 0
var fl = this._fl | 0
var gl = this._gl | 0
var hl = this._hl | 0
for (var i = 0; i < 32; i += 2) {
W[i] = M.readInt32BE(i * 4)
W[i + 1] = M.readInt32BE(i * 4 + 4)
}
for (; i < 160; i += 2) {
var xh = W[i - 15 * 2]
var xl = W[i - 15 * 2 + 1]
var gamma0 = Gamma0(xh, xl)
var gamma0l = Gamma0l(xl, xh)
xh = W[i - 2 * 2]
xl = W[i - 2 * 2 + 1]
var gamma1 = Gamma1(xh, xl)
var gamma1l = Gamma1l(xl, xh)
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7h = W[i - 7 * 2]
var Wi7l = W[i - 7 * 2 + 1]
var Wi16h = W[i - 16 * 2]
var Wi16l = W[i - 16 * 2 + 1]
var Wil = (gamma0l + Wi7l) | 0
var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
Wil = (Wil + gamma1l) | 0
Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
Wil = (Wil + Wi16l) | 0
Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
W[i] = Wih
W[i + 1] = Wil
}
for (var j = 0; j < 160; j += 2) {
Wih = W[j]
Wil = W[j + 1]
var majh = maj(ah, bh, ch)
var majl = maj(al, bl, cl)
var sigma0h = sigma0(ah, al)
var sigma0l = sigma0(al, ah)
var sigma1h = sigma1(eh, el)
var sigma1l = sigma1(el, eh)
// t1 = h + sigma1 + ch + K[j] + W[j]
var Kih = K[j]
var Kil = K[j + 1]
var chh = Ch(eh, fh, gh)
var chl = Ch(el, fl, gl)
var t1l = (hl + sigma1l) | 0
var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
t1l = (t1l + chl) | 0
t1h = (t1h + chh + getCarry(t1l, chl)) | 0
t1l = (t1l + Kil) | 0
t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
t1l = (t1l + Wil) | 0
t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
// t2 = sigma0 + maj
var t2l = (sigma0l + majl) | 0
var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
hh = gh
hl = gl
gh = fh
gl = fl
fh = eh
fl = el
el = (dl + t1l) | 0
eh = (dh + t1h + getCarry(el, dl)) | 0
dh = ch
dl = cl
ch = bh
cl = bl
bh = ah
bl = al
al = (t1l + t2l) | 0
ah = (t1h + t2h + getCarry(al, t1l)) | 0
}
this._al = (this._al + al) | 0
this._bl = (this._bl + bl) | 0
this._cl = (this._cl + cl) | 0
this._dl = (this._dl + dl) | 0
this._el = (this._el + el) | 0
this._fl = (this._fl + fl) | 0
this._gl = (this._gl + gl) | 0
this._hl = (this._hl + hl) | 0
this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
}
Sha512.prototype._hash = function () {
var H = Buffer.allocUnsafe(64)
function writeInt64BE (h, l, offset) {
H.writeInt32BE(h, offset)
H.writeInt32BE(l, offset + 4)
}
writeInt64BE(this._ah, this._al, 0)
writeInt64BE(this._bh, this._bl, 8)
writeInt64BE(this._ch, this._cl, 16)
writeInt64BE(this._dh, this._dl, 24)
writeInt64BE(this._eh, this._el, 32)
writeInt64BE(this._fh, this._fl, 40)
writeInt64BE(this._gh, this._gl, 48)
writeInt64BE(this._hh, this._hl, 56)
return H
}
module.exports = Sha512
},{"./hash":80,"inherits":64,"safe-buffer":79}],88:[function(require,module,exports){
(function(nacl) {
'use strict';
// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
//
// Implementation derived from TweetNaCl version 20140427.
// See for details: http://tweetnacl.cr.yp.to/
var gf = function(init) {
var i, r = new Float64Array(16);
if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
return r;
};
// Pluggable, initialized in high-level API below.
var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
var _0 = new Uint8Array(16);
var _9 = new Uint8Array(32); _9[0] = 9;
var gf0 = gf(),
gf1 = gf([1]),
_121665 = gf([0xdb41, 1]),
D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
function ts64(x, i, h, l) {
x[i] = (h >> 24) & 0xff;
x[i+1] = (h >> 16) & 0xff;
x[i+2] = (h >> 8) & 0xff;
x[i+3] = h & 0xff;
x[i+4] = (l >> 24) & 0xff;
x[i+5] = (l >> 16) & 0xff;
x[i+6] = (l >> 8) & 0xff;
x[i+7] = l & 0xff;
}
function vn(x, xi, y, yi, n) {
var i,d = 0;
for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
return (1 & ((d - 1) >>> 8)) - 1;
}
function crypto_verify_16(x, xi, y, yi) {
return vn(x,xi,y,yi,16);
}
function crypto_verify_32(x, xi, y, yi) {
return vn(x,xi,y,yi,32);
}
function core_salsa20(o, p, k, c) {
var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
x15 = j15, u;
for (var i = 0; i < 20; i += 2) {
u = x0 + x12 | 0;
x4 ^= u<<7 | u>>>(32-7);
u = x4 + x0 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x4 | 0;
x12 ^= u<<13 | u>>>(32-13);
u = x12 + x8 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x1 | 0;
x9 ^= u<<7 | u>>>(32-7);
u = x9 + x5 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x9 | 0;
x1 ^= u<<13 | u>>>(32-13);
u = x1 + x13 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x6 | 0;
x14 ^= u<<7 | u>>>(32-7);
u = x14 + x10 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x14 | 0;
x6 ^= u<<13 | u>>>(32-13);
u = x6 + x2 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x11 | 0;
x3 ^= u<<7 | u>>>(32-7);
u = x3 + x15 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x3 | 0;
x11 ^= u<<13 | u>>>(32-13);
u = x11 + x7 | 0;
x15 ^= u<<18 | u>>>(32-18);
u = x0 + x3 | 0;
x1 ^= u<<7 | u>>>(32-7);
u = x1 + x0 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x1 | 0;
x3 ^= u<<13 | u>>>(32-13);
u = x3 + x2 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x4 | 0;
x6 ^= u<<7 | u>>>(32-7);
u = x6 + x5 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x6 | 0;
x4 ^= u<<13 | u>>>(32-13);
u = x4 + x7 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x9 | 0;
x11 ^= u<<7 | u>>>(32-7);
u = x11 + x10 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x11 | 0;
x9 ^= u<<13 | u>>>(32-13);
u = x9 + x8 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x14 | 0;
x12 ^= u<<7 | u>>>(32-7);
u = x12 + x15 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x12 | 0;
x14 ^= u<<13 | u>>>(32-13);
u = x14 + x13 | 0;
x15 ^= u<<18 | u>>>(32-18);
}
x0 = x0 + j0 | 0;
x1 = x1 + j1 | 0;
x2 = x2 + j2 | 0;
x3 = x3 + j3 | 0;
x4 = x4 + j4 | 0;
x5 = x5 + j5 | 0;
x6 = x6 + j6 | 0;
x7 = x7 + j7 | 0;
x8 = x8 + j8 | 0;
x9 = x9 + j9 | 0;
x10 = x10 + j10 | 0;
x11 = x11 + j11 | 0;
x12 = x12 + j12 | 0;
x13 = x13 + j13 | 0;
x14 = x14 + j14 | 0;
x15 = x15 + j15 | 0;
o[ 0] = x0 >>> 0 & 0xff;
o[ 1] = x0 >>> 8 & 0xff;
o[ 2] = x0 >>> 16 & 0xff;
o[ 3] = x0 >>> 24 & 0xff;
o[ 4] = x1 >>> 0 & 0xff;
o[ 5] = x1 >>> 8 & 0xff;
o[ 6] = x1 >>> 16 & 0xff;
o[ 7] = x1 >>> 24 & 0xff;
o[ 8] = x2 >>> 0 & 0xff;
o[ 9] = x2 >>> 8 & 0xff;
o[10] = x2 >>> 16 & 0xff;
o[11] = x2 >>> 24 & 0xff;
o[12] = x3 >>> 0 & 0xff;
o[13] = x3 >>> 8 & 0xff;
o[14] = x3 >>> 16 & 0xff;
o[15] = x3 >>> 24 & 0xff;
o[16] = x4 >>> 0 & 0xff;
o[17] = x4 >>> 8 & 0xff;
o[18] = x4 >>> 16 & 0xff;
o[19] = x4 >>> 24 & 0xff;
o[20] = x5 >>> 0 & 0xff;
o[21] = x5 >>> 8 & 0xff;
o[22] = x5 >>> 16 & 0xff;
o[23] = x5 >>> 24 & 0xff;
o[24] = x6 >>> 0 & 0xff;
o[25] = x6 >>> 8 & 0xff;
o[26] = x6 >>> 16 & 0xff;
o[27] = x6 >>> 24 & 0xff;
o[28] = x7 >>> 0 & 0xff;
o[29] = x7 >>> 8 & 0xff;
o[30] = x7 >>> 16 & 0xff;
o[31] = x7 >>> 24 & 0xff;
o[32] = x8 >>> 0 & 0xff;
o[33] = x8 >>> 8 & 0xff;
o[34] = x8 >>> 16 & 0xff;
o[35] = x8 >>> 24 & 0xff;
o[36] = x9 >>> 0 & 0xff;
o[37] = x9 >>> 8 & 0xff;
o[38] = x9 >>> 16 & 0xff;
o[39] = x9 >>> 24 & 0xff;
o[40] = x10 >>> 0 & 0xff;
o[41] = x10 >>> 8 & 0xff;
o[42] = x10 >>> 16 & 0xff;
o[43] = x10 >>> 24 & 0xff;
o[44] = x11 >>> 0 & 0xff;
o[45] = x11 >>> 8 & 0xff;
o[46] = x11 >>> 16 & 0xff;
o[47] = x11 >>> 24 & 0xff;
o[48] = x12 >>> 0 & 0xff;
o[49] = x12 >>> 8 & 0xff;
o[50] = x12 >>> 16 & 0xff;
o[51] = x12 >>> 24 & 0xff;
o[52] = x13 >>> 0 & 0xff;
o[53] = x13 >>> 8 & 0xff;
o[54] = x13 >>> 16 & 0xff;
o[55] = x13 >>> 24 & 0xff;
o[56] = x14 >>> 0 & 0xff;
o[57] = x14 >>> 8 & 0xff;
o[58] = x14 >>> 16 & 0xff;
o[59] = x14 >>> 24 & 0xff;
o[60] = x15 >>> 0 & 0xff;
o[61] = x15 >>> 8 & 0xff;
o[62] = x15 >>> 16 & 0xff;
o[63] = x15 >>> 24 & 0xff;
}
function core_hsalsa20(o,p,k,c) {
var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
x15 = j15, u;
for (var i = 0; i < 20; i += 2) {
u = x0 + x12 | 0;
x4 ^= u<<7 | u>>>(32-7);
u = x4 + x0 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x4 | 0;
x12 ^= u<<13 | u>>>(32-13);
u = x12 + x8 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x1 | 0;
x9 ^= u<<7 | u>>>(32-7);
u = x9 + x5 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x9 | 0;
x1 ^= u<<13 | u>>>(32-13);
u = x1 + x13 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x6 | 0;
x14 ^= u<<7 | u>>>(32-7);
u = x14 + x10 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x14 | 0;
x6 ^= u<<13 | u>>>(32-13);
u = x6 + x2 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x11 | 0;
x3 ^= u<<7 | u>>>(32-7);
u = x3 + x15 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x3 | 0;
x11 ^= u<<13 | u>>>(32-13);
u = x11 + x7 | 0;
x15 ^= u<<18 | u>>>(32-18);
u = x0 + x3 | 0;
x1 ^= u<<7 | u>>>(32-7);
u = x1 + x0 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x1 | 0;
x3 ^= u<<13 | u>>>(32-13);
u = x3 + x2 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x4 | 0;
x6 ^= u<<7 | u>>>(32-7);
u = x6 + x5 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x6 | 0;
x4 ^= u<<13 | u>>>(32-13);
u = x4 + x7 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x9 | 0;
x11 ^= u<<7 | u>>>(32-7);
u = x11 + x10 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x11 | 0;
x9 ^= u<<13 | u>>>(32-13);
u = x9 + x8 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x14 | 0;
x12 ^= u<<7 | u>>>(32-7);
u = x12 + x15 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x12 | 0;
x14 ^= u<<13 | u>>>(32-13);
u = x14 + x13 | 0;
x15 ^= u<<18 | u>>>(32-18);
}
o[ 0] = x0 >>> 0 & 0xff;
o[ 1] = x0 >>> 8 & 0xff;
o[ 2] = x0 >>> 16 & 0xff;
o[ 3] = x0 >>> 24 & 0xff;
o[ 4] = x5 >>> 0 & 0xff;
o[ 5] = x5 >>> 8 & 0xff;
o[ 6] = x5 >>> 16 & 0xff;
o[ 7] = x5 >>> 24 & 0xff;
o[ 8] = x10 >>> 0 & 0xff;
o[ 9] = x10 >>> 8 & 0xff;
o[10] = x10 >>> 16 & 0xff;
o[11] = x10 >>> 24 & 0xff;
o[12] = x15 >>> 0 & 0xff;
o[13] = x15 >>> 8 & 0xff;
o[14] = x15 >>> 16 & 0xff;
o[15] = x15 >>> 24 & 0xff;
o[16] = x6 >>> 0 & 0xff;
o[17] = x6 >>> 8 & 0xff;
o[18] = x6 >>> 16 & 0xff;
o[19] = x6 >>> 24 & 0xff;
o[20] = x7 >>> 0 & 0xff;
o[21] = x7 >>> 8 & 0xff;
o[22] = x7 >>> 16 & 0xff;
o[23] = x7 >>> 24 & 0xff;
o[24] = x8 >>> 0 & 0xff;
o[25] = x8 >>> 8 & 0xff;
o[26] = x8 >>> 16 & 0xff;
o[27] = x8 >>> 24 & 0xff;
o[28] = x9 >>> 0 & 0xff;
o[29] = x9 >>> 8 & 0xff;
o[30] = x9 >>> 16 & 0xff;
o[31] = x9 >>> 24 & 0xff;
}
function crypto_core_salsa20(out,inp,k,c) {
core_salsa20(out,inp,k,c);
}
function crypto_core_hsalsa20(out,inp,k,c) {
core_hsalsa20(out,inp,k,c);
}
var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
// "expand 32-byte k"
function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
var z = new Uint8Array(16), x = new Uint8Array(64);
var u, i;
for (i = 0; i < 16; i++) z[i] = 0;
for (i = 0; i < 8; i++) z[i] = n[i];
while (b >= 64) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
u = 1;
for (i = 8; i < 16; i++) {
u = u + (z[i] & 0xff) | 0;
z[i] = u & 0xff;
u >>>= 8;
}
b -= 64;
cpos += 64;
mpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
}
return 0;
}
function crypto_stream_salsa20(c,cpos,b,n,k) {
var z = new Uint8Array(16), x = new Uint8Array(64);
var u, i;
for (i = 0; i < 16; i++) z[i] = 0;
for (i = 0; i < 8; i++) z[i] = n[i];
while (b >= 64) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < 64; i++) c[cpos+i] = x[i];
u = 1;
for (i = 8; i < 16; i++) {
u = u + (z[i] & 0xff) | 0;
z[i] = u & 0xff;
u >>>= 8;
}
b -= 64;
cpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < b; i++) c[cpos+i] = x[i];
}
return 0;
}
function crypto_stream(c,cpos,d,n,k) {
var s = new Uint8Array(32);
crypto_core_hsalsa20(s,n,k,sigma);
var sn = new Uint8Array(8);
for (var i = 0; i < 8; i++) sn[i] = n[i+16];
return crypto_stream_salsa20(c,cpos,d,sn,s);
}
function crypto_stream_xor(c,cpos,m,mpos,d,n,k) {
var s = new Uint8Array(32);
crypto_core_hsalsa20(s,n,k,sigma);
var sn = new Uint8Array(8);
for (var i = 0; i < 8; i++) sn[i] = n[i+16];
return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
}
/*
* Port of Andrew Moon's Poly1305-donna-16. Public domain.
* https://github.com/floodyberry/poly1305-donna
*/
var poly1305 = function(key) {
this.buffer = new Uint8Array(16);
this.r = new Uint16Array(10);
this.h = new Uint16Array(10);
this.pad = new Uint16Array(8);
this.leftover = 0;
this.fin = 0;
var t0, t1, t2, t3, t4, t5, t6, t7;
t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
this.r[5] = ((t4 >>> 1)) & 0x1ffe;
t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
this.r[9] = ((t7 >>> 5)) & 0x007f;
this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
};
poly1305.prototype.blocks = function(m, mpos, bytes) {
var hibit = this.fin ? 0 : (1 << 11);
var t0, t1, t2, t3, t4, t5, t6, t7, c;
var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
var h0 = this.h[0],
h1 = this.h[1],
h2 = this.h[2],
h3 = this.h[3],
h4 = this.h[4],
h5 = this.h[5],
h6 = this.h[6],
h7 = this.h[7],
h8 = this.h[8],
h9 = this.h[9];
var r0 = this.r[0],
r1 = this.r[1],
r2 = this.r[2],
r3 = this.r[3],
r4 = this.r[4],
r5 = this.r[5],
r6 = this.r[6],
r7 = this.r[7],
r8 = this.r[8],
r9 = this.r[9];
while (bytes >= 16) {
t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
h5 += ((t4 >>> 1)) & 0x1fff;
t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
h9 += ((t7 >>> 5)) | hibit;
c = 0;
d0 = c;
d0 += h0 * r0;
d0 += h1 * (5 * r9);
d0 += h2 * (5 * r8);
d0 += h3 * (5 * r7);
d0 += h4 * (5 * r6);
c = (d0 >>> 13); d0 &= 0x1fff;
d0 += h5 * (5 * r5);
d0 += h6 * (5 * r4);
d0 += h7 * (5 * r3);
d0 += h8 * (5 * r2);
d0 += h9 * (5 * r1);
c += (d0 >>> 13); d0 &= 0x1fff;
d1 = c;
d1 += h0 * r1;
d1 += h1 * r0;
d1 += h2 * (5 * r9);
d1 += h3 * (5 * r8);
d1 += h4 * (5 * r7);
c = (d1 >>> 13); d1 &= 0x1fff;
d1 += h5 * (5 * r6);
d1 += h6 * (5 * r5);
d1 += h7 * (5 * r4);
d1 += h8 * (5 * r3);
d1 += h9 * (5 * r2);
c += (d1 >>> 13); d1 &= 0x1fff;
d2 = c;
d2 += h0 * r2;
d2 += h1 * r1;
d2 += h2 * r0;
d2 += h3 * (5 * r9);
d2 += h4 * (5 * r8);
c = (d2 >>> 13); d2 &= 0x1fff;
d2 += h5 * (5 * r7);
d2 += h6 * (5 * r6);
d2 += h7 * (5 * r5);
d2 += h8 * (5 * r4);
d2 += h9 * (5 * r3);
c += (d2 >>> 13); d2 &= 0x1fff;
d3 = c;
d3 += h0 * r3;
d3 += h1 * r2;
d3 += h2 * r1;
d3 += h3 * r0;
d3 += h4 * (5 * r9);
c = (d3 >>> 13); d3 &= 0x1fff;
d3 += h5 * (5 * r8);
d3 += h6 * (5 * r7);
d3 += h7 * (5 * r6);
d3 += h8 * (5 * r5);
d3 += h9 * (5 * r4);
c += (d3 >>> 13); d3 &= 0x1fff;
d4 = c;
d4 += h0 * r4;
d4 += h1 * r3;
d4 += h2 * r2;
d4 += h3 * r1;
d4 += h4 * r0;
c = (d4 >>> 13); d4 &= 0x1fff;
d4 += h5 * (5 * r9);
d4 += h6 * (5 * r8);
d4 += h7 * (5 * r7);
d4 += h8 * (5 * r6);
d4 += h9 * (5 * r5);
c += (d4 >>> 13); d4 &= 0x1fff;
d5 = c;
d5 += h0 * r5;
d5 += h1 * r4;
d5 += h2 * r3;
d5 += h3 * r2;
d5 += h4 * r1;
c = (d5 >>> 13); d5 &= 0x1fff;
d5 += h5 * r0;
d5 += h6 * (5 * r9);
d5 += h7 * (5 * r8);
d5 += h8 * (5 * r7);
d5 += h9 * (5 * r6);
c += (d5 >>> 13); d5 &= 0x1fff;
d6 = c;
d6 += h0 * r6;
d6 += h1 * r5;
d6 += h2 * r4;
d6 += h3 * r3;
d6 += h4 * r2;
c = (d6 >>> 13); d6 &= 0x1fff;
d6 += h5 * r1;
d6 += h6 * r0;
d6 += h7 * (5 * r9);
d6 += h8 * (5 * r8);
d6 += h9 * (5 * r7);
c += (d6 >>> 13); d6 &= 0x1fff;
d7 = c;
d7 += h0 * r7;
d7 += h1 * r6;
d7 += h2 * r5;
d7 += h3 * r4;
d7 += h4 * r3;
c = (d7 >>> 13); d7 &= 0x1fff;
d7 += h5 * r2;
d7 += h6 * r1;
d7 += h7 * r0;
d7 += h8 * (5 * r9);
d7 += h9 * (5 * r8);
c += (d7 >>> 13); d7 &= 0x1fff;
d8 = c;
d8 += h0 * r8;
d8 += h1 * r7;
d8 += h2 * r6;
d8 += h3 * r5;
d8 += h4 * r4;
c = (d8 >>> 13); d8 &= 0x1fff;
d8 += h5 * r3;
d8 += h6 * r2;
d8 += h7 * r1;
d8 += h8 * r0;
d8 += h9 * (5 * r9);
c += (d8 >>> 13); d8 &= 0x1fff;
d9 = c;
d9 += h0 * r9;
d9 += h1 * r8;
d9 += h2 * r7;
d9 += h3 * r6;
d9 += h4 * r5;
c = (d9 >>> 13); d9 &= 0x1fff;
d9 += h5 * r4;
d9 += h6 * r3;
d9 += h7 * r2;
d9 += h8 * r1;
d9 += h9 * r0;
c += (d9 >>> 13); d9 &= 0x1fff;
c = (((c << 2) + c)) | 0;
c = (c + d0) | 0;
d0 = c & 0x1fff;
c = (c >>> 13);
d1 += c;
h0 = d0;
h1 = d1;
h2 = d2;
h3 = d3;
h4 = d4;
h5 = d5;
h6 = d6;
h7 = d7;
h8 = d8;
h9 = d9;
mpos += 16;
bytes -= 16;
}
this.h[0] = h0;
this.h[1] = h1;
this.h[2] = h2;
this.h[3] = h3;
this.h[4] = h4;
this.h[5] = h5;
this.h[6] = h6;
this.h[7] = h7;
this.h[8] = h8;
this.h[9] = h9;
};
poly1305.prototype.finish = function(mac, macpos) {
var g = new Uint16Array(10);
var c, mask, f, i;
if (this.leftover) {
i = this.leftover;
this.buffer[i++] = 1;
for (; i < 16; i++) this.buffer[i] = 0;
this.fin = 1;
this.blocks(this.buffer, 0, 16);
}
c = this.h[1] >>> 13;
this.h[1] &= 0x1fff;
for (i = 2; i < 10; i++) {
this.h[i] += c;
c = this.h[i] >>> 13;
this.h[i] &= 0x1fff;
}
this.h[0] += (c * 5);
c = this.h[0] >>> 13;
this.h[0] &= 0x1fff;
this.h[1] += c;
c = this.h[1] >>> 13;
this.h[1] &= 0x1fff;
this.h[2] += c;
g[0] = this.h[0] + 5;
c = g[0] >>> 13;
g[0] &= 0x1fff;
for (i = 1; i < 10; i++) {
g[i] = this.h[i] + c;
c = g[i] >>> 13;
g[i] &= 0x1fff;
}
g[9] -= (1 << 13);
mask = (c ^ 1) - 1;
for (i = 0; i < 10; i++) g[i] &= mask;
mask = ~mask;
for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
f = this.h[0] + this.pad[0];
this.h[0] = f & 0xffff;
for (i = 1; i < 8; i++) {
f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
this.h[i] = f & 0xffff;
}
mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;
mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;
mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;
mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;
mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;
mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;
mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;
mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;
mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;
mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;
mac[macpos+10] = (this.h[5] >>> 0) & 0xff;
mac[macpos+11] = (this.h[5] >>> 8) & 0xff;
mac[macpos+12] = (this.h[6] >>> 0) & 0xff;
mac[macpos+13] = (this.h[6] >>> 8) & 0xff;
mac[macpos+14] = (this.h[7] >>> 0) & 0xff;
mac[macpos+15] = (this.h[7] >>> 8) & 0xff;
};
poly1305.prototype.update = function(m, mpos, bytes) {
var i, want;
if (this.leftover) {
want = (16 - this.leftover);
if (want > bytes)
want = bytes;
for (i = 0; i < want; i++)
this.buffer[this.leftover + i] = m[mpos+i];
bytes -= want;
mpos += want;
this.leftover += want;
if (this.leftover < 16)
return;
this.blocks(this.buffer, 0, 16);
this.leftover = 0;
}
if (bytes >= 16) {
want = bytes - (bytes % 16);
this.blocks(m, mpos, want);
mpos += want;
bytes -= want;
}
if (bytes) {
for (i = 0; i < bytes; i++)
this.buffer[this.leftover + i] = m[mpos+i];
this.leftover += bytes;
}
};
function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
var s = new poly1305(k);
s.update(m, mpos, n);
s.finish(out, outpos);
return 0;
}
function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
var x = new Uint8Array(16);
crypto_onetimeauth(x,0,m,mpos,n,k);
return crypto_verify_16(h,hpos,x,0);
}
function crypto_secretbox(c,m,d,n,k) {
var i;
if (d < 32) return -1;
crypto_stream_xor(c,0,m,0,d,n,k);
crypto_onetimeauth(c, 16, c, 32, d - 32, c);
for (i = 0; i < 16; i++) c[i] = 0;
return 0;
}
function crypto_secretbox_open(m,c,d,n,k) {
var i;
var x = new Uint8Array(32);
if (d < 32) return -1;
crypto_stream(x,0,32,n,k);
if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;
crypto_stream_xor(m,0,c,0,d,n,k);
for (i = 0; i < 32; i++) m[i] = 0;
return 0;
}
function set25519(r, a) {
var i;
for (i = 0; i < 16; i++) r[i] = a[i]|0;
}
function car25519(o) {
var i, v, c = 1;
for (i = 0; i < 16; i++) {
v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c-1 + 37 * (c-1);
}
function sel25519(p, q, b) {
var t, c = ~(b-1);
for (var i = 0; i < 16; i++) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function pack25519(o, n) {
var i, j, b;
var m = gf(), t = gf();
for (i = 0; i < 16; i++) t[i] = n[i];
car25519(t);
car25519(t);
car25519(t);
for (j = 0; j < 2; j++) {
m[0] = t[0] - 0xffed;
for (i = 1; i < 15; i++) {
m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
m[i-1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
b = (m[15]>>16) & 1;
m[14] &= 0xffff;
sel25519(t, m, 1-b);
}
for (i = 0; i < 16; i++) {
o[2*i] = t[i] & 0xff;
o[2*i+1] = t[i]>>8;
}
}
function neq25519(a, b) {
var c = new Uint8Array(32), d = new Uint8Array(32);
pack25519(c, a);
pack25519(d, b);
return crypto_verify_32(c, 0, d, 0);
}
function par25519(a) {
var d = new Uint8Array(32);
pack25519(d, a);
return d[0] & 1;
}
function unpack25519(o, n) {
var i;
for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
o[15] &= 0x7fff;
}
function A(o, a, b) {
for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
}
function Z(o, a, b) {
for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
}
function M(o, a, b) {
var v, c,
t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3],
b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7],
b8 = b[8],
b9 = b[9],
b10 = b[10],
b11 = b[11],
b12 = b[12],
b13 = b[13],
b14 = b[14],
b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
// t15 left as is
// first car
c = 1;
v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
t0 += c-1 + 37 * (c-1);
// second car
c = 1;
v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
t0 += c-1 + 37 * (c-1);
o[ 0] = t0;
o[ 1] = t1;
o[ 2] = t2;
o[ 3] = t3;
o[ 4] = t4;
o[ 5] = t5;
o[ 6] = t6;
o[ 7] = t7;
o[ 8] = t8;
o[ 9] = t9;
o[10] = t10;
o[11] = t11;
o[12] = t12;
o[13] = t13;
o[14] = t14;
o[15] = t15;
}
function S(o, a) {
M(o, a, a);
}
function inv25519(o, i) {
var c = gf();
var a;
for (a = 0; a < 16; a++) c[a] = i[a];
for (a = 253; a >= 0; a--) {
S(c, c);
if(a !== 2 && a !== 4) M(c, c, i);
}
for (a = 0; a < 16; a++) o[a] = c[a];
}
function pow2523(o, i) {
var c = gf();
var a;
for (a = 0; a < 16; a++) c[a] = i[a];
for (a = 250; a >= 0; a--) {
S(c, c);
if(a !== 1) M(c, c, i);
}
for (a = 0; a < 16; a++) o[a] = c[a];
}
function crypto_scalarmult(q, n, p) {
var z = new Uint8Array(32);
var x = new Float64Array(80), r, i;
var a = gf(), b = gf(), c = gf(),
d = gf(), e = gf(), f = gf();
for (i = 0; i < 31; i++) z[i] = n[i];
z[31]=(n[31]&127)|64;
z[0]&=248;
unpack25519(x,p);
for (i = 0; i < 16; i++) {
b[i]=x[i];
d[i]=a[i]=c[i]=0;
}
a[0]=d[0]=1;
for (i=254; i>=0; --i) {
r=(z[i>>>3]>>>(i&7))&1;
sel25519(a,b,r);
sel25519(c,d,r);
A(e,a,c);
Z(a,a,c);
A(c,b,d);
Z(b,b,d);
S(d,e);
S(f,a);
M(a,c,a);
M(c,b,e);
A(e,a,c);
Z(a,a,c);
S(b,a);
Z(c,d,f);
M(a,c,_121665);
A(a,a,d);
M(c,c,a);
M(a,d,f);
M(d,b,x);
S(b,e);
sel25519(a,b,r);
sel25519(c,d,r);
}
for (i = 0; i < 16; i++) {
x[i+16]=a[i];
x[i+32]=c[i];
x[i+48]=b[i];
x[i+64]=d[i];
}
var x32 = x.subarray(32);
var x16 = x.subarray(16);
inv25519(x32,x32);
M(x16,x16,x32);
pack25519(q,x16);
return 0;
}
function crypto_scalarmult_base(q, n) {
return crypto_scalarmult(q, n, _9);
}
function crypto_box_keypair(y, x) {
randombytes(x, 32);
return crypto_scalarmult_base(y, x);
}
function crypto_box_beforenm(k, y, x) {
var s = new Uint8Array(32);
crypto_scalarmult(s, x, y);
return crypto_core_hsalsa20(k, _0, s, sigma);
}
var crypto_box_afternm = crypto_secretbox;
var crypto_box_open_afternm = crypto_secretbox_open;
function crypto_box(c, m, d, n, y, x) {
var k = new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_afternm(c, m, d, n, k);
}
function crypto_box_open(m, c, d, n, y, x) {
var k = new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_open_afternm(m, c, d, n, k);
}
var K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];
function crypto_hashblocks_hl(hh, hl, m, n) {
var wh = new Int32Array(16), wl = new Int32Array(16),
bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
th, tl, i, j, h, l, a, b, c, d;
var ah0 = hh[0],
ah1 = hh[1],
ah2 = hh[2],
ah3 = hh[3],
ah4 = hh[4],
ah5 = hh[5],
ah6 = hh[6],
ah7 = hh[7],
al0 = hl[0],
al1 = hl[1],
al2 = hl[2],
al3 = hl[3],
al4 = hl[4],
al5 = hl[5],
al6 = hl[6],
al7 = hl[7];
var pos = 0;
while (n >= 128) {
for (i = 0; i < 16; i++) {
j = 8 * i + pos;
wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
}
for (i = 0; i < 80; i++) {
bh0 = ah0;
bh1 = ah1;
bh2 = ah2;
bh3 = ah3;
bh4 = ah4;
bh5 = ah5;
bh6 = ah6;
bh7 = ah7;
bl0 = al0;
bl1 = al1;
bl2 = al2;
bl3 = al3;
bl4 = al4;
bl5 = al5;
bl6 = al6;
bl7 = al7;
// add
h = ah7;
l = al7;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
// Sigma1
h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// Ch
h = (ah4 & ah5) ^ (~ah4 & ah6);
l = (al4 & al5) ^ (~al4 & al6);
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// K
h = K[i*2];
l = K[i*2+1];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// w
h = wh[i%16];
l = wl[i%16];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
th = c & 0xffff | d << 16;
tl = a & 0xffff | b << 16;
// add
h = th;
l = tl;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
// Sigma0
h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// Maj
h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh7 = (c & 0xffff) | (d << 16);
bl7 = (a & 0xffff) | (b << 16);
// add
h = bh3;
l = bl3;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = th;
l = tl;
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh3 = (c & 0xffff) | (d << 16);
bl3 = (a & 0xffff) | (b << 16);
ah1 = bh0;
ah2 = bh1;
ah3 = bh2;
ah4 = bh3;
ah5 = bh4;
ah6 = bh5;
ah7 = bh6;
ah0 = bh7;
al1 = bl0;
al2 = bl1;
al3 = bl2;
al4 = bl3;
al5 = bl4;
al6 = bl5;
al7 = bl6;
al0 = bl7;
if (i%16 === 15) {
for (j = 0; j < 16; j++) {
// add
h = wh[j];
l = wl[j];
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = wh[(j+9)%16];
l = wl[(j+9)%16];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// sigma0
th = wh[(j+1)%16];
tl = wl[(j+1)%16];
h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// sigma1
th = wh[(j+14)%16];
tl = wl[(j+14)%16];
h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
wh[j] = (c & 0xffff) | (d << 16);
wl[j] = (a & 0xffff) | (b << 16);
}
}
}
// add
h = ah0;
l = al0;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[0];
l = hl[0];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[0] = ah0 = (c & 0xffff) | (d << 16);
hl[0] = al0 = (a & 0xffff) | (b << 16);
h = ah1;
l = al1;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[1];
l = hl[1];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[1] = ah1 = (c & 0xffff) | (d << 16);
hl[1] = al1 = (a & 0xffff) | (b << 16);
h = ah2;
l = al2;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[2];
l = hl[2];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[2] = ah2 = (c & 0xffff) | (d << 16);
hl[2] = al2 = (a & 0xffff) | (b << 16);
h = ah3;
l = al3;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[3];
l = hl[3];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[3] = ah3 = (c & 0xffff) | (d << 16);
hl[3] = al3 = (a & 0xffff) | (b << 16);
h = ah4;
l = al4;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[4];
l = hl[4];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[4] = ah4 = (c & 0xffff) | (d << 16);
hl[4] = al4 = (a & 0xffff) | (b << 16);
h = ah5;
l = al5;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[5];
l = hl[5];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[5] = ah5 = (c & 0xffff) | (d << 16);
hl[5] = al5 = (a & 0xffff) | (b << 16);
h = ah6;
l = al6;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[6];
l = hl[6];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[6] = ah6 = (c & 0xffff) | (d << 16);
hl[6] = al6 = (a & 0xffff) | (b << 16);
h = ah7;
l = al7;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[7];
l = hl[7];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[7] = ah7 = (c & 0xffff) | (d << 16);
hl[7] = al7 = (a & 0xffff) | (b << 16);
pos += 128;
n -= 128;
}
return n;
}
function crypto_hash(out, m, n) {
var hh = new Int32Array(8),
hl = new Int32Array(8),
x = new Uint8Array(256),
i, b = n;
hh[0] = 0x6a09e667;
hh[1] = 0xbb67ae85;
hh[2] = 0x3c6ef372;
hh[3] = 0xa54ff53a;
hh[4] = 0x510e527f;
hh[5] = 0x9b05688c;
hh[6] = 0x1f83d9ab;
hh[7] = 0x5be0cd19;
hl[0] = 0xf3bcc908;
hl[1] = 0x84caa73b;
hl[2] = 0xfe94f82b;
hl[3] = 0x5f1d36f1;
hl[4] = 0xade682d1;
hl[5] = 0x2b3e6c1f;
hl[6] = 0xfb41bd6b;
hl[7] = 0x137e2179;
crypto_hashblocks_hl(hh, hl, m, n);
n %= 128;
for (i = 0; i < n; i++) x[i] = m[b-n+i];
x[n] = 128;
n = 256-128*(n<112?1:0);
x[n-9] = 0;
ts64(x, n-8, (b / 0x20000000) | 0, b << 3);
crypto_hashblocks_hl(hh, hl, x, n);
for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);
return 0;
}
function add(p, q) {
var a = gf(), b = gf(), c = gf(),
d = gf(), e = gf(), f = gf(),
g = gf(), h = gf(), t = gf();
Z(a, p[1], p[0]);
Z(t, q[1], q[0]);
M(a, a, t);
A(b, p[0], p[1]);
A(t, q[0], q[1]);
M(b, b, t);
M(c, p[3], q[3]);
M(c, c, D2);
M(d, p[2], q[2]);
A(d, d, d);
Z(e, b, a);
Z(f, d, c);
A(g, d, c);
A(h, b, a);
M(p[0], e, f);
M(p[1], h, g);
M(p[2], g, f);
M(p[3], e, h);
}
function cswap(p, q, b) {
var i;
for (i = 0; i < 4; i++) {
sel25519(p[i], q[i], b);
}
}
function pack(r, p) {
var tx = gf(), ty = gf(), zi = gf();
inv25519(zi, p[2]);
M(tx, p[0], zi);
M(ty, p[1], zi);
pack25519(r, ty);
r[31] ^= par25519(tx) << 7;
}
function scalarmult(p, q, s) {
var b, i;
set25519(p[0], gf0);
set25519(p[1], gf1);
set25519(p[2], gf1);
set25519(p[3], gf0);
for (i = 255; i >= 0; --i) {
b = (s[(i/8)|0] >> (i&7)) & 1;
cswap(p, q, b);
add(q, p);
add(p, p);
cswap(p, q, b);
}
}
function scalarbase(p, s) {
var q = [gf(), gf(), gf(), gf()];
set25519(q[0], X);
set25519(q[1], Y);
set25519(q[2], gf1);
M(q[3], X, Y);
scalarmult(p, q, s);
}
function crypto_sign_keypair(pk, sk, seeded) {
var d = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()];
var i;
if (!seeded) randombytes(sk, 32);
crypto_hash(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
scalarbase(p, d);
pack(pk, p);
for (i = 0; i < 32; i++) sk[i+32] = pk[i];
return 0;
}
var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
function modL(r, x) {
var carry, i, j, k;
for (i = 63; i >= 32; --i) {
carry = 0;
for (j = i - 32, k = i - 12; j < k; ++j) {
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
carry = (x[j] + 128) >> 8;
x[j] -= carry * 256;
}
x[j] += carry;
x[i] = 0;
}
carry = 0;
for (j = 0; j < 32; j++) {
x[j] += carry - (x[31] >> 4) * L[j];
carry = x[j] >> 8;
x[j] &= 255;
}
for (j = 0; j < 32; j++) x[j] -= carry * L[j];
for (i = 0; i < 32; i++) {
x[i+1] += x[i] >> 8;
r[i] = x[i] & 255;
}
}
function reduce(r) {
var x = new Float64Array(64), i;
for (i = 0; i < 64; i++) x[i] = r[i];
for (i = 0; i < 64; i++) r[i] = 0;
modL(r, x);
}
// Note: difference from C - smlen returned, not passed as argument.
function crypto_sign(sm, m, n, sk) {
var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
var i, j, x = new Float64Array(64);
var p = [gf(), gf(), gf(), gf()];
crypto_hash(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
var smlen = n + 64;
for (i = 0; i < n; i++) sm[64 + i] = m[i];
for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
crypto_hash(r, sm.subarray(32), n+32);
reduce(r);
scalarbase(p, r);
pack(sm, p);
for (i = 32; i < 64; i++) sm[i] = sk[i];
crypto_hash(h, sm, n + 64);
reduce(h);
for (i = 0; i < 64; i++) x[i] = 0;
for (i = 0; i < 32; i++) x[i] = r[i];
for (i = 0; i < 32; i++) {
for (j = 0; j < 32; j++) {
x[i+j] += h[i] * d[j];
}
}
modL(sm.subarray(32), x);
return smlen;
}
function unpackneg(r, p) {
var t = gf(), chk = gf(), num = gf(),
den = gf(), den2 = gf(), den4 = gf(),
den6 = gf();
set25519(r[2], gf1);
unpack25519(r[1], p);
S(num, r[1]);
M(den, num, D);
Z(num, num, r[2]);
A(den, r[2], den);
S(den2, den);
S(den4, den2);
M(den6, den4, den2);
M(t, den6, num);
M(t, t, den);
pow2523(t, t);
M(t, t, num);
M(t, t, den);
M(t, t, den);
M(r[0], t, den);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) M(r[0], r[0], I);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) return -1;
if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
M(r[3], r[0], r[1]);
return 0;
}
function crypto_sign_open(m, sm, n, pk) {
var i, mlen;
var t = new Uint8Array(32), h = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()],
q = [gf(), gf(), gf(), gf()];
mlen = -1;
if (n < 64) return -1;
if (unpackneg(q, pk)) return -1;
for (i = 0; i < n; i++) m[i] = sm[i];
for (i = 0; i < 32; i++) m[i+32] = pk[i];
crypto_hash(h, m, n);
reduce(h);
scalarmult(p, q, h);
scalarbase(q, sm.subarray(32));
add(p, q);
pack(t, p);
n -= 64;
if (crypto_verify_32(sm, 0, t, 0)) {
for (i = 0; i < n; i++) m[i] = 0;
return -1;
}
for (i = 0; i < n; i++) m[i] = sm[i + 64];
mlen = n;
return mlen;
}
var crypto_secretbox_KEYBYTES = 32,
crypto_secretbox_NONCEBYTES = 24,
crypto_secretbox_ZEROBYTES = 32,
crypto_secretbox_BOXZEROBYTES = 16,
crypto_scalarmult_BYTES = 32,
crypto_scalarmult_SCALARBYTES = 32,
crypto_box_PUBLICKEYBYTES = 32,
crypto_box_SECRETKEYBYTES = 32,
crypto_box_BEFORENMBYTES = 32,
crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
crypto_sign_BYTES = 64,
crypto_sign_PUBLICKEYBYTES = 32,
crypto_sign_SECRETKEYBYTES = 64,
crypto_sign_SEEDBYTES = 32,
crypto_hash_BYTES = 64;
nacl.lowlevel = {
crypto_core_hsalsa20: crypto_core_hsalsa20,
crypto_stream_xor: crypto_stream_xor,
crypto_stream: crypto_stream,
crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
crypto_stream_salsa20: crypto_stream_salsa20,
crypto_onetimeauth: crypto_onetimeauth,
crypto_onetimeauth_verify: crypto_onetimeauth_verify,
crypto_verify_16: crypto_verify_16,
crypto_verify_32: crypto_verify_32,
crypto_secretbox: crypto_secretbox,
crypto_secretbox_open: crypto_secretbox_open,
crypto_scalarmult: crypto_scalarmult,
crypto_scalarmult_base: crypto_scalarmult_base,
crypto_box_beforenm: crypto_box_beforenm,
crypto_box_afternm: crypto_box_afternm,
crypto_box: crypto_box,
crypto_box_open: crypto_box_open,
crypto_box_keypair: crypto_box_keypair,
crypto_hash: crypto_hash,
crypto_sign: crypto_sign,
crypto_sign_keypair: crypto_sign_keypair,
crypto_sign_open: crypto_sign_open,
crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
crypto_sign_BYTES: crypto_sign_BYTES,
crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
crypto_hash_BYTES: crypto_hash_BYTES
};
/* High-level API */
function checkLengths(k, n) {
if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
}
function checkBoxLengths(pk, sk) {
if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');
if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');
}
function checkArrayTypes() {
var t, i;
for (i = 0; i < arguments.length; i++) {
if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')
throw new TypeError('unexpected type ' + t + ', use Uint8Array');
}
}
function cleanup(arr) {
for (var i = 0; i < arr.length; i++) arr[i] = 0;
}
// TODO: Completely remove this in v0.15.
if (!nacl.util) {
nacl.util = {};
nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {
throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');
};
}
nacl.randomBytes = function(n) {
var b = new Uint8Array(n);
randombytes(b, n);
return b;
};
nacl.secretbox = function(msg, nonce, key) {
checkArrayTypes(msg, nonce, key);
checkLengths(key, nonce);
var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
var c = new Uint8Array(m.length);
for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];
crypto_secretbox(c, m, m.length, nonce, key);
return c.subarray(crypto_secretbox_BOXZEROBYTES);
};
nacl.secretbox.open = function(box, nonce, key) {
checkArrayTypes(box, nonce, key);
checkLengths(key, nonce);
var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
var m = new Uint8Array(c.length);
for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];
if (c.length < 32) return false;
if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;
return m.subarray(crypto_secretbox_ZEROBYTES);
};
nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
nacl.scalarMult = function(n, p) {
checkArrayTypes(n, p);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult(q, n, p);
return q;
};
nacl.scalarMult.base = function(n) {
checkArrayTypes(n);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult_base(q, n);
return q;
};
nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
nacl.box = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox(msg, nonce, k);
};
nacl.box.before = function(publicKey, secretKey) {
checkArrayTypes(publicKey, secretKey);
checkBoxLengths(publicKey, secretKey);
var k = new Uint8Array(crypto_box_BEFORENMBYTES);
crypto_box_beforenm(k, publicKey, secretKey);
return k;
};
nacl.box.after = nacl.secretbox;
nacl.box.open = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox.open(msg, nonce, k);
};
nacl.box.open.after = nacl.secretbox.open;
nacl.box.keyPair = function() {
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
crypto_box_keypair(pk, sk);
return {publicKey: pk, secretKey: sk};
};
nacl.box.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_box_SECRETKEYBYTES)
throw new Error('bad secret key size');
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
crypto_scalarmult_base(pk, secretKey);
return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
};
nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
nacl.box.nonceLength = crypto_box_NONCEBYTES;
nacl.box.overheadLength = nacl.secretbox.overheadLength;
nacl.sign = function(msg, secretKey) {
checkArrayTypes(msg, secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
throw new Error('bad secret key size');
var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
crypto_sign(signedMsg, msg, msg.length, secretKey);
return signedMsg;
};
nacl.sign.open = function(signedMsg, publicKey) {
if (arguments.length !== 2)
throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');
checkArrayTypes(signedMsg, publicKey);
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
throw new Error('bad public key size');
var tmp = new Uint8Array(signedMsg.length);
var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
if (mlen < 0) return null;
var m = new Uint8Array(mlen);
for (var i = 0; i < m.length; i++) m[i] = tmp[i];
return m;
};
nacl.sign.detached = function(msg, secretKey) {
var signedMsg = nacl.sign(msg, secretKey);
var sig = new Uint8Array(crypto_sign_BYTES);
for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
return sig;
};
nacl.sign.detached.verify = function(msg, sig, publicKey) {
checkArrayTypes(msg, sig, publicKey);
if (sig.length !== crypto_sign_BYTES)
throw new Error('bad signature size');
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
throw new Error('bad public key size');
var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
var m = new Uint8Array(crypto_sign_BYTES + msg.length);
var i;
for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
};
nacl.sign.keyPair = function() {
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
crypto_sign_keypair(pk, sk);
return {publicKey: pk, secretKey: sk};
};
nacl.sign.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
throw new Error('bad secret key size');
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
};
nacl.sign.keyPair.fromSeed = function(seed) {
checkArrayTypes(seed);
if (seed.length !== crypto_sign_SEEDBYTES)
throw new Error('bad seed size');
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
for (var i = 0; i < 32; i++) sk[i] = seed[i];
crypto_sign_keypair(pk, sk, true);
return {publicKey: pk, secretKey: sk};
};
nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
nacl.sign.seedLength = crypto_sign_SEEDBYTES;
nacl.sign.signatureLength = crypto_sign_BYTES;
nacl.hash = function(msg) {
checkArrayTypes(msg);
var h = new Uint8Array(crypto_hash_BYTES);
crypto_hash(h, msg, msg.length);
return h;
};
nacl.hash.hashLength = crypto_hash_BYTES;
nacl.verify = function(x, y) {
checkArrayTypes(x, y);
// Zero length arguments are considered not equal.
if (x.length === 0 || y.length === 0) return false;
if (x.length !== y.length) return false;
return (vn(x, 0, y, 0, x.length) === 0) ? true : false;
};
nacl.setPRNG = function(fn) {
randombytes = fn;
};
(function() {
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
if (crypto && crypto.getRandomValues) {
// Browsers.
var QUOTA = 65536;
nacl.setPRNG(function(x, n) {
var i, v = new Uint8Array(n);
for (i = 0; i < n; i += QUOTA) {
crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
}
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
} else if (typeof require !== 'undefined') {
// Node.js.
crypto = require('crypto');
if (crypto && crypto.randomBytes) {
nacl.setPRNG(function(x, n) {
var i, v = crypto.randomBytes(n);
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
}
}
})();
})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
},{"crypto":61}],89:[function(require,module,exports){
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/(function(global,factory){/* global define, require, module */ /* AMD */if(typeof define==='function'&&define.amd)define(["protobufjs/minimal"],factory);/* CommonJS */else if(typeof require==='function'&&(typeof module==="undefined"?"undefined":(0,_typeof2["default"])(module))==='object'&&module&&module.exports)module.exports=factory(require("protobufjs/minimal"));})(void 0,function($protobuf){"use strict";// Common aliases
var $Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util;// Exported root namespace
var $root=$protobuf.roots["default"]||($protobuf.roots["default"]={});$root.exonum=function(){/**
* Namespace exonum.
* @exports exonum
* @namespace
*/var exonum={};exonum.crypto=function(){/**
* Namespace crypto.
* @memberof exonum
* @namespace
*/var crypto={};crypto.Hash=function(){/**
* Properties of a Hash.
* @memberof exonum.crypto
* @interface IHash
* @property {Uint8Array|null} [data] Hash data
*/ /**
* Constructs a new Hash.
* @memberof exonum.crypto
* @classdesc Represents a Hash.
* @implements IHash
* @constructor
* @param {exonum.crypto.IHash=} [properties] Properties to set
*/function Hash(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Hash data.
* @member {Uint8Array} data
* @memberof exonum.crypto.Hash
* @instance
*/Hash.prototype.data=$util.newBuffer([]);/**
* Creates a new Hash instance using the specified properties.
* @function create
* @memberof exonum.crypto.Hash
* @static
* @param {exonum.crypto.IHash=} [properties] Properties to set
* @returns {exonum.crypto.Hash} Hash instance
*/Hash.create=function create(properties){return new Hash(properties);};/**
* Encodes the specified Hash message. Does not implicitly {@link exonum.crypto.Hash.verify|verify} messages.
* @function encode
* @memberof exonum.crypto.Hash
* @static
* @param {exonum.crypto.IHash} message Hash message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Hash.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.data!=null&&message.hasOwnProperty("data"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.data);return writer;};/**
* Encodes the specified Hash message, length delimited. Does not implicitly {@link exonum.crypto.Hash.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.crypto.Hash
* @static
* @param {exonum.crypto.IHash} message Hash message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Hash.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Hash message from the specified reader or buffer.
* @function decode
* @memberof exonum.crypto.Hash
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.crypto.Hash} Hash
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Hash.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.crypto.Hash();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.data=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Hash message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.crypto.Hash
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.crypto.Hash} Hash
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Hash.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Hash message.
* @function verify
* @memberof exonum.crypto.Hash
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Hash.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.data!=null&&message.hasOwnProperty("data"))if(!(message.data&&typeof message.data.length==="number"||$util.isString(message.data)))return"data: buffer expected";return null;};/**
* Creates a Hash message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.crypto.Hash
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.crypto.Hash} Hash
*/Hash.fromObject=function fromObject(object){if(object instanceof $root.exonum.crypto.Hash)return object;var message=new $root.exonum.crypto.Hash();if(object.data!=null)if(typeof object.data==="string")$util.base64.decode(object.data,message.data=$util.newBuffer($util.base64.length(object.data)),0);else if(object.data.length)message.data=object.data;return message;};/**
* Creates a plain object from a Hash message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.crypto.Hash
* @static
* @param {exonum.crypto.Hash} message Hash
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Hash.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults)if(options.bytes===String)object.data="";else{object.data=[];if(options.bytes!==Array)object.data=$util.newBuffer(object.data);}if(message.data!=null&&message.hasOwnProperty("data"))object.data=options.bytes===String?$util.base64.encode(message.data,0,message.data.length):options.bytes===Array?Array.prototype.slice.call(message.data):message.data;return object;};/**
* Converts this Hash to JSON.
* @function toJSON
* @memberof exonum.crypto.Hash
* @instance
* @returns {Object.<string,*>} JSON object
*/Hash.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Hash;}();crypto.PublicKey=function(){/**
* Properties of a PublicKey.
* @memberof exonum.crypto
* @interface IPublicKey
* @property {Uint8Array|null} [data] PublicKey data
*/ /**
* Constructs a new PublicKey.
* @memberof exonum.crypto
* @classdesc Represents a PublicKey.
* @implements IPublicKey
* @constructor
* @param {exonum.crypto.IPublicKey=} [properties] Properties to set
*/function PublicKey(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* PublicKey data.
* @member {Uint8Array} data
* @memberof exonum.crypto.PublicKey
* @instance
*/PublicKey.prototype.data=$util.newBuffer([]);/**
* Creates a new PublicKey instance using the specified properties.
* @function create
* @memberof exonum.crypto.PublicKey
* @static
* @param {exonum.crypto.IPublicKey=} [properties] Properties to set
* @returns {exonum.crypto.PublicKey} PublicKey instance
*/PublicKey.create=function create(properties){return new PublicKey(properties);};/**
* Encodes the specified PublicKey message. Does not implicitly {@link exonum.crypto.PublicKey.verify|verify} messages.
* @function encode
* @memberof exonum.crypto.PublicKey
* @static
* @param {exonum.crypto.IPublicKey} message PublicKey message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PublicKey.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.data!=null&&message.hasOwnProperty("data"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.data);return writer;};/**
* Encodes the specified PublicKey message, length delimited. Does not implicitly {@link exonum.crypto.PublicKey.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.crypto.PublicKey
* @static
* @param {exonum.crypto.IPublicKey} message PublicKey message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PublicKey.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a PublicKey message from the specified reader or buffer.
* @function decode
* @memberof exonum.crypto.PublicKey
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.crypto.PublicKey} PublicKey
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PublicKey.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.crypto.PublicKey();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.data=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a PublicKey message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.crypto.PublicKey
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.crypto.PublicKey} PublicKey
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PublicKey.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a PublicKey message.
* @function verify
* @memberof exonum.crypto.PublicKey
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/PublicKey.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.data!=null&&message.hasOwnProperty("data"))if(!(message.data&&typeof message.data.length==="number"||$util.isString(message.data)))return"data: buffer expected";return null;};/**
* Creates a PublicKey message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.crypto.PublicKey
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.crypto.PublicKey} PublicKey
*/PublicKey.fromObject=function fromObject(object){if(object instanceof $root.exonum.crypto.PublicKey)return object;var message=new $root.exonum.crypto.PublicKey();if(object.data!=null)if(typeof object.data==="string")$util.base64.decode(object.data,message.data=$util.newBuffer($util.base64.length(object.data)),0);else if(object.data.length)message.data=object.data;return message;};/**
* Creates a plain object from a PublicKey message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.crypto.PublicKey
* @static
* @param {exonum.crypto.PublicKey} message PublicKey
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/PublicKey.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults)if(options.bytes===String)object.data="";else{object.data=[];if(options.bytes!==Array)object.data=$util.newBuffer(object.data);}if(message.data!=null&&message.hasOwnProperty("data"))object.data=options.bytes===String?$util.base64.encode(message.data,0,message.data.length):options.bytes===Array?Array.prototype.slice.call(message.data):message.data;return object;};/**
* Converts this PublicKey to JSON.
* @function toJSON
* @memberof exonum.crypto.PublicKey
* @instance
* @returns {Object.<string,*>} JSON object
*/PublicKey.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return PublicKey;}();crypto.Signature=function(){/**
* Properties of a Signature.
* @memberof exonum.crypto
* @interface ISignature
* @property {Uint8Array|null} [data] Signature data
*/ /**
* Constructs a new Signature.
* @memberof exonum.crypto
* @classdesc Represents a Signature.
* @implements ISignature
* @constructor
* @param {exonum.crypto.ISignature=} [properties] Properties to set
*/function Signature(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Signature data.
* @member {Uint8Array} data
* @memberof exonum.crypto.Signature
* @instance
*/Signature.prototype.data=$util.newBuffer([]);/**
* Creates a new Signature instance using the specified properties.
* @function create
* @memberof exonum.crypto.Signature
* @static
* @param {exonum.crypto.ISignature=} [properties] Properties to set
* @returns {exonum.crypto.Signature} Signature instance
*/Signature.create=function create(properties){return new Signature(properties);};/**
* Encodes the specified Signature message. Does not implicitly {@link exonum.crypto.Signature.verify|verify} messages.
* @function encode
* @memberof exonum.crypto.Signature
* @static
* @param {exonum.crypto.ISignature} message Signature message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Signature.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.data!=null&&message.hasOwnProperty("data"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.data);return writer;};/**
* Encodes the specified Signature message, length delimited. Does not implicitly {@link exonum.crypto.Signature.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.crypto.Signature
* @static
* @param {exonum.crypto.ISignature} message Signature message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Signature.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Signature message from the specified reader or buffer.
* @function decode
* @memberof exonum.crypto.Signature
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.crypto.Signature} Signature
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Signature.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.crypto.Signature();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.data=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Signature message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.crypto.Signature
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.crypto.Signature} Signature
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Signature.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Signature message.
* @function verify
* @memberof exonum.crypto.Signature
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Signature.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.data!=null&&message.hasOwnProperty("data"))if(!(message.data&&typeof message.data.length==="number"||$util.isString(message.data)))return"data: buffer expected";return null;};/**
* Creates a Signature message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.crypto.Signature
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.crypto.Signature} Signature
*/Signature.fromObject=function fromObject(object){if(object instanceof $root.exonum.crypto.Signature)return object;var message=new $root.exonum.crypto.Signature();if(object.data!=null)if(typeof object.data==="string")$util.base64.decode(object.data,message.data=$util.newBuffer($util.base64.length(object.data)),0);else if(object.data.length)message.data=object.data;return message;};/**
* Creates a plain object from a Signature message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.crypto.Signature
* @static
* @param {exonum.crypto.Signature} message Signature
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Signature.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults)if(options.bytes===String)object.data="";else{object.data=[];if(options.bytes!==Array)object.data=$util.newBuffer(object.data);}if(message.data!=null&&message.hasOwnProperty("data"))object.data=options.bytes===String?$util.base64.encode(message.data,0,message.data.length):options.bytes===Array?Array.prototype.slice.call(message.data):message.data;return object;};/**
* Converts this Signature to JSON.
* @function toJSON
* @memberof exonum.crypto.Signature
* @instance
* @returns {Object.<string,*>} JSON object
*/Signature.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Signature;}();return crypto;}();exonum.Block=function(){/**
* Properties of a Block.
* @memberof exonum
* @interface IBlock
* @property {number|Long|null} [chain_id] Block chain_id
* @property {number|null} [proposer_id] Block proposer_id
* @property {number|Long|null} [height] Block height
* @property {number|null} [tx_count] Block tx_count
* @property {exonum.crypto.IHash|null} [prev_hash] Block prev_hash
* @property {exonum.crypto.IHash|null} [tx_hash] Block tx_hash
* @property {exonum.crypto.IHash|null} [state_hash] Block state_hash
*/ /**
* Constructs a new Block.
* @memberof exonum
* @classdesc Represents a Block.
* @implements IBlock
* @constructor
* @param {exonum.IBlock=} [properties] Properties to set
*/function Block(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Block chain_id.
* @member {number|Long} chain_id
* @memberof exonum.Block
* @instance
*/Block.prototype.chain_id=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Block proposer_id.
* @member {number} proposer_id
* @memberof exonum.Block
* @instance
*/Block.prototype.proposer_id=0;/**
* Block height.
* @member {number|Long} height
* @memberof exonum.Block
* @instance
*/Block.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Block tx_count.
* @member {number} tx_count
* @memberof exonum.Block
* @instance
*/Block.prototype.tx_count=0;/**
* Block prev_hash.
* @member {exonum.crypto.IHash|null|undefined} prev_hash
* @memberof exonum.Block
* @instance
*/Block.prototype.prev_hash=null;/**
* Block tx_hash.
* @member {exonum.crypto.IHash|null|undefined} tx_hash
* @memberof exonum.Block
* @instance
*/Block.prototype.tx_hash=null;/**
* Block state_hash.
* @member {exonum.crypto.IHash|null|undefined} state_hash
* @memberof exonum.Block
* @instance
*/Block.prototype.state_hash=null;/**
* Creates a new Block instance using the specified properties.
* @function create
* @memberof exonum.Block
* @static
* @param {exonum.IBlock=} [properties] Properties to set
* @returns {exonum.Block} Block instance
*/Block.create=function create(properties){return new Block(properties);};/**
* Encodes the specified Block message. Does not implicitly {@link exonum.Block.verify|verify} messages.
* @function encode
* @memberof exonum.Block
* @static
* @param {exonum.IBlock} message Block message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Block.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.proposer_id!=null&&message.hasOwnProperty("proposer_id"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.proposer_id);if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.height);if(message.tx_count!=null&&message.hasOwnProperty("tx_count"))writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.tx_count);if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash"))$root.exonum.crypto.Hash.encode(message.prev_hash,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();if(message.tx_hash!=null&&message.hasOwnProperty("tx_hash"))$root.exonum.crypto.Hash.encode(message.tx_hash,writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();if(message.state_hash!=null&&message.hasOwnProperty("state_hash"))$root.exonum.crypto.Hash.encode(message.state_hash,writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim();if(message.chain_id!=null&&message.hasOwnProperty("chain_id"))writer.uint32(/* id 7, wireType 0 =*/56).uint64(message.chain_id);return writer;};/**
* Encodes the specified Block message, length delimited. Does not implicitly {@link exonum.Block.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.Block
* @static
* @param {exonum.IBlock} message Block message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Block.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Block message from the specified reader or buffer.
* @function decode
* @memberof exonum.Block
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.Block} Block
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Block.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.Block();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 7:message.chain_id=reader.uint64();break;case 1:message.proposer_id=reader.uint32();break;case 2:message.height=reader.uint64();break;case 3:message.tx_count=reader.uint32();break;case 4:message.prev_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 5:message.tx_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 6:message.state_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Block message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.Block
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.Block} Block
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Block.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Block message.
* @function verify
* @memberof exonum.Block
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Block.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.chain_id!=null&&message.hasOwnProperty("chain_id"))if(!$util.isInteger(message.chain_id)&&!(message.chain_id&&$util.isInteger(message.chain_id.low)&&$util.isInteger(message.chain_id.high)))return"chain_id: integer|Long expected";if(message.proposer_id!=null&&message.hasOwnProperty("proposer_id"))if(!$util.isInteger(message.proposer_id))return"proposer_id: integer expected";if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";if(message.tx_count!=null&&message.hasOwnProperty("tx_count"))if(!$util.isInteger(message.tx_count))return"tx_count: integer expected";if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash")){var error=$root.exonum.crypto.Hash.verify(message.prev_hash);if(error)return"prev_hash."+error;}if(message.tx_hash!=null&&message.hasOwnProperty("tx_hash")){var error=$root.exonum.crypto.Hash.verify(message.tx_hash);if(error)return"tx_hash."+error;}if(message.state_hash!=null&&message.hasOwnProperty("state_hash")){var error=$root.exonum.crypto.Hash.verify(message.state_hash);if(error)return"state_hash."+error;}return null;};/**
* Creates a Block message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.Block
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.Block} Block
*/Block.fromObject=function fromObject(object){if(object instanceof $root.exonum.Block)return object;var message=new $root.exonum.Block();if(object.chain_id!=null)if($util.Long)(message.chain_id=$util.Long.fromValue(object.chain_id)).unsigned=true;else if(typeof object.chain_id==="string")message.chain_id=parseInt(object.chain_id,10);else if(typeof object.chain_id==="number")message.chain_id=object.chain_id;else if((0,_typeof2["default"])(object.chain_id)==="object")message.chain_id=new $util.LongBits(object.chain_id.low>>>0,object.chain_id.high>>>0).toNumber(true);if(object.proposer_id!=null)message.proposer_id=object.proposer_id>>>0;if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);if(object.tx_count!=null)message.tx_count=object.tx_count>>>0;if(object.prev_hash!=null){if((0,_typeof2["default"])(object.prev_hash)!=="object")throw TypeError(".exonum.Block.prev_hash: object expected");message.prev_hash=$root.exonum.crypto.Hash.fromObject(object.prev_hash);}if(object.tx_hash!=null){if((0,_typeof2["default"])(object.tx_hash)!=="object")throw TypeError(".exonum.Block.tx_hash: object expected");message.tx_hash=$root.exonum.crypto.Hash.fromObject(object.tx_hash);}if(object.state_hash!=null){if((0,_typeof2["default"])(object.state_hash)!=="object")throw TypeError(".exonum.Block.state_hash: object expected");message.state_hash=$root.exonum.crypto.Hash.fromObject(object.state_hash);}return message;};/**
* Creates a plain object from a Block message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.Block
* @static
* @param {exonum.Block} message Block
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Block.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.proposer_id=0;if($util.Long){var _long=new $util.Long(0,0,true);object.height=options.longs===String?_long.toString():options.longs===Number?_long.toNumber():_long;}else object.height=options.longs===String?"0":0;object.tx_count=0;object.prev_hash=null;object.tx_hash=null;object.state_hash=null;if($util.Long){var _long=new $util.Long(0,0,true);object.chain_id=options.longs===String?_long.toString():options.longs===Number?_long.toNumber():_long;}else object.chain_id=options.longs===String?"0":0;}if(message.proposer_id!=null&&message.hasOwnProperty("proposer_id"))object.proposer_id=message.proposer_id;if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;if(message.tx_count!=null&&message.hasOwnProperty("tx_count"))object.tx_count=message.tx_count;if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash"))object.prev_hash=$root.exonum.crypto.Hash.toObject(message.prev_hash,options);if(message.tx_hash!=null&&message.hasOwnProperty("tx_hash"))object.tx_hash=$root.exonum.crypto.Hash.toObject(message.tx_hash,options);if(message.state_hash!=null&&message.hasOwnProperty("state_hash"))object.state_hash=$root.exonum.crypto.Hash.toObject(message.state_hash,options);if(message.chain_id!=null&&message.hasOwnProperty("chain_id"))if(typeof message.chain_id==="number")object.chain_id=options.longs===String?String(message.chain_id):message.chain_id;else object.chain_id=options.longs===String?$util.Long.prototype.toString.call(message.chain_id):options.longs===Number?new $util.LongBits(message.chain_id.low>>>0,message.chain_id.high>>>0).toNumber(true):message.chain_id;return object;};/**
* Converts this Block to JSON.
* @function toJSON
* @memberof exonum.Block
* @instance
* @returns {Object.<string,*>} JSON object
*/Block.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Block;}();exonum.TxLocation=function(){/**
* Properties of a TxLocation.
* @memberof exonum
* @interface ITxLocation
* @property {number|Long|null} [block_height] TxLocation block_height
* @property {number|Long|null} [position_in_block] TxLocation position_in_block
*/ /**
* Constructs a new TxLocation.
* @memberof exonum
* @classdesc Represents a TxLocation.
* @implements ITxLocation
* @constructor
* @param {exonum.ITxLocation=} [properties] Properties to set
*/function TxLocation(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* TxLocation block_height.
* @member {number|Long} block_height
* @memberof exonum.TxLocation
* @instance
*/TxLocation.prototype.block_height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* TxLocation position_in_block.
* @member {number|Long} position_in_block
* @memberof exonum.TxLocation
* @instance
*/TxLocation.prototype.position_in_block=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Creates a new TxLocation instance using the specified properties.
* @function create
* @memberof exonum.TxLocation
* @static
* @param {exonum.ITxLocation=} [properties] Properties to set
* @returns {exonum.TxLocation} TxLocation instance
*/TxLocation.create=function create(properties){return new TxLocation(properties);};/**
* Encodes the specified TxLocation message. Does not implicitly {@link exonum.TxLocation.verify|verify} messages.
* @function encode
* @memberof exonum.TxLocation
* @static
* @param {exonum.ITxLocation} message TxLocation message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TxLocation.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.block_height!=null&&message.hasOwnProperty("block_height"))writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.block_height);if(message.position_in_block!=null&&message.hasOwnProperty("position_in_block"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.position_in_block);return writer;};/**
* Encodes the specified TxLocation message, length delimited. Does not implicitly {@link exonum.TxLocation.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.TxLocation
* @static
* @param {exonum.ITxLocation} message TxLocation message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TxLocation.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a TxLocation message from the specified reader or buffer.
* @function decode
* @memberof exonum.TxLocation
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.TxLocation} TxLocation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TxLocation.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.TxLocation();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.block_height=reader.uint64();break;case 2:message.position_in_block=reader.uint64();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a TxLocation message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.TxLocation
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.TxLocation} TxLocation
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TxLocation.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a TxLocation message.
* @function verify
* @memberof exonum.TxLocation
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/TxLocation.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.block_height!=null&&message.hasOwnProperty("block_height"))if(!$util.isInteger(message.block_height)&&!(message.block_height&&$util.isInteger(message.block_height.low)&&$util.isInteger(message.block_height.high)))return"block_height: integer|Long expected";if(message.position_in_block!=null&&message.hasOwnProperty("position_in_block"))if(!$util.isInteger(message.position_in_block)&&!(message.position_in_block&&$util.isInteger(message.position_in_block.low)&&$util.isInteger(message.position_in_block.high)))return"position_in_block: integer|Long expected";return null;};/**
* Creates a TxLocation message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.TxLocation
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.TxLocation} TxLocation
*/TxLocation.fromObject=function fromObject(object){if(object instanceof $root.exonum.TxLocation)return object;var message=new $root.exonum.TxLocation();if(object.block_height!=null)if($util.Long)(message.block_height=$util.Long.fromValue(object.block_height)).unsigned=true;else if(typeof object.block_height==="string")message.block_height=parseInt(object.block_height,10);else if(typeof object.block_height==="number")message.block_height=object.block_height;else if((0,_typeof2["default"])(object.block_height)==="object")message.block_height=new $util.LongBits(object.block_height.low>>>0,object.block_height.high>>>0).toNumber(true);if(object.position_in_block!=null)if($util.Long)(message.position_in_block=$util.Long.fromValue(object.position_in_block)).unsigned=true;else if(typeof object.position_in_block==="string")message.position_in_block=parseInt(object.position_in_block,10);else if(typeof object.position_in_block==="number")message.position_in_block=object.position_in_block;else if((0,_typeof2["default"])(object.position_in_block)==="object")message.position_in_block=new $util.LongBits(object.position_in_block.low>>>0,object.position_in_block.high>>>0).toNumber(true);return message;};/**
* Creates a plain object from a TxLocation message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.TxLocation
* @static
* @param {exonum.TxLocation} message TxLocation
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/TxLocation.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if($util.Long){var _long2=new $util.Long(0,0,true);object.block_height=options.longs===String?_long2.toString():options.longs===Number?_long2.toNumber():_long2;}else object.block_height=options.longs===String?"0":0;if($util.Long){var _long2=new $util.Long(0,0,true);object.position_in_block=options.longs===String?_long2.toString():options.longs===Number?_long2.toNumber():_long2;}else object.position_in_block=options.longs===String?"0":0;}if(message.block_height!=null&&message.hasOwnProperty("block_height"))if(typeof message.block_height==="number")object.block_height=options.longs===String?String(message.block_height):message.block_height;else object.block_height=options.longs===String?$util.Long.prototype.toString.call(message.block_height):options.longs===Number?new $util.LongBits(message.block_height.low>>>0,message.block_height.high>>>0).toNumber(true):message.block_height;if(message.position_in_block!=null&&message.hasOwnProperty("position_in_block"))if(typeof message.position_in_block==="number")object.position_in_block=options.longs===String?String(message.position_in_block):message.position_in_block;else object.position_in_block=options.longs===String?$util.Long.prototype.toString.call(message.position_in_block):options.longs===Number?new $util.LongBits(message.position_in_block.low>>>0,message.position_in_block.high>>>0).toNumber(true):message.position_in_block;return object;};/**
* Converts this TxLocation to JSON.
* @function toJSON
* @memberof exonum.TxLocation
* @instance
* @returns {Object.<string,*>} JSON object
*/TxLocation.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return TxLocation;}();exonum.ValidatorKeys=function(){/**
* Properties of a ValidatorKeys.
* @memberof exonum
* @interface IValidatorKeys
* @property {exonum.crypto.IPublicKey|null} [consensus_key] ValidatorKeys consensus_key
* @property {exonum.crypto.IPublicKey|null} [service_key] ValidatorKeys service_key
*/ /**
* Constructs a new ValidatorKeys.
* @memberof exonum
* @classdesc Represents a ValidatorKeys.
* @implements IValidatorKeys
* @constructor
* @param {exonum.IValidatorKeys=} [properties] Properties to set
*/function ValidatorKeys(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ValidatorKeys consensus_key.
* @member {exonum.crypto.IPublicKey|null|undefined} consensus_key
* @memberof exonum.ValidatorKeys
* @instance
*/ValidatorKeys.prototype.consensus_key=null;/**
* ValidatorKeys service_key.
* @member {exonum.crypto.IPublicKey|null|undefined} service_key
* @memberof exonum.ValidatorKeys
* @instance
*/ValidatorKeys.prototype.service_key=null;/**
* Creates a new ValidatorKeys instance using the specified properties.
* @function create
* @memberof exonum.ValidatorKeys
* @static
* @param {exonum.IValidatorKeys=} [properties] Properties to set
* @returns {exonum.ValidatorKeys} ValidatorKeys instance
*/ValidatorKeys.create=function create(properties){return new ValidatorKeys(properties);};/**
* Encodes the specified ValidatorKeys message. Does not implicitly {@link exonum.ValidatorKeys.verify|verify} messages.
* @function encode
* @memberof exonum.ValidatorKeys
* @static
* @param {exonum.IValidatorKeys} message ValidatorKeys message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ValidatorKeys.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.consensus_key!=null&&message.hasOwnProperty("consensus_key"))$root.exonum.crypto.PublicKey.encode(message.consensus_key,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.service_key!=null&&message.hasOwnProperty("service_key"))$root.exonum.crypto.PublicKey.encode(message.service_key,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();return writer;};/**
* Encodes the specified ValidatorKeys message, length delimited. Does not implicitly {@link exonum.ValidatorKeys.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.ValidatorKeys
* @static
* @param {exonum.IValidatorKeys} message ValidatorKeys message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ValidatorKeys.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a ValidatorKeys message from the specified reader or buffer.
* @function decode
* @memberof exonum.ValidatorKeys
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.ValidatorKeys} ValidatorKeys
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ValidatorKeys.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.ValidatorKeys();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.consensus_key=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:message.service_key=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a ValidatorKeys message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.ValidatorKeys
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.ValidatorKeys} ValidatorKeys
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ValidatorKeys.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a ValidatorKeys message.
* @function verify
* @memberof exonum.ValidatorKeys
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ValidatorKeys.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.consensus_key!=null&&message.hasOwnProperty("consensus_key")){var error=$root.exonum.crypto.PublicKey.verify(message.consensus_key);if(error)return"consensus_key."+error;}if(message.service_key!=null&&message.hasOwnProperty("service_key")){var error=$root.exonum.crypto.PublicKey.verify(message.service_key);if(error)return"service_key."+error;}return null;};/**
* Creates a ValidatorKeys message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.ValidatorKeys
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.ValidatorKeys} ValidatorKeys
*/ValidatorKeys.fromObject=function fromObject(object){if(object instanceof $root.exonum.ValidatorKeys)return object;var message=new $root.exonum.ValidatorKeys();if(object.consensus_key!=null){if((0,_typeof2["default"])(object.consensus_key)!=="object")throw TypeError(".exonum.ValidatorKeys.consensus_key: object expected");message.consensus_key=$root.exonum.crypto.PublicKey.fromObject(object.consensus_key);}if(object.service_key!=null){if((0,_typeof2["default"])(object.service_key)!=="object")throw TypeError(".exonum.ValidatorKeys.service_key: object expected");message.service_key=$root.exonum.crypto.PublicKey.fromObject(object.service_key);}return message;};/**
* Creates a plain object from a ValidatorKeys message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.ValidatorKeys
* @static
* @param {exonum.ValidatorKeys} message ValidatorKeys
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ValidatorKeys.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.consensus_key=null;object.service_key=null;}if(message.consensus_key!=null&&message.hasOwnProperty("consensus_key"))object.consensus_key=$root.exonum.crypto.PublicKey.toObject(message.consensus_key,options);if(message.service_key!=null&&message.hasOwnProperty("service_key"))object.service_key=$root.exonum.crypto.PublicKey.toObject(message.service_key,options);return object;};/**
* Converts this ValidatorKeys to JSON.
* @function toJSON
* @memberof exonum.ValidatorKeys
* @instance
* @returns {Object.<string,*>} JSON object
*/ValidatorKeys.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ValidatorKeys;}();exonum.Config=function(){/**
* Properties of a Config.
* @memberof exonum
* @interface IConfig
* @property {Array.<exonum.IValidatorKeys>|null} [validator_keys] Config validator_keys
* @property {number|Long|null} [first_round_timeout] Config first_round_timeout
* @property {number|Long|null} [status_timeout] Config status_timeout
* @property {number|Long|null} [peers_timeout] Config peers_timeout
* @property {number|null} [txs_block_limit] Config txs_block_limit
* @property {number|null} [max_message_len] Config max_message_len
* @property {number|Long|null} [min_propose_timeout] Config min_propose_timeout
* @property {number|Long|null} [max_propose_timeout] Config max_propose_timeout
* @property {number|null} [propose_timeout_threshold] Config propose_timeout_threshold
*/ /**
* Constructs a new Config.
* @memberof exonum
* @classdesc Represents a Config.
* @implements IConfig
* @constructor
* @param {exonum.IConfig=} [properties] Properties to set
*/function Config(properties){this.validator_keys=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Config validator_keys.
* @member {Array.<exonum.IValidatorKeys>} validator_keys
* @memberof exonum.Config
* @instance
*/Config.prototype.validator_keys=$util.emptyArray;/**
* Config first_round_timeout.
* @member {number|Long} first_round_timeout
* @memberof exonum.Config
* @instance
*/Config.prototype.first_round_timeout=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Config status_timeout.
* @member {number|Long} status_timeout
* @memberof exonum.Config
* @instance
*/Config.prototype.status_timeout=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Config peers_timeout.
* @member {number|Long} peers_timeout
* @memberof exonum.Config
* @instance
*/Config.prototype.peers_timeout=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Config txs_block_limit.
* @member {number} txs_block_limit
* @memberof exonum.Config
* @instance
*/Config.prototype.txs_block_limit=0;/**
* Config max_message_len.
* @member {number} max_message_len
* @memberof exonum.Config
* @instance
*/Config.prototype.max_message_len=0;/**
* Config min_propose_timeout.
* @member {number|Long} min_propose_timeout
* @memberof exonum.Config
* @instance
*/Config.prototype.min_propose_timeout=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Config max_propose_timeout.
* @member {number|Long} max_propose_timeout
* @memberof exonum.Config
* @instance
*/Config.prototype.max_propose_timeout=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Config propose_timeout_threshold.
* @member {number} propose_timeout_threshold
* @memberof exonum.Config
* @instance
*/Config.prototype.propose_timeout_threshold=0;/**
* Creates a new Config instance using the specified properties.
* @function create
* @memberof exonum.Config
* @static
* @param {exonum.IConfig=} [properties] Properties to set
* @returns {exonum.Config} Config instance
*/Config.create=function create(properties){return new Config(properties);};/**
* Encodes the specified Config message. Does not implicitly {@link exonum.Config.verify|verify} messages.
* @function encode
* @memberof exonum.Config
* @static
* @param {exonum.IConfig} message Config message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Config.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.validator_keys!=null&&message.validator_keys.length)for(var i=0;i<message.validator_keys.length;++i){$root.exonum.ValidatorKeys.encode(message.validator_keys[i],writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();}if(message.first_round_timeout!=null&&message.hasOwnProperty("first_round_timeout"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.first_round_timeout);if(message.status_timeout!=null&&message.hasOwnProperty("status_timeout"))writer.uint32(/* id 3, wireType 0 =*/24).uint64(message.status_timeout);if(message.peers_timeout!=null&&message.hasOwnProperty("peers_timeout"))writer.uint32(/* id 4, wireType 0 =*/32).uint64(message.peers_timeout);if(message.txs_block_limit!=null&&message.hasOwnProperty("txs_block_limit"))writer.uint32(/* id 5, wireType 0 =*/40).uint32(message.txs_block_limit);if(message.max_message_len!=null&&message.hasOwnProperty("max_message_len"))writer.uint32(/* id 6, wireType 0 =*/48).uint32(message.max_message_len);if(message.min_propose_timeout!=null&&message.hasOwnProperty("min_propose_timeout"))writer.uint32(/* id 7, wireType 0 =*/56).uint64(message.min_propose_timeout);if(message.max_propose_timeout!=null&&message.hasOwnProperty("max_propose_timeout"))writer.uint32(/* id 8, wireType 0 =*/64).uint64(message.max_propose_timeout);if(message.propose_timeout_threshold!=null&&message.hasOwnProperty("propose_timeout_threshold"))writer.uint32(/* id 9, wireType 0 =*/72).uint32(message.propose_timeout_threshold);return writer;};/**
* Encodes the specified Config message, length delimited. Does not implicitly {@link exonum.Config.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.Config
* @static
* @param {exonum.IConfig} message Config message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Config.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Config message from the specified reader or buffer.
* @function decode
* @memberof exonum.Config
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.Config} Config
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Config.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.Config();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:if(!(message.validator_keys&&message.validator_keys.length))message.validator_keys=[];message.validator_keys.push($root.exonum.ValidatorKeys.decode(reader,reader.uint32()));break;case 2:message.first_round_timeout=reader.uint64();break;case 3:message.status_timeout=reader.uint64();break;case 4:message.peers_timeout=reader.uint64();break;case 5:message.txs_block_limit=reader.uint32();break;case 6:message.max_message_len=reader.uint32();break;case 7:message.min_propose_timeout=reader.uint64();break;case 8:message.max_propose_timeout=reader.uint64();break;case 9:message.propose_timeout_threshold=reader.uint32();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Config message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.Config
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.Config} Config
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Config.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Config message.
* @function verify
* @memberof exonum.Config
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Config.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.validator_keys!=null&&message.hasOwnProperty("validator_keys")){if(!Array.isArray(message.validator_keys))return"validator_keys: array expected";for(var i=0;i<message.validator_keys.length;++i){var error=$root.exonum.ValidatorKeys.verify(message.validator_keys[i]);if(error)return"validator_keys."+error;}}if(message.first_round_timeout!=null&&message.hasOwnProperty("first_round_timeout"))if(!$util.isInteger(message.first_round_timeout)&&!(message.first_round_timeout&&$util.isInteger(message.first_round_timeout.low)&&$util.isInteger(message.first_round_timeout.high)))return"first_round_timeout: integer|Long expected";if(message.status_timeout!=null&&message.hasOwnProperty("status_timeout"))if(!$util.isInteger(message.status_timeout)&&!(message.status_timeout&&$util.isInteger(message.status_timeout.low)&&$util.isInteger(message.status_timeout.high)))return"status_timeout: integer|Long expected";if(message.peers_timeout!=null&&message.hasOwnProperty("peers_timeout"))if(!$util.isInteger(message.peers_timeout)&&!(message.peers_timeout&&$util.isInteger(message.peers_timeout.low)&&$util.isInteger(message.peers_timeout.high)))return"peers_timeout: integer|Long expected";if(message.txs_block_limit!=null&&message.hasOwnProperty("txs_block_limit"))if(!$util.isInteger(message.txs_block_limit))return"txs_block_limit: integer expected";if(message.max_message_len!=null&&message.hasOwnProperty("max_message_len"))if(!$util.isInteger(message.max_message_len))return"max_message_len: integer expected";if(message.min_propose_timeout!=null&&message.hasOwnProperty("min_propose_timeout"))if(!$util.isInteger(message.min_propose_timeout)&&!(message.min_propose_timeout&&$util.isInteger(message.min_propose_timeout.low)&&$util.isInteger(message.min_propose_timeout.high)))return"min_propose_timeout: integer|Long expected";if(message.max_propose_timeout!=null&&message.hasOwnProperty("max_propose_timeout"))if(!$util.isInteger(message.max_propose_timeout)&&!(message.max_propose_timeout&&$util.isInteger(message.max_propose_timeout.low)&&$util.isInteger(message.max_propose_timeout.high)))return"max_propose_timeout: integer|Long expected";if(message.propose_timeout_threshold!=null&&message.hasOwnProperty("propose_timeout_threshold"))if(!$util.isInteger(message.propose_timeout_threshold))return"propose_timeout_threshold: integer expected";return null;};/**
* Creates a Config message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.Config
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.Config} Config
*/Config.fromObject=function fromObject(object){if(object instanceof $root.exonum.Config)return object;var message=new $root.exonum.Config();if(object.validator_keys){if(!Array.isArray(object.validator_keys))throw TypeError(".exonum.Config.validator_keys: array expected");message.validator_keys=[];for(var i=0;i<object.validator_keys.length;++i){if((0,_typeof2["default"])(object.validator_keys[i])!=="object")throw TypeError(".exonum.Config.validator_keys: object expected");message.validator_keys[i]=$root.exonum.ValidatorKeys.fromObject(object.validator_keys[i]);}}if(object.first_round_timeout!=null)if($util.Long)(message.first_round_timeout=$util.Long.fromValue(object.first_round_timeout)).unsigned=true;else if(typeof object.first_round_timeout==="string")message.first_round_timeout=parseInt(object.first_round_timeout,10);else if(typeof object.first_round_timeout==="number")message.first_round_timeout=object.first_round_timeout;else if((0,_typeof2["default"])(object.first_round_timeout)==="object")message.first_round_timeout=new $util.LongBits(object.first_round_timeout.low>>>0,object.first_round_timeout.high>>>0).toNumber(true);if(object.status_timeout!=null)if($util.Long)(message.status_timeout=$util.Long.fromValue(object.status_timeout)).unsigned=true;else if(typeof object.status_timeout==="string")message.status_timeout=parseInt(object.status_timeout,10);else if(typeof object.status_timeout==="number")message.status_timeout=object.status_timeout;else if((0,_typeof2["default"])(object.status_timeout)==="object")message.status_timeout=new $util.LongBits(object.status_timeout.low>>>0,object.status_timeout.high>>>0).toNumber(true);if(object.peers_timeout!=null)if($util.Long)(message.peers_timeout=$util.Long.fromValue(object.peers_timeout)).unsigned=true;else if(typeof object.peers_timeout==="string")message.peers_timeout=parseInt(object.peers_timeout,10);else if(typeof object.peers_timeout==="number")message.peers_timeout=object.peers_timeout;else if((0,_typeof2["default"])(object.peers_timeout)==="object")message.peers_timeout=new $util.LongBits(object.peers_timeout.low>>>0,object.peers_timeout.high>>>0).toNumber(true);if(object.txs_block_limit!=null)message.txs_block_limit=object.txs_block_limit>>>0;if(object.max_message_len!=null)message.max_message_len=object.max_message_len>>>0;if(object.min_propose_timeout!=null)if($util.Long)(message.min_propose_timeout=$util.Long.fromValue(object.min_propose_timeout)).unsigned=true;else if(typeof object.min_propose_timeout==="string")message.min_propose_timeout=parseInt(object.min_propose_timeout,10);else if(typeof object.min_propose_timeout==="number")message.min_propose_timeout=object.min_propose_timeout;else if((0,_typeof2["default"])(object.min_propose_timeout)==="object")message.min_propose_timeout=new $util.LongBits(object.min_propose_timeout.low>>>0,object.min_propose_timeout.high>>>0).toNumber(true);if(object.max_propose_timeout!=null)if($util.Long)(message.max_propose_timeout=$util.Long.fromValue(object.max_propose_timeout)).unsigned=true;else if(typeof object.max_propose_timeout==="string")message.max_propose_timeout=parseInt(object.max_propose_timeout,10);else if(typeof object.max_propose_timeout==="number")message.max_propose_timeout=object.max_propose_timeout;else if((0,_typeof2["default"])(object.max_propose_timeout)==="object")message.max_propose_timeout=new $util.LongBits(object.max_propose_timeout.low>>>0,object.max_propose_timeout.high>>>0).toNumber(true);if(object.propose_timeout_threshold!=null)message.propose_timeout_threshold=object.propose_timeout_threshold>>>0;return message;};/**
* Creates a plain object from a Config message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.Config
* @static
* @param {exonum.Config} message Config
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Config.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.validator_keys=[];if(options.defaults){if($util.Long){var _long3=new $util.Long(0,0,true);object.first_round_timeout=options.longs===String?_long3.toString():options.longs===Number?_long3.toNumber():_long3;}else object.first_round_timeout=options.longs===String?"0":0;if($util.Long){var _long3=new $util.Long(0,0,true);object.status_timeout=options.longs===String?_long3.toString():options.longs===Number?_long3.toNumber():_long3;}else object.status_timeout=options.longs===String?"0":0;if($util.Long){var _long3=new $util.Long(0,0,true);object.peers_timeout=options.longs===String?_long3.toString():options.longs===Number?_long3.toNumber():_long3;}else object.peers_timeout=options.longs===String?"0":0;object.txs_block_limit=0;object.max_message_len=0;if($util.Long){var _long3=new $util.Long(0,0,true);object.min_propose_timeout=options.longs===String?_long3.toString():options.longs===Number?_long3.toNumber():_long3;}else object.min_propose_timeout=options.longs===String?"0":0;if($util.Long){var _long3=new $util.Long(0,0,true);object.max_propose_timeout=options.longs===String?_long3.toString():options.longs===Number?_long3.toNumber():_long3;}else object.max_propose_timeout=options.longs===String?"0":0;object.propose_timeout_threshold=0;}if(message.validator_keys&&message.validator_keys.length){object.validator_keys=[];for(var j=0;j<message.validator_keys.length;++j){object.validator_keys[j]=$root.exonum.ValidatorKeys.toObject(message.validator_keys[j],options);}}if(message.first_round_timeout!=null&&message.hasOwnProperty("first_round_timeout"))if(typeof message.first_round_timeout==="number")object.first_round_timeout=options.longs===String?String(message.first_round_timeout):message.first_round_timeout;else object.first_round_timeout=options.longs===String?$util.Long.prototype.toString.call(message.first_round_timeout):options.longs===Number?new $util.LongBits(message.first_round_timeout.low>>>0,message.first_round_timeout.high>>>0).toNumber(true):message.first_round_timeout;if(message.status_timeout!=null&&message.hasOwnProperty("status_timeout"))if(typeof message.status_timeout==="number")object.status_timeout=options.longs===String?String(message.status_timeout):message.status_timeout;else object.status_timeout=options.longs===String?$util.Long.prototype.toString.call(message.status_timeout):options.longs===Number?new $util.LongBits(message.status_timeout.low>>>0,message.status_timeout.high>>>0).toNumber(true):message.status_timeout;if(message.peers_timeout!=null&&message.hasOwnProperty("peers_timeout"))if(typeof message.peers_timeout==="number")object.peers_timeout=options.longs===String?String(message.peers_timeout):message.peers_timeout;else object.peers_timeout=options.longs===String?$util.Long.prototype.toString.call(message.peers_timeout):options.longs===Number?new $util.LongBits(message.peers_timeout.low>>>0,message.peers_timeout.high>>>0).toNumber(true):message.peers_timeout;if(message.txs_block_limit!=null&&message.hasOwnProperty("txs_block_limit"))object.txs_block_limit=message.txs_block_limit;if(message.max_message_len!=null&&message.hasOwnProperty("max_message_len"))object.max_message_len=message.max_message_len;if(message.min_propose_timeout!=null&&message.hasOwnProperty("min_propose_timeout"))if(typeof message.min_propose_timeout==="number")object.min_propose_timeout=options.longs===String?String(message.min_propose_timeout):message.min_propose_timeout;else object.min_propose_timeout=options.longs===String?$util.Long.prototype.toString.call(message.min_propose_timeout):options.longs===Number?new $util.LongBits(message.min_propose_timeout.low>>>0,message.min_propose_timeout.high>>>0).toNumber(true):message.min_propose_timeout;if(message.max_propose_timeout!=null&&message.hasOwnProperty("max_propose_timeout"))if(typeof message.max_propose_timeout==="number")object.max_propose_timeout=options.longs===String?String(message.max_propose_timeout):message.max_propose_timeout;else object.max_propose_timeout=options.longs===String?$util.Long.prototype.toString.call(message.max_propose_timeout):options.longs===Number?new $util.LongBits(message.max_propose_timeout.low>>>0,message.max_propose_timeout.high>>>0).toNumber(true):message.max_propose_timeout;if(message.propose_timeout_threshold!=null&&message.hasOwnProperty("propose_timeout_threshold"))object.propose_timeout_threshold=message.propose_timeout_threshold;return object;};/**
* Converts this Config to JSON.
* @function toJSON
* @memberof exonum.Config
* @instance
* @returns {Object.<string,*>} JSON object
*/Config.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Config;}();exonum.AppliedConfig=function(){/**
* Properties of an AppliedConfig.
* @memberof exonum
* @interface IAppliedConfig
* @property {number|Long|null} [actual_from] AppliedConfig actual_from
* @property {exonum.crypto.IHash|null} [prev_hash] AppliedConfig prev_hash
* @property {exonum.IConfig|null} [consensus_config] AppliedConfig consensus_config
*/ /**
* Constructs a new AppliedConfig.
* @memberof exonum
* @classdesc Represents an AppliedConfig.
* @implements IAppliedConfig
* @constructor
* @param {exonum.IAppliedConfig=} [properties] Properties to set
*/function AppliedConfig(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* AppliedConfig actual_from.
* @member {number|Long} actual_from
* @memberof exonum.AppliedConfig
* @instance
*/AppliedConfig.prototype.actual_from=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* AppliedConfig prev_hash.
* @member {exonum.crypto.IHash|null|undefined} prev_hash
* @memberof exonum.AppliedConfig
* @instance
*/AppliedConfig.prototype.prev_hash=null;/**
* AppliedConfig consensus_config.
* @member {exonum.IConfig|null|undefined} consensus_config
* @memberof exonum.AppliedConfig
* @instance
*/AppliedConfig.prototype.consensus_config=null;/**
* Creates a new AppliedConfig instance using the specified properties.
* @function create
* @memberof exonum.AppliedConfig
* @static
* @param {exonum.IAppliedConfig=} [properties] Properties to set
* @returns {exonum.AppliedConfig} AppliedConfig instance
*/AppliedConfig.create=function create(properties){return new AppliedConfig(properties);};/**
* Encodes the specified AppliedConfig message. Does not implicitly {@link exonum.AppliedConfig.verify|verify} messages.
* @function encode
* @memberof exonum.AppliedConfig
* @static
* @param {exonum.IAppliedConfig} message AppliedConfig message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/AppliedConfig.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.actual_from!=null&&message.hasOwnProperty("actual_from"))writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.actual_from);if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash"))$root.exonum.crypto.Hash.encode(message.prev_hash,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();if(message.consensus_config!=null&&message.hasOwnProperty("consensus_config"))$root.exonum.Config.encode(message.consensus_config,writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();return writer;};/**
* Encodes the specified AppliedConfig message, length delimited. Does not implicitly {@link exonum.AppliedConfig.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.AppliedConfig
* @static
* @param {exonum.IAppliedConfig} message AppliedConfig message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/AppliedConfig.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an AppliedConfig message from the specified reader or buffer.
* @function decode
* @memberof exonum.AppliedConfig
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.AppliedConfig} AppliedConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/AppliedConfig.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.AppliedConfig();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.actual_from=reader.uint64();break;case 2:message.prev_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 3:message.consensus_config=$root.exonum.Config.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an AppliedConfig message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.AppliedConfig
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.AppliedConfig} AppliedConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/AppliedConfig.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an AppliedConfig message.
* @function verify
* @memberof exonum.AppliedConfig
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/AppliedConfig.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.actual_from!=null&&message.hasOwnProperty("actual_from"))if(!$util.isInteger(message.actual_from)&&!(message.actual_from&&$util.isInteger(message.actual_from.low)&&$util.isInteger(message.actual_from.high)))return"actual_from: integer|Long expected";if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash")){var error=$root.exonum.crypto.Hash.verify(message.prev_hash);if(error)return"prev_hash."+error;}if(message.consensus_config!=null&&message.hasOwnProperty("consensus_config")){var error=$root.exonum.Config.verify(message.consensus_config);if(error)return"consensus_config."+error;}return null;};/**
* Creates an AppliedConfig message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.AppliedConfig
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.AppliedConfig} AppliedConfig
*/AppliedConfig.fromObject=function fromObject(object){if(object instanceof $root.exonum.AppliedConfig)return object;var message=new $root.exonum.AppliedConfig();if(object.actual_from!=null)if($util.Long)(message.actual_from=$util.Long.fromValue(object.actual_from)).unsigned=true;else if(typeof object.actual_from==="string")message.actual_from=parseInt(object.actual_from,10);else if(typeof object.actual_from==="number")message.actual_from=object.actual_from;else if((0,_typeof2["default"])(object.actual_from)==="object")message.actual_from=new $util.LongBits(object.actual_from.low>>>0,object.actual_from.high>>>0).toNumber(true);if(object.prev_hash!=null){if((0,_typeof2["default"])(object.prev_hash)!=="object")throw TypeError(".exonum.AppliedConfig.prev_hash: object expected");message.prev_hash=$root.exonum.crypto.Hash.fromObject(object.prev_hash);}if(object.consensus_config!=null){if((0,_typeof2["default"])(object.consensus_config)!=="object")throw TypeError(".exonum.AppliedConfig.consensus_config: object expected");message.consensus_config=$root.exonum.Config.fromObject(object.consensus_config);}return message;};/**
* Creates a plain object from an AppliedConfig message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.AppliedConfig
* @static
* @param {exonum.AppliedConfig} message AppliedConfig
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/AppliedConfig.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if($util.Long){var _long4=new $util.Long(0,0,true);object.actual_from=options.longs===String?_long4.toString():options.longs===Number?_long4.toNumber():_long4;}else object.actual_from=options.longs===String?"0":0;object.prev_hash=null;object.consensus_config=null;}if(message.actual_from!=null&&message.hasOwnProperty("actual_from"))if(typeof message.actual_from==="number")object.actual_from=options.longs===String?String(message.actual_from):message.actual_from;else object.actual_from=options.longs===String?$util.Long.prototype.toString.call(message.actual_from):options.longs===Number?new $util.LongBits(message.actual_from.low>>>0,message.actual_from.high>>>0).toNumber(true):message.actual_from;if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash"))object.prev_hash=$root.exonum.crypto.Hash.toObject(message.prev_hash,options);if(message.consensus_config!=null&&message.hasOwnProperty("consensus_config"))object.consensus_config=$root.exonum.Config.toObject(message.consensus_config,options);return object;};/**
* Converts this AppliedConfig to JSON.
* @function toJSON
* @memberof exonum.AppliedConfig
* @instance
* @returns {Object.<string,*>} JSON object
*/AppliedConfig.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return AppliedConfig;}();exonum.consensus=function(){/**
* Namespace consensus.
* @memberof exonum
* @namespace
*/var consensus={};consensus.CoreMessage=function(){/**
* Properties of a CoreMessage.
* @memberof exonum.consensus
* @interface ICoreMessage
* @property {exonum.runtime.IAnyTx|null} [any_tx] CoreMessage any_tx
* @property {exonum.consensus.IPrecommit|null} [precommit] CoreMessage precommit
*/ /**
* Constructs a new CoreMessage.
* @memberof exonum.consensus
* @classdesc Represents a CoreMessage.
* @implements ICoreMessage
* @constructor
* @param {exonum.consensus.ICoreMessage=} [properties] Properties to set
*/function CoreMessage(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* CoreMessage any_tx.
* @member {exonum.runtime.IAnyTx|null|undefined} any_tx
* @memberof exonum.consensus.CoreMessage
* @instance
*/CoreMessage.prototype.any_tx=null;/**
* CoreMessage precommit.
* @member {exonum.consensus.IPrecommit|null|undefined} precommit
* @memberof exonum.consensus.CoreMessage
* @instance
*/CoreMessage.prototype.precommit=null;// OneOf field names bound to virtual getters and setters
var $oneOfFields;/**
* CoreMessage kind.
* @member {"any_tx"|"precommit"|undefined} kind
* @memberof exonum.consensus.CoreMessage
* @instance
*/Object.defineProperty(CoreMessage.prototype,"kind",{get:$util.oneOfGetter($oneOfFields=["any_tx","precommit"]),set:$util.oneOfSetter($oneOfFields)});/**
* Creates a new CoreMessage instance using the specified properties.
* @function create
* @memberof exonum.consensus.CoreMessage
* @static
* @param {exonum.consensus.ICoreMessage=} [properties] Properties to set
* @returns {exonum.consensus.CoreMessage} CoreMessage instance
*/CoreMessage.create=function create(properties){return new CoreMessage(properties);};/**
* Encodes the specified CoreMessage message. Does not implicitly {@link exonum.consensus.CoreMessage.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.CoreMessage
* @static
* @param {exonum.consensus.ICoreMessage} message CoreMessage message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/CoreMessage.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.any_tx!=null&&message.hasOwnProperty("any_tx"))$root.exonum.runtime.AnyTx.encode(message.any_tx,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.precommit!=null&&message.hasOwnProperty("precommit"))$root.exonum.consensus.Precommit.encode(message.precommit,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();return writer;};/**
* Encodes the specified CoreMessage message, length delimited. Does not implicitly {@link exonum.consensus.CoreMessage.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.CoreMessage
* @static
* @param {exonum.consensus.ICoreMessage} message CoreMessage message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/CoreMessage.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a CoreMessage message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.CoreMessage
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.CoreMessage} CoreMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/CoreMessage.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.CoreMessage();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.any_tx=$root.exonum.runtime.AnyTx.decode(reader,reader.uint32());break;case 2:message.precommit=$root.exonum.consensus.Precommit.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a CoreMessage message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.CoreMessage
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.CoreMessage} CoreMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/CoreMessage.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a CoreMessage message.
* @function verify
* @memberof exonum.consensus.CoreMessage
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/CoreMessage.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";var properties={};if(message.any_tx!=null&&message.hasOwnProperty("any_tx")){properties.kind=1;{var error=$root.exonum.runtime.AnyTx.verify(message.any_tx);if(error)return"any_tx."+error;}}if(message.precommit!=null&&message.hasOwnProperty("precommit")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.Precommit.verify(message.precommit);if(error)return"precommit."+error;}}return null;};/**
* Creates a CoreMessage message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.CoreMessage
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.CoreMessage} CoreMessage
*/CoreMessage.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.CoreMessage)return object;var message=new $root.exonum.consensus.CoreMessage();if(object.any_tx!=null){if((0,_typeof2["default"])(object.any_tx)!=="object")throw TypeError(".exonum.consensus.CoreMessage.any_tx: object expected");message.any_tx=$root.exonum.runtime.AnyTx.fromObject(object.any_tx);}if(object.precommit!=null){if((0,_typeof2["default"])(object.precommit)!=="object")throw TypeError(".exonum.consensus.CoreMessage.precommit: object expected");message.precommit=$root.exonum.consensus.Precommit.fromObject(object.precommit);}return message;};/**
* Creates a plain object from a CoreMessage message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.CoreMessage
* @static
* @param {exonum.consensus.CoreMessage} message CoreMessage
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/CoreMessage.toObject=function toObject(message,options){if(!options)options={};var object={};if(message.any_tx!=null&&message.hasOwnProperty("any_tx")){object.any_tx=$root.exonum.runtime.AnyTx.toObject(message.any_tx,options);if(options.oneofs)object.kind="any_tx";}if(message.precommit!=null&&message.hasOwnProperty("precommit")){object.precommit=$root.exonum.consensus.Precommit.toObject(message.precommit,options);if(options.oneofs)object.kind="precommit";}return object;};/**
* Converts this CoreMessage to JSON.
* @function toJSON
* @memberof exonum.consensus.CoreMessage
* @instance
* @returns {Object.<string,*>} JSON object
*/CoreMessage.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return CoreMessage;}();consensus.SignedMessage=function(){/**
* Properties of a SignedMessage.
* @memberof exonum.consensus
* @interface ISignedMessage
* @property {Uint8Array|null} [chain_id_bytes] SignedMessage chain_id_bytes
* @property {Uint8Array|null} [payload] SignedMessage payload
* @property {exonum.crypto.IPublicKey|null} [author] SignedMessage author
* @property {exonum.crypto.ISignature|null} [signature] SignedMessage signature
*/ /**
* Constructs a new SignedMessage.
* @memberof exonum.consensus
* @classdesc Represents a SignedMessage.
* @implements ISignedMessage
* @constructor
* @param {exonum.consensus.ISignedMessage=} [properties] Properties to set
*/function SignedMessage(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* SignedMessage chain_id_bytes.
* @member {Uint8Array} chain_id_bytes
* @memberof exonum.consensus.SignedMessage
* @instance
*/SignedMessage.prototype.chain_id_bytes=$util.newBuffer([]);/**
* SignedMessage payload.
* @member {Uint8Array} payload
* @memberof exonum.consensus.SignedMessage
* @instance
*/SignedMessage.prototype.payload=$util.newBuffer([]);/**
* SignedMessage author.
* @member {exonum.crypto.IPublicKey|null|undefined} author
* @memberof exonum.consensus.SignedMessage
* @instance
*/SignedMessage.prototype.author=null;/**
* SignedMessage signature.
* @member {exonum.crypto.ISignature|null|undefined} signature
* @memberof exonum.consensus.SignedMessage
* @instance
*/SignedMessage.prototype.signature=null;/**
* Creates a new SignedMessage instance using the specified properties.
* @function create
* @memberof exonum.consensus.SignedMessage
* @static
* @param {exonum.consensus.ISignedMessage=} [properties] Properties to set
* @returns {exonum.consensus.SignedMessage} SignedMessage instance
*/SignedMessage.create=function create(properties){return new SignedMessage(properties);};/**
* Encodes the specified SignedMessage message. Does not implicitly {@link exonum.consensus.SignedMessage.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.SignedMessage
* @static
* @param {exonum.consensus.ISignedMessage} message SignedMessage message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/SignedMessage.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.chain_id_bytes!=null&&message.hasOwnProperty("chain_id_bytes"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.chain_id_bytes);if(message.payload!=null&&message.hasOwnProperty("payload"))writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.payload);if(message.author!=null&&message.hasOwnProperty("author"))$root.exonum.crypto.PublicKey.encode(message.author,writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();if(message.signature!=null&&message.hasOwnProperty("signature"))$root.exonum.crypto.Signature.encode(message.signature,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();return writer;};/**
* Encodes the specified SignedMessage message, length delimited. Does not implicitly {@link exonum.consensus.SignedMessage.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.SignedMessage
* @static
* @param {exonum.consensus.ISignedMessage} message SignedMessage message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/SignedMessage.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a SignedMessage message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.SignedMessage
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.SignedMessage} SignedMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/SignedMessage.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.SignedMessage();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.chain_id_bytes=reader.bytes();break;case 2:message.payload=reader.bytes();break;case 3:message.author=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 4:message.signature=$root.exonum.crypto.Signature.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a SignedMessage message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.SignedMessage
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.SignedMessage} SignedMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/SignedMessage.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a SignedMessage message.
* @function verify
* @memberof exonum.consensus.SignedMessage
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/SignedMessage.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.chain_id_bytes!=null&&message.hasOwnProperty("chain_id_bytes"))if(!(message.chain_id_bytes&&typeof message.chain_id_bytes.length==="number"||$util.isString(message.chain_id_bytes)))return"chain_id_bytes: buffer expected";if(message.payload!=null&&message.hasOwnProperty("payload"))if(!(message.payload&&typeof message.payload.length==="number"||$util.isString(message.payload)))return"payload: buffer expected";if(message.author!=null&&message.hasOwnProperty("author")){var error=$root.exonum.crypto.PublicKey.verify(message.author);if(error)return"author."+error;}if(message.signature!=null&&message.hasOwnProperty("signature")){var error=$root.exonum.crypto.Signature.verify(message.signature);if(error)return"signature."+error;}return null;};/**
* Creates a SignedMessage message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.SignedMessage
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.SignedMessage} SignedMessage
*/SignedMessage.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.SignedMessage)return object;var message=new $root.exonum.consensus.SignedMessage();if(object.chain_id_bytes!=null)if(typeof object.chain_id_bytes==="string")$util.base64.decode(object.chain_id_bytes,message.chain_id_bytes=$util.newBuffer($util.base64.length(object.chain_id_bytes)),0);else if(object.chain_id_bytes.length)message.chain_id_bytes=object.chain_id_bytes;if(object.payload!=null)if(typeof object.payload==="string")$util.base64.decode(object.payload,message.payload=$util.newBuffer($util.base64.length(object.payload)),0);else if(object.payload.length)message.payload=object.payload;if(object.author!=null){if((0,_typeof2["default"])(object.author)!=="object")throw TypeError(".exonum.consensus.SignedMessage.author: object expected");message.author=$root.exonum.crypto.PublicKey.fromObject(object.author);}if(object.signature!=null){if((0,_typeof2["default"])(object.signature)!=="object")throw TypeError(".exonum.consensus.SignedMessage.signature: object expected");message.signature=$root.exonum.crypto.Signature.fromObject(object.signature);}return message;};/**
* Creates a plain object from a SignedMessage message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.SignedMessage
* @static
* @param {exonum.consensus.SignedMessage} message SignedMessage
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/SignedMessage.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if(options.bytes===String)object.chain_id_bytes="";else{object.chain_id_bytes=[];if(options.bytes!==Array)object.chain_id_bytes=$util.newBuffer(object.chain_id_bytes);}if(options.bytes===String)object.payload="";else{object.payload=[];if(options.bytes!==Array)object.payload=$util.newBuffer(object.payload);}object.author=null;object.signature=null;}if(message.chain_id_bytes!=null&&message.hasOwnProperty("chain_id_bytes"))object.chain_id_bytes=options.bytes===String?$util.base64.encode(message.chain_id_bytes,0,message.chain_id_bytes.length):options.bytes===Array?Array.prototype.slice.call(message.chain_id_bytes):message.chain_id_bytes;if(message.payload!=null&&message.hasOwnProperty("payload"))object.payload=options.bytes===String?$util.base64.encode(message.payload,0,message.payload.length):options.bytes===Array?Array.prototype.slice.call(message.payload):message.payload;if(message.author!=null&&message.hasOwnProperty("author"))object.author=$root.exonum.crypto.PublicKey.toObject(message.author,options);if(message.signature!=null&&message.hasOwnProperty("signature"))object.signature=$root.exonum.crypto.Signature.toObject(message.signature,options);return object;};/**
* Converts this SignedMessage to JSON.
* @function toJSON
* @memberof exonum.consensus.SignedMessage
* @instance
* @returns {Object.<string,*>} JSON object
*/SignedMessage.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return SignedMessage;}();consensus.Connect=function(){/**
* Properties of a Connect.
* @memberof exonum.consensus
* @interface IConnect
* @property {string|null} [host] Connect host
* @property {google.protobuf.ITimestamp|null} [time] Connect time
* @property {string|null} [user_agent] Connect user_agent
*/ /**
* Constructs a new Connect.
* @memberof exonum.consensus
* @classdesc Represents a Connect.
* @implements IConnect
* @constructor
* @param {exonum.consensus.IConnect=} [properties] Properties to set
*/function Connect(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Connect host.
* @member {string} host
* @memberof exonum.consensus.Connect
* @instance
*/Connect.prototype.host="";/**
* Connect time.
* @member {google.protobuf.ITimestamp|null|undefined} time
* @memberof exonum.consensus.Connect
* @instance
*/Connect.prototype.time=null;/**
* Connect user_agent.
* @member {string} user_agent
* @memberof exonum.consensus.Connect
* @instance
*/Connect.prototype.user_agent="";/**
* Creates a new Connect instance using the specified properties.
* @function create
* @memberof exonum.consensus.Connect
* @static
* @param {exonum.consensus.IConnect=} [properties] Properties to set
* @returns {exonum.consensus.Connect} Connect instance
*/Connect.create=function create(properties){return new Connect(properties);};/**
* Encodes the specified Connect message. Does not implicitly {@link exonum.consensus.Connect.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.Connect
* @static
* @param {exonum.consensus.IConnect} message Connect message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Connect.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.host!=null&&message.hasOwnProperty("host"))writer.uint32(/* id 1, wireType 2 =*/10).string(message.host);if(message.time!=null&&message.hasOwnProperty("time"))$root.google.protobuf.Timestamp.encode(message.time,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();if(message.user_agent!=null&&message.hasOwnProperty("user_agent"))writer.uint32(/* id 3, wireType 2 =*/26).string(message.user_agent);return writer;};/**
* Encodes the specified Connect message, length delimited. Does not implicitly {@link exonum.consensus.Connect.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.Connect
* @static
* @param {exonum.consensus.IConnect} message Connect message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Connect.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Connect message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.Connect
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.Connect} Connect
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Connect.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.Connect();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.host=reader.string();break;case 2:message.time=$root.google.protobuf.Timestamp.decode(reader,reader.uint32());break;case 3:message.user_agent=reader.string();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Connect message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.Connect
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.Connect} Connect
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Connect.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Connect message.
* @function verify
* @memberof exonum.consensus.Connect
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Connect.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.host!=null&&message.hasOwnProperty("host"))if(!$util.isString(message.host))return"host: string expected";if(message.time!=null&&message.hasOwnProperty("time")){var error=$root.google.protobuf.Timestamp.verify(message.time);if(error)return"time."+error;}if(message.user_agent!=null&&message.hasOwnProperty("user_agent"))if(!$util.isString(message.user_agent))return"user_agent: string expected";return null;};/**
* Creates a Connect message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.Connect
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.Connect} Connect
*/Connect.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.Connect)return object;var message=new $root.exonum.consensus.Connect();if(object.host!=null)message.host=String(object.host);if(object.time!=null){if((0,_typeof2["default"])(object.time)!=="object")throw TypeError(".exonum.consensus.Connect.time: object expected");message.time=$root.google.protobuf.Timestamp.fromObject(object.time);}if(object.user_agent!=null)message.user_agent=String(object.user_agent);return message;};/**
* Creates a plain object from a Connect message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.Connect
* @static
* @param {exonum.consensus.Connect} message Connect
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Connect.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.host="";object.time=null;object.user_agent="";}if(message.host!=null&&message.hasOwnProperty("host"))object.host=message.host;if(message.time!=null&&message.hasOwnProperty("time"))object.time=$root.google.protobuf.Timestamp.toObject(message.time,options);if(message.user_agent!=null&&message.hasOwnProperty("user_agent"))object.user_agent=message.user_agent;return object;};/**
* Converts this Connect to JSON.
* @function toJSON
* @memberof exonum.consensus.Connect
* @instance
* @returns {Object.<string,*>} JSON object
*/Connect.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Connect;}();consensus.Status=function(){/**
* Properties of a Status.
* @memberof exonum.consensus
* @interface IStatus
* @property {number|Long|null} [height] Status height
* @property {exonum.crypto.IHash|null} [last_hash] Status last_hash
* @property {number|Long|null} [pool_size] Status pool_size
*/ /**
* Constructs a new Status.
* @memberof exonum.consensus
* @classdesc Represents a Status.
* @implements IStatus
* @constructor
* @param {exonum.consensus.IStatus=} [properties] Properties to set
*/function Status(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Status height.
* @member {number|Long} height
* @memberof exonum.consensus.Status
* @instance
*/Status.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Status last_hash.
* @member {exonum.crypto.IHash|null|undefined} last_hash
* @memberof exonum.consensus.Status
* @instance
*/Status.prototype.last_hash=null;/**
* Status pool_size.
* @member {number|Long} pool_size
* @memberof exonum.consensus.Status
* @instance
*/Status.prototype.pool_size=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Creates a new Status instance using the specified properties.
* @function create
* @memberof exonum.consensus.Status
* @static
* @param {exonum.consensus.IStatus=} [properties] Properties to set
* @returns {exonum.consensus.Status} Status instance
*/Status.create=function create(properties){return new Status(properties);};/**
* Encodes the specified Status message. Does not implicitly {@link exonum.consensus.Status.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.Status
* @static
* @param {exonum.consensus.IStatus} message Status message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Status.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.height);if(message.last_hash!=null&&message.hasOwnProperty("last_hash"))$root.exonum.crypto.Hash.encode(message.last_hash,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();if(message.pool_size!=null&&message.hasOwnProperty("pool_size"))writer.uint32(/* id 3, wireType 0 =*/24).uint64(message.pool_size);return writer;};/**
* Encodes the specified Status message, length delimited. Does not implicitly {@link exonum.consensus.Status.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.Status
* @static
* @param {exonum.consensus.IStatus} message Status message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Status.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Status message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.Status
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.Status} Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Status.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.Status();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.height=reader.uint64();break;case 2:message.last_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 3:message.pool_size=reader.uint64();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Status message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.Status
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.Status} Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Status.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Status message.
* @function verify
* @memberof exonum.consensus.Status
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Status.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";if(message.last_hash!=null&&message.hasOwnProperty("last_hash")){var error=$root.exonum.crypto.Hash.verify(message.last_hash);if(error)return"last_hash."+error;}if(message.pool_size!=null&&message.hasOwnProperty("pool_size"))if(!$util.isInteger(message.pool_size)&&!(message.pool_size&&$util.isInteger(message.pool_size.low)&&$util.isInteger(message.pool_size.high)))return"pool_size: integer|Long expected";return null;};/**
* Creates a Status message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.Status
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.Status} Status
*/Status.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.Status)return object;var message=new $root.exonum.consensus.Status();if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);if(object.last_hash!=null){if((0,_typeof2["default"])(object.last_hash)!=="object")throw TypeError(".exonum.consensus.Status.last_hash: object expected");message.last_hash=$root.exonum.crypto.Hash.fromObject(object.last_hash);}if(object.pool_size!=null)if($util.Long)(message.pool_size=$util.Long.fromValue(object.pool_size)).unsigned=true;else if(typeof object.pool_size==="string")message.pool_size=parseInt(object.pool_size,10);else if(typeof object.pool_size==="number")message.pool_size=object.pool_size;else if((0,_typeof2["default"])(object.pool_size)==="object")message.pool_size=new $util.LongBits(object.pool_size.low>>>0,object.pool_size.high>>>0).toNumber(true);return message;};/**
* Creates a plain object from a Status message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.Status
* @static
* @param {exonum.consensus.Status} message Status
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Status.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if($util.Long){var _long5=new $util.Long(0,0,true);object.height=options.longs===String?_long5.toString():options.longs===Number?_long5.toNumber():_long5;}else object.height=options.longs===String?"0":0;object.last_hash=null;if($util.Long){var _long5=new $util.Long(0,0,true);object.pool_size=options.longs===String?_long5.toString():options.longs===Number?_long5.toNumber():_long5;}else object.pool_size=options.longs===String?"0":0;}if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;if(message.last_hash!=null&&message.hasOwnProperty("last_hash"))object.last_hash=$root.exonum.crypto.Hash.toObject(message.last_hash,options);if(message.pool_size!=null&&message.hasOwnProperty("pool_size"))if(typeof message.pool_size==="number")object.pool_size=options.longs===String?String(message.pool_size):message.pool_size;else object.pool_size=options.longs===String?$util.Long.prototype.toString.call(message.pool_size):options.longs===Number?new $util.LongBits(message.pool_size.low>>>0,message.pool_size.high>>>0).toNumber(true):message.pool_size;return object;};/**
* Converts this Status to JSON.
* @function toJSON
* @memberof exonum.consensus.Status
* @instance
* @returns {Object.<string,*>} JSON object
*/Status.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Status;}();consensus.Propose=function(){/**
* Properties of a Propose.
* @memberof exonum.consensus
* @interface IPropose
* @property {number|null} [validator] Propose validator
* @property {number|Long|null} [height] Propose height
* @property {number|null} [round] Propose round
* @property {exonum.crypto.IHash|null} [prev_hash] Propose prev_hash
* @property {Array.<exonum.crypto.IHash>|null} [transactions] Propose transactions
*/ /**
* Constructs a new Propose.
* @memberof exonum.consensus
* @classdesc Represents a Propose.
* @implements IPropose
* @constructor
* @param {exonum.consensus.IPropose=} [properties] Properties to set
*/function Propose(properties){this.transactions=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Propose validator.
* @member {number} validator
* @memberof exonum.consensus.Propose
* @instance
*/Propose.prototype.validator=0;/**
* Propose height.
* @member {number|Long} height
* @memberof exonum.consensus.Propose
* @instance
*/Propose.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Propose round.
* @member {number} round
* @memberof exonum.consensus.Propose
* @instance
*/Propose.prototype.round=0;/**
* Propose prev_hash.
* @member {exonum.crypto.IHash|null|undefined} prev_hash
* @memberof exonum.consensus.Propose
* @instance
*/Propose.prototype.prev_hash=null;/**
* Propose transactions.
* @member {Array.<exonum.crypto.IHash>} transactions
* @memberof exonum.consensus.Propose
* @instance
*/Propose.prototype.transactions=$util.emptyArray;/**
* Creates a new Propose instance using the specified properties.
* @function create
* @memberof exonum.consensus.Propose
* @static
* @param {exonum.consensus.IPropose=} [properties] Properties to set
* @returns {exonum.consensus.Propose} Propose instance
*/Propose.create=function create(properties){return new Propose(properties);};/**
* Encodes the specified Propose message. Does not implicitly {@link exonum.consensus.Propose.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.Propose
* @static
* @param {exonum.consensus.IPropose} message Propose message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Propose.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.validator!=null&&message.hasOwnProperty("validator"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.validator);if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.height);if(message.round!=null&&message.hasOwnProperty("round"))writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.round);if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash"))$root.exonum.crypto.Hash.encode(message.prev_hash,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();if(message.transactions!=null&&message.transactions.length)for(var i=0;i<message.transactions.length;++i){$root.exonum.crypto.Hash.encode(message.transactions[i],writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();}return writer;};/**
* Encodes the specified Propose message, length delimited. Does not implicitly {@link exonum.consensus.Propose.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.Propose
* @static
* @param {exonum.consensus.IPropose} message Propose message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Propose.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Propose message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.Propose
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.Propose} Propose
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Propose.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.Propose();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.validator=reader.uint32();break;case 2:message.height=reader.uint64();break;case 3:message.round=reader.uint32();break;case 4:message.prev_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 5:if(!(message.transactions&&message.transactions.length))message.transactions=[];message.transactions.push($root.exonum.crypto.Hash.decode(reader,reader.uint32()));break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Propose message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.Propose
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.Propose} Propose
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Propose.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Propose message.
* @function verify
* @memberof exonum.consensus.Propose
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Propose.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.validator!=null&&message.hasOwnProperty("validator"))if(!$util.isInteger(message.validator))return"validator: integer expected";if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";if(message.round!=null&&message.hasOwnProperty("round"))if(!$util.isInteger(message.round))return"round: integer expected";if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash")){var error=$root.exonum.crypto.Hash.verify(message.prev_hash);if(error)return"prev_hash."+error;}if(message.transactions!=null&&message.hasOwnProperty("transactions")){if(!Array.isArray(message.transactions))return"transactions: array expected";for(var i=0;i<message.transactions.length;++i){var error=$root.exonum.crypto.Hash.verify(message.transactions[i]);if(error)return"transactions."+error;}}return null;};/**
* Creates a Propose message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.Propose
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.Propose} Propose
*/Propose.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.Propose)return object;var message=new $root.exonum.consensus.Propose();if(object.validator!=null)message.validator=object.validator>>>0;if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);if(object.round!=null)message.round=object.round>>>0;if(object.prev_hash!=null){if((0,_typeof2["default"])(object.prev_hash)!=="object")throw TypeError(".exonum.consensus.Propose.prev_hash: object expected");message.prev_hash=$root.exonum.crypto.Hash.fromObject(object.prev_hash);}if(object.transactions){if(!Array.isArray(object.transactions))throw TypeError(".exonum.consensus.Propose.transactions: array expected");message.transactions=[];for(var i=0;i<object.transactions.length;++i){if((0,_typeof2["default"])(object.transactions[i])!=="object")throw TypeError(".exonum.consensus.Propose.transactions: object expected");message.transactions[i]=$root.exonum.crypto.Hash.fromObject(object.transactions[i]);}}return message;};/**
* Creates a plain object from a Propose message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.Propose
* @static
* @param {exonum.consensus.Propose} message Propose
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Propose.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.transactions=[];if(options.defaults){object.validator=0;if($util.Long){var _long6=new $util.Long(0,0,true);object.height=options.longs===String?_long6.toString():options.longs===Number?_long6.toNumber():_long6;}else object.height=options.longs===String?"0":0;object.round=0;object.prev_hash=null;}if(message.validator!=null&&message.hasOwnProperty("validator"))object.validator=message.validator;if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;if(message.round!=null&&message.hasOwnProperty("round"))object.round=message.round;if(message.prev_hash!=null&&message.hasOwnProperty("prev_hash"))object.prev_hash=$root.exonum.crypto.Hash.toObject(message.prev_hash,options);if(message.transactions&&message.transactions.length){object.transactions=[];for(var j=0;j<message.transactions.length;++j){object.transactions[j]=$root.exonum.crypto.Hash.toObject(message.transactions[j],options);}}return object;};/**
* Converts this Propose to JSON.
* @function toJSON
* @memberof exonum.consensus.Propose
* @instance
* @returns {Object.<string,*>} JSON object
*/Propose.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Propose;}();consensus.Prevote=function(){/**
* Properties of a Prevote.
* @memberof exonum.consensus
* @interface IPrevote
* @property {number|null} [validator] Prevote validator
* @property {number|Long|null} [height] Prevote height
* @property {number|null} [round] Prevote round
* @property {exonum.crypto.IHash|null} [propose_hash] Prevote propose_hash
* @property {number|null} [locked_round] Prevote locked_round
*/ /**
* Constructs a new Prevote.
* @memberof exonum.consensus
* @classdesc Represents a Prevote.
* @implements IPrevote
* @constructor
* @param {exonum.consensus.IPrevote=} [properties] Properties to set
*/function Prevote(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Prevote validator.
* @member {number} validator
* @memberof exonum.consensus.Prevote
* @instance
*/Prevote.prototype.validator=0;/**
* Prevote height.
* @member {number|Long} height
* @memberof exonum.consensus.Prevote
* @instance
*/Prevote.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Prevote round.
* @member {number} round
* @memberof exonum.consensus.Prevote
* @instance
*/Prevote.prototype.round=0;/**
* Prevote propose_hash.
* @member {exonum.crypto.IHash|null|undefined} propose_hash
* @memberof exonum.consensus.Prevote
* @instance
*/Prevote.prototype.propose_hash=null;/**
* Prevote locked_round.
* @member {number} locked_round
* @memberof exonum.consensus.Prevote
* @instance
*/Prevote.prototype.locked_round=0;/**
* Creates a new Prevote instance using the specified properties.
* @function create
* @memberof exonum.consensus.Prevote
* @static
* @param {exonum.consensus.IPrevote=} [properties] Properties to set
* @returns {exonum.consensus.Prevote} Prevote instance
*/Prevote.create=function create(properties){return new Prevote(properties);};/**
* Encodes the specified Prevote message. Does not implicitly {@link exonum.consensus.Prevote.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.Prevote
* @static
* @param {exonum.consensus.IPrevote} message Prevote message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Prevote.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.validator!=null&&message.hasOwnProperty("validator"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.validator);if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.height);if(message.round!=null&&message.hasOwnProperty("round"))writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.round);if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))$root.exonum.crypto.Hash.encode(message.propose_hash,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();if(message.locked_round!=null&&message.hasOwnProperty("locked_round"))writer.uint32(/* id 5, wireType 0 =*/40).uint32(message.locked_round);return writer;};/**
* Encodes the specified Prevote message, length delimited. Does not implicitly {@link exonum.consensus.Prevote.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.Prevote
* @static
* @param {exonum.consensus.IPrevote} message Prevote message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Prevote.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Prevote message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.Prevote
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.Prevote} Prevote
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Prevote.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.Prevote();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.validator=reader.uint32();break;case 2:message.height=reader.uint64();break;case 3:message.round=reader.uint32();break;case 4:message.propose_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 5:message.locked_round=reader.uint32();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Prevote message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.Prevote
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.Prevote} Prevote
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Prevote.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Prevote message.
* @function verify
* @memberof exonum.consensus.Prevote
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Prevote.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.validator!=null&&message.hasOwnProperty("validator"))if(!$util.isInteger(message.validator))return"validator: integer expected";if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";if(message.round!=null&&message.hasOwnProperty("round"))if(!$util.isInteger(message.round))return"round: integer expected";if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash")){var error=$root.exonum.crypto.Hash.verify(message.propose_hash);if(error)return"propose_hash."+error;}if(message.locked_round!=null&&message.hasOwnProperty("locked_round"))if(!$util.isInteger(message.locked_round))return"locked_round: integer expected";return null;};/**
* Creates a Prevote message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.Prevote
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.Prevote} Prevote
*/Prevote.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.Prevote)return object;var message=new $root.exonum.consensus.Prevote();if(object.validator!=null)message.validator=object.validator>>>0;if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);if(object.round!=null)message.round=object.round>>>0;if(object.propose_hash!=null){if((0,_typeof2["default"])(object.propose_hash)!=="object")throw TypeError(".exonum.consensus.Prevote.propose_hash: object expected");message.propose_hash=$root.exonum.crypto.Hash.fromObject(object.propose_hash);}if(object.locked_round!=null)message.locked_round=object.locked_round>>>0;return message;};/**
* Creates a plain object from a Prevote message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.Prevote
* @static
* @param {exonum.consensus.Prevote} message Prevote
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Prevote.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.validator=0;if($util.Long){var _long7=new $util.Long(0,0,true);object.height=options.longs===String?_long7.toString():options.longs===Number?_long7.toNumber():_long7;}else object.height=options.longs===String?"0":0;object.round=0;object.propose_hash=null;object.locked_round=0;}if(message.validator!=null&&message.hasOwnProperty("validator"))object.validator=message.validator;if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;if(message.round!=null&&message.hasOwnProperty("round"))object.round=message.round;if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))object.propose_hash=$root.exonum.crypto.Hash.toObject(message.propose_hash,options);if(message.locked_round!=null&&message.hasOwnProperty("locked_round"))object.locked_round=message.locked_round;return object;};/**
* Converts this Prevote to JSON.
* @function toJSON
* @memberof exonum.consensus.Prevote
* @instance
* @returns {Object.<string,*>} JSON object
*/Prevote.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Prevote;}();consensus.Precommit=function(){/**
* Properties of a Precommit.
* @memberof exonum.consensus
* @interface IPrecommit
* @property {number|null} [validator] Precommit validator
* @property {number|Long|null} [height] Precommit height
* @property {number|null} [round] Precommit round
* @property {exonum.crypto.IHash|null} [propose_hash] Precommit propose_hash
* @property {exonum.crypto.IHash|null} [block_hash] Precommit block_hash
* @property {google.protobuf.ITimestamp|null} [time] Precommit time
*/ /**
* Constructs a new Precommit.
* @memberof exonum.consensus
* @classdesc Represents a Precommit.
* @implements IPrecommit
* @constructor
* @param {exonum.consensus.IPrecommit=} [properties] Properties to set
*/function Precommit(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Precommit validator.
* @member {number} validator
* @memberof exonum.consensus.Precommit
* @instance
*/Precommit.prototype.validator=0;/**
* Precommit height.
* @member {number|Long} height
* @memberof exonum.consensus.Precommit
* @instance
*/Precommit.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Precommit round.
* @member {number} round
* @memberof exonum.consensus.Precommit
* @instance
*/Precommit.prototype.round=0;/**
* Precommit propose_hash.
* @member {exonum.crypto.IHash|null|undefined} propose_hash
* @memberof exonum.consensus.Precommit
* @instance
*/Precommit.prototype.propose_hash=null;/**
* Precommit block_hash.
* @member {exonum.crypto.IHash|null|undefined} block_hash
* @memberof exonum.consensus.Precommit
* @instance
*/Precommit.prototype.block_hash=null;/**
* Precommit time.
* @member {google.protobuf.ITimestamp|null|undefined} time
* @memberof exonum.consensus.Precommit
* @instance
*/Precommit.prototype.time=null;/**
* Creates a new Precommit instance using the specified properties.
* @function create
* @memberof exonum.consensus.Precommit
* @static
* @param {exonum.consensus.IPrecommit=} [properties] Properties to set
* @returns {exonum.consensus.Precommit} Precommit instance
*/Precommit.create=function create(properties){return new Precommit(properties);};/**
* Encodes the specified Precommit message. Does not implicitly {@link exonum.consensus.Precommit.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.Precommit
* @static
* @param {exonum.consensus.IPrecommit} message Precommit message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Precommit.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.validator!=null&&message.hasOwnProperty("validator"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.validator);if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.height);if(message.round!=null&&message.hasOwnProperty("round"))writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.round);if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))$root.exonum.crypto.Hash.encode(message.propose_hash,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();if(message.block_hash!=null&&message.hasOwnProperty("block_hash"))$root.exonum.crypto.Hash.encode(message.block_hash,writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();if(message.time!=null&&message.hasOwnProperty("time"))$root.google.protobuf.Timestamp.encode(message.time,writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim();return writer;};/**
* Encodes the specified Precommit message, length delimited. Does not implicitly {@link exonum.consensus.Precommit.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.Precommit
* @static
* @param {exonum.consensus.IPrecommit} message Precommit message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Precommit.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Precommit message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.Precommit
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.Precommit} Precommit
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Precommit.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.Precommit();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.validator=reader.uint32();break;case 2:message.height=reader.uint64();break;case 3:message.round=reader.uint32();break;case 4:message.propose_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 5:message.block_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 6:message.time=$root.google.protobuf.Timestamp.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Precommit message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.Precommit
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.Precommit} Precommit
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Precommit.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Precommit message.
* @function verify
* @memberof exonum.consensus.Precommit
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Precommit.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.validator!=null&&message.hasOwnProperty("validator"))if(!$util.isInteger(message.validator))return"validator: integer expected";if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";if(message.round!=null&&message.hasOwnProperty("round"))if(!$util.isInteger(message.round))return"round: integer expected";if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash")){var error=$root.exonum.crypto.Hash.verify(message.propose_hash);if(error)return"propose_hash."+error;}if(message.block_hash!=null&&message.hasOwnProperty("block_hash")){var error=$root.exonum.crypto.Hash.verify(message.block_hash);if(error)return"block_hash."+error;}if(message.time!=null&&message.hasOwnProperty("time")){var error=$root.google.protobuf.Timestamp.verify(message.time);if(error)return"time."+error;}return null;};/**
* Creates a Precommit message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.Precommit
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.Precommit} Precommit
*/Precommit.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.Precommit)return object;var message=new $root.exonum.consensus.Precommit();if(object.validator!=null)message.validator=object.validator>>>0;if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);if(object.round!=null)message.round=object.round>>>0;if(object.propose_hash!=null){if((0,_typeof2["default"])(object.propose_hash)!=="object")throw TypeError(".exonum.consensus.Precommit.propose_hash: object expected");message.propose_hash=$root.exonum.crypto.Hash.fromObject(object.propose_hash);}if(object.block_hash!=null){if((0,_typeof2["default"])(object.block_hash)!=="object")throw TypeError(".exonum.consensus.Precommit.block_hash: object expected");message.block_hash=$root.exonum.crypto.Hash.fromObject(object.block_hash);}if(object.time!=null){if((0,_typeof2["default"])(object.time)!=="object")throw TypeError(".exonum.consensus.Precommit.time: object expected");message.time=$root.google.protobuf.Timestamp.fromObject(object.time);}return message;};/**
* Creates a plain object from a Precommit message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.Precommit
* @static
* @param {exonum.consensus.Precommit} message Precommit
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Precommit.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.validator=0;if($util.Long){var _long8=new $util.Long(0,0,true);object.height=options.longs===String?_long8.toString():options.longs===Number?_long8.toNumber():_long8;}else object.height=options.longs===String?"0":0;object.round=0;object.propose_hash=null;object.block_hash=null;object.time=null;}if(message.validator!=null&&message.hasOwnProperty("validator"))object.validator=message.validator;if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;if(message.round!=null&&message.hasOwnProperty("round"))object.round=message.round;if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))object.propose_hash=$root.exonum.crypto.Hash.toObject(message.propose_hash,options);if(message.block_hash!=null&&message.hasOwnProperty("block_hash"))object.block_hash=$root.exonum.crypto.Hash.toObject(message.block_hash,options);if(message.time!=null&&message.hasOwnProperty("time"))object.time=$root.google.protobuf.Timestamp.toObject(message.time,options);return object;};/**
* Converts this Precommit to JSON.
* @function toJSON
* @memberof exonum.consensus.Precommit
* @instance
* @returns {Object.<string,*>} JSON object
*/Precommit.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Precommit;}();consensus.BlockResponse=function(){/**
* Properties of a BlockResponse.
* @memberof exonum.consensus
* @interface IBlockResponse
* @property {exonum.crypto.IPublicKey|null} [to] BlockResponse to
* @property {exonum.IBlock|null} [block] BlockResponse block
* @property {Array.<Uint8Array>|null} [precommits] BlockResponse precommits
* @property {Array.<exonum.crypto.IHash>|null} [transactions] BlockResponse transactions
*/ /**
* Constructs a new BlockResponse.
* @memberof exonum.consensus
* @classdesc Represents a BlockResponse.
* @implements IBlockResponse
* @constructor
* @param {exonum.consensus.IBlockResponse=} [properties] Properties to set
*/function BlockResponse(properties){this.precommits=[];this.transactions=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* BlockResponse to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.BlockResponse
* @instance
*/BlockResponse.prototype.to=null;/**
* BlockResponse block.
* @member {exonum.IBlock|null|undefined} block
* @memberof exonum.consensus.BlockResponse
* @instance
*/BlockResponse.prototype.block=null;/**
* BlockResponse precommits.
* @member {Array.<Uint8Array>} precommits
* @memberof exonum.consensus.BlockResponse
* @instance
*/BlockResponse.prototype.precommits=$util.emptyArray;/**
* BlockResponse transactions.
* @member {Array.<exonum.crypto.IHash>} transactions
* @memberof exonum.consensus.BlockResponse
* @instance
*/BlockResponse.prototype.transactions=$util.emptyArray;/**
* Creates a new BlockResponse instance using the specified properties.
* @function create
* @memberof exonum.consensus.BlockResponse
* @static
* @param {exonum.consensus.IBlockResponse=} [properties] Properties to set
* @returns {exonum.consensus.BlockResponse} BlockResponse instance
*/BlockResponse.create=function create(properties){return new BlockResponse(properties);};/**
* Encodes the specified BlockResponse message. Does not implicitly {@link exonum.consensus.BlockResponse.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.BlockResponse
* @static
* @param {exonum.consensus.IBlockResponse} message BlockResponse message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BlockResponse.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.block!=null&&message.hasOwnProperty("block"))$root.exonum.Block.encode(message.block,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();if(message.precommits!=null&&message.precommits.length)for(var i=0;i<message.precommits.length;++i){writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.precommits[i]);}if(message.transactions!=null&&message.transactions.length)for(var i=0;i<message.transactions.length;++i){$root.exonum.crypto.Hash.encode(message.transactions[i],writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();}return writer;};/**
* Encodes the specified BlockResponse message, length delimited. Does not implicitly {@link exonum.consensus.BlockResponse.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.BlockResponse
* @static
* @param {exonum.consensus.IBlockResponse} message BlockResponse message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BlockResponse.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a BlockResponse message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.BlockResponse
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.BlockResponse} BlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BlockResponse.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.BlockResponse();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:message.block=$root.exonum.Block.decode(reader,reader.uint32());break;case 3:if(!(message.precommits&&message.precommits.length))message.precommits=[];message.precommits.push(reader.bytes());break;case 4:if(!(message.transactions&&message.transactions.length))message.transactions=[];message.transactions.push($root.exonum.crypto.Hash.decode(reader,reader.uint32()));break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a BlockResponse message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.BlockResponse
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.BlockResponse} BlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BlockResponse.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a BlockResponse message.
* @function verify
* @memberof exonum.consensus.BlockResponse
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/BlockResponse.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}if(message.block!=null&&message.hasOwnProperty("block")){var error=$root.exonum.Block.verify(message.block);if(error)return"block."+error;}if(message.precommits!=null&&message.hasOwnProperty("precommits")){if(!Array.isArray(message.precommits))return"precommits: array expected";for(var i=0;i<message.precommits.length;++i){if(!(message.precommits[i]&&typeof message.precommits[i].length==="number"||$util.isString(message.precommits[i])))return"precommits: buffer[] expected";}}if(message.transactions!=null&&message.hasOwnProperty("transactions")){if(!Array.isArray(message.transactions))return"transactions: array expected";for(var i=0;i<message.transactions.length;++i){var error=$root.exonum.crypto.Hash.verify(message.transactions[i]);if(error)return"transactions."+error;}}return null;};/**
* Creates a BlockResponse message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.BlockResponse
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.BlockResponse} BlockResponse
*/BlockResponse.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.BlockResponse)return object;var message=new $root.exonum.consensus.BlockResponse();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.BlockResponse.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}if(object.block!=null){if((0,_typeof2["default"])(object.block)!=="object")throw TypeError(".exonum.consensus.BlockResponse.block: object expected");message.block=$root.exonum.Block.fromObject(object.block);}if(object.precommits){if(!Array.isArray(object.precommits))throw TypeError(".exonum.consensus.BlockResponse.precommits: array expected");message.precommits=[];for(var i=0;i<object.precommits.length;++i){if(typeof object.precommits[i]==="string")$util.base64.decode(object.precommits[i],message.precommits[i]=$util.newBuffer($util.base64.length(object.precommits[i])),0);else if(object.precommits[i].length)message.precommits[i]=object.precommits[i];}}if(object.transactions){if(!Array.isArray(object.transactions))throw TypeError(".exonum.consensus.BlockResponse.transactions: array expected");message.transactions=[];for(var i=0;i<object.transactions.length;++i){if((0,_typeof2["default"])(object.transactions[i])!=="object")throw TypeError(".exonum.consensus.BlockResponse.transactions: object expected");message.transactions[i]=$root.exonum.crypto.Hash.fromObject(object.transactions[i]);}}return message;};/**
* Creates a plain object from a BlockResponse message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.BlockResponse
* @static
* @param {exonum.consensus.BlockResponse} message BlockResponse
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/BlockResponse.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults){object.precommits=[];object.transactions=[];}if(options.defaults){object.to=null;object.block=null;}if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);if(message.block!=null&&message.hasOwnProperty("block"))object.block=$root.exonum.Block.toObject(message.block,options);if(message.precommits&&message.precommits.length){object.precommits=[];for(var j=0;j<message.precommits.length;++j){object.precommits[j]=options.bytes===String?$util.base64.encode(message.precommits[j],0,message.precommits[j].length):options.bytes===Array?Array.prototype.slice.call(message.precommits[j]):message.precommits[j];}}if(message.transactions&&message.transactions.length){object.transactions=[];for(var j=0;j<message.transactions.length;++j){object.transactions[j]=$root.exonum.crypto.Hash.toObject(message.transactions[j],options);}}return object;};/**
* Converts this BlockResponse to JSON.
* @function toJSON
* @memberof exonum.consensus.BlockResponse
* @instance
* @returns {Object.<string,*>} JSON object
*/BlockResponse.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return BlockResponse;}();consensus.TransactionsResponse=function(){/**
* Properties of a TransactionsResponse.
* @memberof exonum.consensus
* @interface ITransactionsResponse
* @property {exonum.crypto.IPublicKey|null} [to] TransactionsResponse to
* @property {Array.<Uint8Array>|null} [transactions] TransactionsResponse transactions
*/ /**
* Constructs a new TransactionsResponse.
* @memberof exonum.consensus
* @classdesc Represents a TransactionsResponse.
* @implements ITransactionsResponse
* @constructor
* @param {exonum.consensus.ITransactionsResponse=} [properties] Properties to set
*/function TransactionsResponse(properties){this.transactions=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* TransactionsResponse to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.TransactionsResponse
* @instance
*/TransactionsResponse.prototype.to=null;/**
* TransactionsResponse transactions.
* @member {Array.<Uint8Array>} transactions
* @memberof exonum.consensus.TransactionsResponse
* @instance
*/TransactionsResponse.prototype.transactions=$util.emptyArray;/**
* Creates a new TransactionsResponse instance using the specified properties.
* @function create
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {exonum.consensus.ITransactionsResponse=} [properties] Properties to set
* @returns {exonum.consensus.TransactionsResponse} TransactionsResponse instance
*/TransactionsResponse.create=function create(properties){return new TransactionsResponse(properties);};/**
* Encodes the specified TransactionsResponse message. Does not implicitly {@link exonum.consensus.TransactionsResponse.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {exonum.consensus.ITransactionsResponse} message TransactionsResponse message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TransactionsResponse.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.transactions!=null&&message.transactions.length)for(var i=0;i<message.transactions.length;++i){writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.transactions[i]);}return writer;};/**
* Encodes the specified TransactionsResponse message, length delimited. Does not implicitly {@link exonum.consensus.TransactionsResponse.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {exonum.consensus.ITransactionsResponse} message TransactionsResponse message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TransactionsResponse.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a TransactionsResponse message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.TransactionsResponse} TransactionsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TransactionsResponse.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.TransactionsResponse();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:if(!(message.transactions&&message.transactions.length))message.transactions=[];message.transactions.push(reader.bytes());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a TransactionsResponse message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.TransactionsResponse} TransactionsResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TransactionsResponse.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a TransactionsResponse message.
* @function verify
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/TransactionsResponse.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}if(message.transactions!=null&&message.hasOwnProperty("transactions")){if(!Array.isArray(message.transactions))return"transactions: array expected";for(var i=0;i<message.transactions.length;++i){if(!(message.transactions[i]&&typeof message.transactions[i].length==="number"||$util.isString(message.transactions[i])))return"transactions: buffer[] expected";}}return null;};/**
* Creates a TransactionsResponse message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.TransactionsResponse} TransactionsResponse
*/TransactionsResponse.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.TransactionsResponse)return object;var message=new $root.exonum.consensus.TransactionsResponse();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.TransactionsResponse.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}if(object.transactions){if(!Array.isArray(object.transactions))throw TypeError(".exonum.consensus.TransactionsResponse.transactions: array expected");message.transactions=[];for(var i=0;i<object.transactions.length;++i){if(typeof object.transactions[i]==="string")$util.base64.decode(object.transactions[i],message.transactions[i]=$util.newBuffer($util.base64.length(object.transactions[i])),0);else if(object.transactions[i].length)message.transactions[i]=object.transactions[i];}}return message;};/**
* Creates a plain object from a TransactionsResponse message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.TransactionsResponse
* @static
* @param {exonum.consensus.TransactionsResponse} message TransactionsResponse
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/TransactionsResponse.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.transactions=[];if(options.defaults)object.to=null;if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);if(message.transactions&&message.transactions.length){object.transactions=[];for(var j=0;j<message.transactions.length;++j){object.transactions[j]=options.bytes===String?$util.base64.encode(message.transactions[j],0,message.transactions[j].length):options.bytes===Array?Array.prototype.slice.call(message.transactions[j]):message.transactions[j];}}return object;};/**
* Converts this TransactionsResponse to JSON.
* @function toJSON
* @memberof exonum.consensus.TransactionsResponse
* @instance
* @returns {Object.<string,*>} JSON object
*/TransactionsResponse.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return TransactionsResponse;}();consensus.ProposeRequest=function(){/**
* Properties of a ProposeRequest.
* @memberof exonum.consensus
* @interface IProposeRequest
* @property {exonum.crypto.IPublicKey|null} [to] ProposeRequest to
* @property {number|Long|null} [height] ProposeRequest height
* @property {exonum.crypto.IHash|null} [propose_hash] ProposeRequest propose_hash
*/ /**
* Constructs a new ProposeRequest.
* @memberof exonum.consensus
* @classdesc Represents a ProposeRequest.
* @implements IProposeRequest
* @constructor
* @param {exonum.consensus.IProposeRequest=} [properties] Properties to set
*/function ProposeRequest(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ProposeRequest to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.ProposeRequest
* @instance
*/ProposeRequest.prototype.to=null;/**
* ProposeRequest height.
* @member {number|Long} height
* @memberof exonum.consensus.ProposeRequest
* @instance
*/ProposeRequest.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* ProposeRequest propose_hash.
* @member {exonum.crypto.IHash|null|undefined} propose_hash
* @memberof exonum.consensus.ProposeRequest
* @instance
*/ProposeRequest.prototype.propose_hash=null;/**
* Creates a new ProposeRequest instance using the specified properties.
* @function create
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {exonum.consensus.IProposeRequest=} [properties] Properties to set
* @returns {exonum.consensus.ProposeRequest} ProposeRequest instance
*/ProposeRequest.create=function create(properties){return new ProposeRequest(properties);};/**
* Encodes the specified ProposeRequest message. Does not implicitly {@link exonum.consensus.ProposeRequest.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {exonum.consensus.IProposeRequest} message ProposeRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ProposeRequest.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.height);if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))$root.exonum.crypto.Hash.encode(message.propose_hash,writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();return writer;};/**
* Encodes the specified ProposeRequest message, length delimited. Does not implicitly {@link exonum.consensus.ProposeRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {exonum.consensus.IProposeRequest} message ProposeRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ProposeRequest.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a ProposeRequest message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.ProposeRequest} ProposeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ProposeRequest.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.ProposeRequest();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:message.height=reader.uint64();break;case 3:message.propose_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a ProposeRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.ProposeRequest} ProposeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ProposeRequest.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a ProposeRequest message.
* @function verify
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ProposeRequest.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash")){var error=$root.exonum.crypto.Hash.verify(message.propose_hash);if(error)return"propose_hash."+error;}return null;};/**
* Creates a ProposeRequest message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.ProposeRequest} ProposeRequest
*/ProposeRequest.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.ProposeRequest)return object;var message=new $root.exonum.consensus.ProposeRequest();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.ProposeRequest.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);if(object.propose_hash!=null){if((0,_typeof2["default"])(object.propose_hash)!=="object")throw TypeError(".exonum.consensus.ProposeRequest.propose_hash: object expected");message.propose_hash=$root.exonum.crypto.Hash.fromObject(object.propose_hash);}return message;};/**
* Creates a plain object from a ProposeRequest message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.ProposeRequest
* @static
* @param {exonum.consensus.ProposeRequest} message ProposeRequest
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ProposeRequest.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.to=null;if($util.Long){var _long9=new $util.Long(0,0,true);object.height=options.longs===String?_long9.toString():options.longs===Number?_long9.toNumber():_long9;}else object.height=options.longs===String?"0":0;object.propose_hash=null;}if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))object.propose_hash=$root.exonum.crypto.Hash.toObject(message.propose_hash,options);return object;};/**
* Converts this ProposeRequest to JSON.
* @function toJSON
* @memberof exonum.consensus.ProposeRequest
* @instance
* @returns {Object.<string,*>} JSON object
*/ProposeRequest.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ProposeRequest;}();consensus.TransactionsRequest=function(){/**
* Properties of a TransactionsRequest.
* @memberof exonum.consensus
* @interface ITransactionsRequest
* @property {exonum.crypto.IPublicKey|null} [to] TransactionsRequest to
* @property {Array.<exonum.crypto.IHash>|null} [txs] TransactionsRequest txs
*/ /**
* Constructs a new TransactionsRequest.
* @memberof exonum.consensus
* @classdesc Represents a TransactionsRequest.
* @implements ITransactionsRequest
* @constructor
* @param {exonum.consensus.ITransactionsRequest=} [properties] Properties to set
*/function TransactionsRequest(properties){this.txs=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* TransactionsRequest to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.TransactionsRequest
* @instance
*/TransactionsRequest.prototype.to=null;/**
* TransactionsRequest txs.
* @member {Array.<exonum.crypto.IHash>} txs
* @memberof exonum.consensus.TransactionsRequest
* @instance
*/TransactionsRequest.prototype.txs=$util.emptyArray;/**
* Creates a new TransactionsRequest instance using the specified properties.
* @function create
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {exonum.consensus.ITransactionsRequest=} [properties] Properties to set
* @returns {exonum.consensus.TransactionsRequest} TransactionsRequest instance
*/TransactionsRequest.create=function create(properties){return new TransactionsRequest(properties);};/**
* Encodes the specified TransactionsRequest message. Does not implicitly {@link exonum.consensus.TransactionsRequest.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {exonum.consensus.ITransactionsRequest} message TransactionsRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TransactionsRequest.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.txs!=null&&message.txs.length)for(var i=0;i<message.txs.length;++i){$root.exonum.crypto.Hash.encode(message.txs[i],writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();}return writer;};/**
* Encodes the specified TransactionsRequest message, length delimited. Does not implicitly {@link exonum.consensus.TransactionsRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {exonum.consensus.ITransactionsRequest} message TransactionsRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TransactionsRequest.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a TransactionsRequest message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.TransactionsRequest} TransactionsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TransactionsRequest.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.TransactionsRequest();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:if(!(message.txs&&message.txs.length))message.txs=[];message.txs.push($root.exonum.crypto.Hash.decode(reader,reader.uint32()));break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a TransactionsRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.TransactionsRequest} TransactionsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TransactionsRequest.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a TransactionsRequest message.
* @function verify
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/TransactionsRequest.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}if(message.txs!=null&&message.hasOwnProperty("txs")){if(!Array.isArray(message.txs))return"txs: array expected";for(var i=0;i<message.txs.length;++i){var error=$root.exonum.crypto.Hash.verify(message.txs[i]);if(error)return"txs."+error;}}return null;};/**
* Creates a TransactionsRequest message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.TransactionsRequest} TransactionsRequest
*/TransactionsRequest.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.TransactionsRequest)return object;var message=new $root.exonum.consensus.TransactionsRequest();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.TransactionsRequest.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}if(object.txs){if(!Array.isArray(object.txs))throw TypeError(".exonum.consensus.TransactionsRequest.txs: array expected");message.txs=[];for(var i=0;i<object.txs.length;++i){if((0,_typeof2["default"])(object.txs[i])!=="object")throw TypeError(".exonum.consensus.TransactionsRequest.txs: object expected");message.txs[i]=$root.exonum.crypto.Hash.fromObject(object.txs[i]);}}return message;};/**
* Creates a plain object from a TransactionsRequest message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.TransactionsRequest
* @static
* @param {exonum.consensus.TransactionsRequest} message TransactionsRequest
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/TransactionsRequest.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.txs=[];if(options.defaults)object.to=null;if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);if(message.txs&&message.txs.length){object.txs=[];for(var j=0;j<message.txs.length;++j){object.txs[j]=$root.exonum.crypto.Hash.toObject(message.txs[j],options);}}return object;};/**
* Converts this TransactionsRequest to JSON.
* @function toJSON
* @memberof exonum.consensus.TransactionsRequest
* @instance
* @returns {Object.<string,*>} JSON object
*/TransactionsRequest.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return TransactionsRequest;}();consensus.PrevotesRequest=function(){/**
* Properties of a PrevotesRequest.
* @memberof exonum.consensus
* @interface IPrevotesRequest
* @property {exonum.crypto.IPublicKey|null} [to] PrevotesRequest to
* @property {number|Long|null} [height] PrevotesRequest height
* @property {number|null} [round] PrevotesRequest round
* @property {exonum.crypto.IHash|null} [propose_hash] PrevotesRequest propose_hash
* @property {exonum.common.IBitVec|null} [validators] PrevotesRequest validators
*/ /**
* Constructs a new PrevotesRequest.
* @memberof exonum.consensus
* @classdesc Represents a PrevotesRequest.
* @implements IPrevotesRequest
* @constructor
* @param {exonum.consensus.IPrevotesRequest=} [properties] Properties to set
*/function PrevotesRequest(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* PrevotesRequest to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.PrevotesRequest
* @instance
*/PrevotesRequest.prototype.to=null;/**
* PrevotesRequest height.
* @member {number|Long} height
* @memberof exonum.consensus.PrevotesRequest
* @instance
*/PrevotesRequest.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* PrevotesRequest round.
* @member {number} round
* @memberof exonum.consensus.PrevotesRequest
* @instance
*/PrevotesRequest.prototype.round=0;/**
* PrevotesRequest propose_hash.
* @member {exonum.crypto.IHash|null|undefined} propose_hash
* @memberof exonum.consensus.PrevotesRequest
* @instance
*/PrevotesRequest.prototype.propose_hash=null;/**
* PrevotesRequest validators.
* @member {exonum.common.IBitVec|null|undefined} validators
* @memberof exonum.consensus.PrevotesRequest
* @instance
*/PrevotesRequest.prototype.validators=null;/**
* Creates a new PrevotesRequest instance using the specified properties.
* @function create
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {exonum.consensus.IPrevotesRequest=} [properties] Properties to set
* @returns {exonum.consensus.PrevotesRequest} PrevotesRequest instance
*/PrevotesRequest.create=function create(properties){return new PrevotesRequest(properties);};/**
* Encodes the specified PrevotesRequest message. Does not implicitly {@link exonum.consensus.PrevotesRequest.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {exonum.consensus.IPrevotesRequest} message PrevotesRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PrevotesRequest.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.height);if(message.round!=null&&message.hasOwnProperty("round"))writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.round);if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))$root.exonum.crypto.Hash.encode(message.propose_hash,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();if(message.validators!=null&&message.hasOwnProperty("validators"))$root.exonum.common.BitVec.encode(message.validators,writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();return writer;};/**
* Encodes the specified PrevotesRequest message, length delimited. Does not implicitly {@link exonum.consensus.PrevotesRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {exonum.consensus.IPrevotesRequest} message PrevotesRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PrevotesRequest.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a PrevotesRequest message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.PrevotesRequest} PrevotesRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PrevotesRequest.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.PrevotesRequest();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:message.height=reader.uint64();break;case 3:message.round=reader.uint32();break;case 4:message.propose_hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 5:message.validators=$root.exonum.common.BitVec.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a PrevotesRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.PrevotesRequest} PrevotesRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PrevotesRequest.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a PrevotesRequest message.
* @function verify
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/PrevotesRequest.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";if(message.round!=null&&message.hasOwnProperty("round"))if(!$util.isInteger(message.round))return"round: integer expected";if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash")){var error=$root.exonum.crypto.Hash.verify(message.propose_hash);if(error)return"propose_hash."+error;}if(message.validators!=null&&message.hasOwnProperty("validators")){var error=$root.exonum.common.BitVec.verify(message.validators);if(error)return"validators."+error;}return null;};/**
* Creates a PrevotesRequest message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.PrevotesRequest} PrevotesRequest
*/PrevotesRequest.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.PrevotesRequest)return object;var message=new $root.exonum.consensus.PrevotesRequest();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.PrevotesRequest.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);if(object.round!=null)message.round=object.round>>>0;if(object.propose_hash!=null){if((0,_typeof2["default"])(object.propose_hash)!=="object")throw TypeError(".exonum.consensus.PrevotesRequest.propose_hash: object expected");message.propose_hash=$root.exonum.crypto.Hash.fromObject(object.propose_hash);}if(object.validators!=null){if((0,_typeof2["default"])(object.validators)!=="object")throw TypeError(".exonum.consensus.PrevotesRequest.validators: object expected");message.validators=$root.exonum.common.BitVec.fromObject(object.validators);}return message;};/**
* Creates a plain object from a PrevotesRequest message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.PrevotesRequest
* @static
* @param {exonum.consensus.PrevotesRequest} message PrevotesRequest
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/PrevotesRequest.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.to=null;if($util.Long){var _long10=new $util.Long(0,0,true);object.height=options.longs===String?_long10.toString():options.longs===Number?_long10.toNumber():_long10;}else object.height=options.longs===String?"0":0;object.round=0;object.propose_hash=null;object.validators=null;}if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;if(message.round!=null&&message.hasOwnProperty("round"))object.round=message.round;if(message.propose_hash!=null&&message.hasOwnProperty("propose_hash"))object.propose_hash=$root.exonum.crypto.Hash.toObject(message.propose_hash,options);if(message.validators!=null&&message.hasOwnProperty("validators"))object.validators=$root.exonum.common.BitVec.toObject(message.validators,options);return object;};/**
* Converts this PrevotesRequest to JSON.
* @function toJSON
* @memberof exonum.consensus.PrevotesRequest
* @instance
* @returns {Object.<string,*>} JSON object
*/PrevotesRequest.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return PrevotesRequest;}();consensus.PeersRequest=function(){/**
* Properties of a PeersRequest.
* @memberof exonum.consensus
* @interface IPeersRequest
* @property {exonum.crypto.IPublicKey|null} [to] PeersRequest to
*/ /**
* Constructs a new PeersRequest.
* @memberof exonum.consensus
* @classdesc Represents a PeersRequest.
* @implements IPeersRequest
* @constructor
* @param {exonum.consensus.IPeersRequest=} [properties] Properties to set
*/function PeersRequest(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* PeersRequest to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.PeersRequest
* @instance
*/PeersRequest.prototype.to=null;/**
* Creates a new PeersRequest instance using the specified properties.
* @function create
* @memberof exonum.consensus.PeersRequest
* @static
* @param {exonum.consensus.IPeersRequest=} [properties] Properties to set
* @returns {exonum.consensus.PeersRequest} PeersRequest instance
*/PeersRequest.create=function create(properties){return new PeersRequest(properties);};/**
* Encodes the specified PeersRequest message. Does not implicitly {@link exonum.consensus.PeersRequest.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.PeersRequest
* @static
* @param {exonum.consensus.IPeersRequest} message PeersRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PeersRequest.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();return writer;};/**
* Encodes the specified PeersRequest message, length delimited. Does not implicitly {@link exonum.consensus.PeersRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.PeersRequest
* @static
* @param {exonum.consensus.IPeersRequest} message PeersRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PeersRequest.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a PeersRequest message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.PeersRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.PeersRequest} PeersRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PeersRequest.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.PeersRequest();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a PeersRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.PeersRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.PeersRequest} PeersRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PeersRequest.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a PeersRequest message.
* @function verify
* @memberof exonum.consensus.PeersRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/PeersRequest.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}return null;};/**
* Creates a PeersRequest message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.PeersRequest
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.PeersRequest} PeersRequest
*/PeersRequest.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.PeersRequest)return object;var message=new $root.exonum.consensus.PeersRequest();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.PeersRequest.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}return message;};/**
* Creates a plain object from a PeersRequest message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.PeersRequest
* @static
* @param {exonum.consensus.PeersRequest} message PeersRequest
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/PeersRequest.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults)object.to=null;if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);return object;};/**
* Converts this PeersRequest to JSON.
* @function toJSON
* @memberof exonum.consensus.PeersRequest
* @instance
* @returns {Object.<string,*>} JSON object
*/PeersRequest.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return PeersRequest;}();consensus.BlockRequest=function(){/**
* Properties of a BlockRequest.
* @memberof exonum.consensus
* @interface IBlockRequest
* @property {exonum.crypto.IPublicKey|null} [to] BlockRequest to
* @property {number|Long|null} [height] BlockRequest height
*/ /**
* Constructs a new BlockRequest.
* @memberof exonum.consensus
* @classdesc Represents a BlockRequest.
* @implements IBlockRequest
* @constructor
* @param {exonum.consensus.IBlockRequest=} [properties] Properties to set
*/function BlockRequest(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* BlockRequest to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.BlockRequest
* @instance
*/BlockRequest.prototype.to=null;/**
* BlockRequest height.
* @member {number|Long} height
* @memberof exonum.consensus.BlockRequest
* @instance
*/BlockRequest.prototype.height=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Creates a new BlockRequest instance using the specified properties.
* @function create
* @memberof exonum.consensus.BlockRequest
* @static
* @param {exonum.consensus.IBlockRequest=} [properties] Properties to set
* @returns {exonum.consensus.BlockRequest} BlockRequest instance
*/BlockRequest.create=function create(properties){return new BlockRequest(properties);};/**
* Encodes the specified BlockRequest message. Does not implicitly {@link exonum.consensus.BlockRequest.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.BlockRequest
* @static
* @param {exonum.consensus.IBlockRequest} message BlockRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BlockRequest.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.height);return writer;};/**
* Encodes the specified BlockRequest message, length delimited. Does not implicitly {@link exonum.consensus.BlockRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.BlockRequest
* @static
* @param {exonum.consensus.IBlockRequest} message BlockRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BlockRequest.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a BlockRequest message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.BlockRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.BlockRequest} BlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BlockRequest.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.BlockRequest();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:message.height=reader.uint64();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a BlockRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.BlockRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.BlockRequest} BlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BlockRequest.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a BlockRequest message.
* @function verify
* @memberof exonum.consensus.BlockRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/BlockRequest.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height)&&!(message.height&&$util.isInteger(message.height.low)&&$util.isInteger(message.height.high)))return"height: integer|Long expected";return null;};/**
* Creates a BlockRequest message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.BlockRequest
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.BlockRequest} BlockRequest
*/BlockRequest.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.BlockRequest)return object;var message=new $root.exonum.consensus.BlockRequest();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.BlockRequest.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}if(object.height!=null)if($util.Long)(message.height=$util.Long.fromValue(object.height)).unsigned=true;else if(typeof object.height==="string")message.height=parseInt(object.height,10);else if(typeof object.height==="number")message.height=object.height;else if((0,_typeof2["default"])(object.height)==="object")message.height=new $util.LongBits(object.height.low>>>0,object.height.high>>>0).toNumber(true);return message;};/**
* Creates a plain object from a BlockRequest message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.BlockRequest
* @static
* @param {exonum.consensus.BlockRequest} message BlockRequest
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/BlockRequest.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.to=null;if($util.Long){var _long11=new $util.Long(0,0,true);object.height=options.longs===String?_long11.toString():options.longs===Number?_long11.toNumber():_long11;}else object.height=options.longs===String?"0":0;}if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);if(message.height!=null&&message.hasOwnProperty("height"))if(typeof message.height==="number")object.height=options.longs===String?String(message.height):message.height;else object.height=options.longs===String?$util.Long.prototype.toString.call(message.height):options.longs===Number?new $util.LongBits(message.height.low>>>0,message.height.high>>>0).toNumber(true):message.height;return object;};/**
* Converts this BlockRequest to JSON.
* @function toJSON
* @memberof exonum.consensus.BlockRequest
* @instance
* @returns {Object.<string,*>} JSON object
*/BlockRequest.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return BlockRequest;}();consensus.PoolTransactionsRequest=function(){/**
* Properties of a PoolTransactionsRequest.
* @memberof exonum.consensus
* @interface IPoolTransactionsRequest
* @property {exonum.crypto.IPublicKey|null} [to] PoolTransactionsRequest to
*/ /**
* Constructs a new PoolTransactionsRequest.
* @memberof exonum.consensus
* @classdesc Represents a PoolTransactionsRequest.
* @implements IPoolTransactionsRequest
* @constructor
* @param {exonum.consensus.IPoolTransactionsRequest=} [properties] Properties to set
*/function PoolTransactionsRequest(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* PoolTransactionsRequest to.
* @member {exonum.crypto.IPublicKey|null|undefined} to
* @memberof exonum.consensus.PoolTransactionsRequest
* @instance
*/PoolTransactionsRequest.prototype.to=null;/**
* Creates a new PoolTransactionsRequest instance using the specified properties.
* @function create
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {exonum.consensus.IPoolTransactionsRequest=} [properties] Properties to set
* @returns {exonum.consensus.PoolTransactionsRequest} PoolTransactionsRequest instance
*/PoolTransactionsRequest.create=function create(properties){return new PoolTransactionsRequest(properties);};/**
* Encodes the specified PoolTransactionsRequest message. Does not implicitly {@link exonum.consensus.PoolTransactionsRequest.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {exonum.consensus.IPoolTransactionsRequest} message PoolTransactionsRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PoolTransactionsRequest.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.to!=null&&message.hasOwnProperty("to"))$root.exonum.crypto.PublicKey.encode(message.to,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();return writer;};/**
* Encodes the specified PoolTransactionsRequest message, length delimited. Does not implicitly {@link exonum.consensus.PoolTransactionsRequest.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {exonum.consensus.IPoolTransactionsRequest} message PoolTransactionsRequest message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/PoolTransactionsRequest.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a PoolTransactionsRequest message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.PoolTransactionsRequest} PoolTransactionsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PoolTransactionsRequest.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.PoolTransactionsRequest();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.to=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a PoolTransactionsRequest message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.PoolTransactionsRequest} PoolTransactionsRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/PoolTransactionsRequest.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a PoolTransactionsRequest message.
* @function verify
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/PoolTransactionsRequest.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.to!=null&&message.hasOwnProperty("to")){var error=$root.exonum.crypto.PublicKey.verify(message.to);if(error)return"to."+error;}return null;};/**
* Creates a PoolTransactionsRequest message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.PoolTransactionsRequest} PoolTransactionsRequest
*/PoolTransactionsRequest.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.PoolTransactionsRequest)return object;var message=new $root.exonum.consensus.PoolTransactionsRequest();if(object.to!=null){if((0,_typeof2["default"])(object.to)!=="object")throw TypeError(".exonum.consensus.PoolTransactionsRequest.to: object expected");message.to=$root.exonum.crypto.PublicKey.fromObject(object.to);}return message;};/**
* Creates a plain object from a PoolTransactionsRequest message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.PoolTransactionsRequest
* @static
* @param {exonum.consensus.PoolTransactionsRequest} message PoolTransactionsRequest
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/PoolTransactionsRequest.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults)object.to=null;if(message.to!=null&&message.hasOwnProperty("to"))object.to=$root.exonum.crypto.PublicKey.toObject(message.to,options);return object;};/**
* Converts this PoolTransactionsRequest to JSON.
* @function toJSON
* @memberof exonum.consensus.PoolTransactionsRequest
* @instance
* @returns {Object.<string,*>} JSON object
*/PoolTransactionsRequest.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return PoolTransactionsRequest;}();consensus.ExonumMessage=function(){/**
* Properties of an ExonumMessage.
* @memberof exonum.consensus
* @interface IExonumMessage
* @property {exonum.runtime.IAnyTx|null} [any_tx] ExonumMessage any_tx
* @property {exonum.consensus.IConnect|null} [connect] ExonumMessage connect
* @property {exonum.consensus.IStatus|null} [status] ExonumMessage status
* @property {exonum.consensus.IPrecommit|null} [precommit] ExonumMessage precommit
* @property {exonum.consensus.IPropose|null} [propose] ExonumMessage propose
* @property {exonum.consensus.IPrevote|null} [prevote] ExonumMessage prevote
* @property {exonum.consensus.ITransactionsResponse|null} [transactions_response] ExonumMessage transactions_response
* @property {exonum.consensus.IBlockResponse|null} [block_response] ExonumMessage block_response
* @property {exonum.consensus.IProposeRequest|null} [propose_request] ExonumMessage propose_request
* @property {exonum.consensus.ITransactionsRequest|null} [transactions_request] ExonumMessage transactions_request
* @property {exonum.consensus.IPrevotesRequest|null} [prevotes_request] ExonumMessage prevotes_request
* @property {exonum.consensus.IPeersRequest|null} [peers_request] ExonumMessage peers_request
* @property {exonum.consensus.IBlockRequest|null} [block_request] ExonumMessage block_request
* @property {exonum.consensus.IPoolTransactionsRequest|null} [pool_transactions_request] ExonumMessage pool_transactions_request
*/ /**
* Constructs a new ExonumMessage.
* @memberof exonum.consensus
* @classdesc Represents an ExonumMessage.
* @implements IExonumMessage
* @constructor
* @param {exonum.consensus.IExonumMessage=} [properties] Properties to set
*/function ExonumMessage(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ExonumMessage any_tx.
* @member {exonum.runtime.IAnyTx|null|undefined} any_tx
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.any_tx=null;/**
* ExonumMessage connect.
* @member {exonum.consensus.IConnect|null|undefined} connect
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.connect=null;/**
* ExonumMessage status.
* @member {exonum.consensus.IStatus|null|undefined} status
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.status=null;/**
* ExonumMessage precommit.
* @member {exonum.consensus.IPrecommit|null|undefined} precommit
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.precommit=null;/**
* ExonumMessage propose.
* @member {exonum.consensus.IPropose|null|undefined} propose
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.propose=null;/**
* ExonumMessage prevote.
* @member {exonum.consensus.IPrevote|null|undefined} prevote
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.prevote=null;/**
* ExonumMessage transactions_response.
* @member {exonum.consensus.ITransactionsResponse|null|undefined} transactions_response
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.transactions_response=null;/**
* ExonumMessage block_response.
* @member {exonum.consensus.IBlockResponse|null|undefined} block_response
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.block_response=null;/**
* ExonumMessage propose_request.
* @member {exonum.consensus.IProposeRequest|null|undefined} propose_request
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.propose_request=null;/**
* ExonumMessage transactions_request.
* @member {exonum.consensus.ITransactionsRequest|null|undefined} transactions_request
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.transactions_request=null;/**
* ExonumMessage prevotes_request.
* @member {exonum.consensus.IPrevotesRequest|null|undefined} prevotes_request
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.prevotes_request=null;/**
* ExonumMessage peers_request.
* @member {exonum.consensus.IPeersRequest|null|undefined} peers_request
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.peers_request=null;/**
* ExonumMessage block_request.
* @member {exonum.consensus.IBlockRequest|null|undefined} block_request
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.block_request=null;/**
* ExonumMessage pool_transactions_request.
* @member {exonum.consensus.IPoolTransactionsRequest|null|undefined} pool_transactions_request
* @memberof exonum.consensus.ExonumMessage
* @instance
*/ExonumMessage.prototype.pool_transactions_request=null;// OneOf field names bound to virtual getters and setters
var $oneOfFields;/**
* ExonumMessage kind.
* @member {"any_tx"|"connect"|"status"|"precommit"|"propose"|"prevote"|"transactions_response"|"block_response"|"propose_request"|"transactions_request"|"prevotes_request"|"peers_request"|"block_request"|"pool_transactions_request"|undefined} kind
* @memberof exonum.consensus.ExonumMessage
* @instance
*/Object.defineProperty(ExonumMessage.prototype,"kind",{get:$util.oneOfGetter($oneOfFields=["any_tx","connect","status","precommit","propose","prevote","transactions_response","block_response","propose_request","transactions_request","prevotes_request","peers_request","block_request","pool_transactions_request"]),set:$util.oneOfSetter($oneOfFields)});/**
* Creates a new ExonumMessage instance using the specified properties.
* @function create
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {exonum.consensus.IExonumMessage=} [properties] Properties to set
* @returns {exonum.consensus.ExonumMessage} ExonumMessage instance
*/ExonumMessage.create=function create(properties){return new ExonumMessage(properties);};/**
* Encodes the specified ExonumMessage message. Does not implicitly {@link exonum.consensus.ExonumMessage.verify|verify} messages.
* @function encode
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {exonum.consensus.IExonumMessage} message ExonumMessage message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ExonumMessage.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.any_tx!=null&&message.hasOwnProperty("any_tx"))$root.exonum.runtime.AnyTx.encode(message.any_tx,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.connect!=null&&message.hasOwnProperty("connect"))$root.exonum.consensus.Connect.encode(message.connect,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();if(message.status!=null&&message.hasOwnProperty("status"))$root.exonum.consensus.Status.encode(message.status,writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();if(message.precommit!=null&&message.hasOwnProperty("precommit"))$root.exonum.consensus.Precommit.encode(message.precommit,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();if(message.propose!=null&&message.hasOwnProperty("propose"))$root.exonum.consensus.Propose.encode(message.propose,writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim();if(message.prevote!=null&&message.hasOwnProperty("prevote"))$root.exonum.consensus.Prevote.encode(message.prevote,writer.uint32(/* id 6, wireType 2 =*/50).fork()).ldelim();if(message.transactions_response!=null&&message.hasOwnProperty("transactions_response"))$root.exonum.consensus.TransactionsResponse.encode(message.transactions_response,writer.uint32(/* id 7, wireType 2 =*/58).fork()).ldelim();if(message.block_response!=null&&message.hasOwnProperty("block_response"))$root.exonum.consensus.BlockResponse.encode(message.block_response,writer.uint32(/* id 8, wireType 2 =*/66).fork()).ldelim();if(message.propose_request!=null&&message.hasOwnProperty("propose_request"))$root.exonum.consensus.ProposeRequest.encode(message.propose_request,writer.uint32(/* id 9, wireType 2 =*/74).fork()).ldelim();if(message.transactions_request!=null&&message.hasOwnProperty("transactions_request"))$root.exonum.consensus.TransactionsRequest.encode(message.transactions_request,writer.uint32(/* id 10, wireType 2 =*/82).fork()).ldelim();if(message.prevotes_request!=null&&message.hasOwnProperty("prevotes_request"))$root.exonum.consensus.PrevotesRequest.encode(message.prevotes_request,writer.uint32(/* id 11, wireType 2 =*/90).fork()).ldelim();if(message.peers_request!=null&&message.hasOwnProperty("peers_request"))$root.exonum.consensus.PeersRequest.encode(message.peers_request,writer.uint32(/* id 12, wireType 2 =*/98).fork()).ldelim();if(message.block_request!=null&&message.hasOwnProperty("block_request"))$root.exonum.consensus.BlockRequest.encode(message.block_request,writer.uint32(/* id 13, wireType 2 =*/106).fork()).ldelim();if(message.pool_transactions_request!=null&&message.hasOwnProperty("pool_transactions_request"))$root.exonum.consensus.PoolTransactionsRequest.encode(message.pool_transactions_request,writer.uint32(/* id 14, wireType 2 =*/114).fork()).ldelim();return writer;};/**
* Encodes the specified ExonumMessage message, length delimited. Does not implicitly {@link exonum.consensus.ExonumMessage.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {exonum.consensus.IExonumMessage} message ExonumMessage message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ExonumMessage.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an ExonumMessage message from the specified reader or buffer.
* @function decode
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.consensus.ExonumMessage} ExonumMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ExonumMessage.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.consensus.ExonumMessage();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.any_tx=$root.exonum.runtime.AnyTx.decode(reader,reader.uint32());break;case 2:message.connect=$root.exonum.consensus.Connect.decode(reader,reader.uint32());break;case 3:message.status=$root.exonum.consensus.Status.decode(reader,reader.uint32());break;case 4:message.precommit=$root.exonum.consensus.Precommit.decode(reader,reader.uint32());break;case 5:message.propose=$root.exonum.consensus.Propose.decode(reader,reader.uint32());break;case 6:message.prevote=$root.exonum.consensus.Prevote.decode(reader,reader.uint32());break;case 7:message.transactions_response=$root.exonum.consensus.TransactionsResponse.decode(reader,reader.uint32());break;case 8:message.block_response=$root.exonum.consensus.BlockResponse.decode(reader,reader.uint32());break;case 9:message.propose_request=$root.exonum.consensus.ProposeRequest.decode(reader,reader.uint32());break;case 10:message.transactions_request=$root.exonum.consensus.TransactionsRequest.decode(reader,reader.uint32());break;case 11:message.prevotes_request=$root.exonum.consensus.PrevotesRequest.decode(reader,reader.uint32());break;case 12:message.peers_request=$root.exonum.consensus.PeersRequest.decode(reader,reader.uint32());break;case 13:message.block_request=$root.exonum.consensus.BlockRequest.decode(reader,reader.uint32());break;case 14:message.pool_transactions_request=$root.exonum.consensus.PoolTransactionsRequest.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an ExonumMessage message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.consensus.ExonumMessage} ExonumMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ExonumMessage.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an ExonumMessage message.
* @function verify
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ExonumMessage.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";var properties={};if(message.any_tx!=null&&message.hasOwnProperty("any_tx")){properties.kind=1;{var error=$root.exonum.runtime.AnyTx.verify(message.any_tx);if(error)return"any_tx."+error;}}if(message.connect!=null&&message.hasOwnProperty("connect")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.Connect.verify(message.connect);if(error)return"connect."+error;}}if(message.status!=null&&message.hasOwnProperty("status")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.Status.verify(message.status);if(error)return"status."+error;}}if(message.precommit!=null&&message.hasOwnProperty("precommit")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.Precommit.verify(message.precommit);if(error)return"precommit."+error;}}if(message.propose!=null&&message.hasOwnProperty("propose")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.Propose.verify(message.propose);if(error)return"propose."+error;}}if(message.prevote!=null&&message.hasOwnProperty("prevote")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.Prevote.verify(message.prevote);if(error)return"prevote."+error;}}if(message.transactions_response!=null&&message.hasOwnProperty("transactions_response")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.TransactionsResponse.verify(message.transactions_response);if(error)return"transactions_response."+error;}}if(message.block_response!=null&&message.hasOwnProperty("block_response")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.BlockResponse.verify(message.block_response);if(error)return"block_response."+error;}}if(message.propose_request!=null&&message.hasOwnProperty("propose_request")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.ProposeRequest.verify(message.propose_request);if(error)return"propose_request."+error;}}if(message.transactions_request!=null&&message.hasOwnProperty("transactions_request")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.TransactionsRequest.verify(message.transactions_request);if(error)return"transactions_request."+error;}}if(message.prevotes_request!=null&&message.hasOwnProperty("prevotes_request")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.PrevotesRequest.verify(message.prevotes_request);if(error)return"prevotes_request."+error;}}if(message.peers_request!=null&&message.hasOwnProperty("peers_request")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.PeersRequest.verify(message.peers_request);if(error)return"peers_request."+error;}}if(message.block_request!=null&&message.hasOwnProperty("block_request")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.BlockRequest.verify(message.block_request);if(error)return"block_request."+error;}}if(message.pool_transactions_request!=null&&message.hasOwnProperty("pool_transactions_request")){if(properties.kind===1)return"kind: multiple values";properties.kind=1;{var error=$root.exonum.consensus.PoolTransactionsRequest.verify(message.pool_transactions_request);if(error)return"pool_transactions_request."+error;}}return null;};/**
* Creates an ExonumMessage message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.consensus.ExonumMessage} ExonumMessage
*/ExonumMessage.fromObject=function fromObject(object){if(object instanceof $root.exonum.consensus.ExonumMessage)return object;var message=new $root.exonum.consensus.ExonumMessage();if(object.any_tx!=null){if((0,_typeof2["default"])(object.any_tx)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.any_tx: object expected");message.any_tx=$root.exonum.runtime.AnyTx.fromObject(object.any_tx);}if(object.connect!=null){if((0,_typeof2["default"])(object.connect)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.connect: object expected");message.connect=$root.exonum.consensus.Connect.fromObject(object.connect);}if(object.status!=null){if((0,_typeof2["default"])(object.status)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.status: object expected");message.status=$root.exonum.consensus.Status.fromObject(object.status);}if(object.precommit!=null){if((0,_typeof2["default"])(object.precommit)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.precommit: object expected");message.precommit=$root.exonum.consensus.Precommit.fromObject(object.precommit);}if(object.propose!=null){if((0,_typeof2["default"])(object.propose)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.propose: object expected");message.propose=$root.exonum.consensus.Propose.fromObject(object.propose);}if(object.prevote!=null){if((0,_typeof2["default"])(object.prevote)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.prevote: object expected");message.prevote=$root.exonum.consensus.Prevote.fromObject(object.prevote);}if(object.transactions_response!=null){if((0,_typeof2["default"])(object.transactions_response)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.transactions_response: object expected");message.transactions_response=$root.exonum.consensus.TransactionsResponse.fromObject(object.transactions_response);}if(object.block_response!=null){if((0,_typeof2["default"])(object.block_response)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.block_response: object expected");message.block_response=$root.exonum.consensus.BlockResponse.fromObject(object.block_response);}if(object.propose_request!=null){if((0,_typeof2["default"])(object.propose_request)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.propose_request: object expected");message.propose_request=$root.exonum.consensus.ProposeRequest.fromObject(object.propose_request);}if(object.transactions_request!=null){if((0,_typeof2["default"])(object.transactions_request)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.transactions_request: object expected");message.transactions_request=$root.exonum.consensus.TransactionsRequest.fromObject(object.transactions_request);}if(object.prevotes_request!=null){if((0,_typeof2["default"])(object.prevotes_request)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.prevotes_request: object expected");message.prevotes_request=$root.exonum.consensus.PrevotesRequest.fromObject(object.prevotes_request);}if(object.peers_request!=null){if((0,_typeof2["default"])(object.peers_request)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.peers_request: object expected");message.peers_request=$root.exonum.consensus.PeersRequest.fromObject(object.peers_request);}if(object.block_request!=null){if((0,_typeof2["default"])(object.block_request)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.block_request: object expected");message.block_request=$root.exonum.consensus.BlockRequest.fromObject(object.block_request);}if(object.pool_transactions_request!=null){if((0,_typeof2["default"])(object.pool_transactions_request)!=="object")throw TypeError(".exonum.consensus.ExonumMessage.pool_transactions_request: object expected");message.pool_transactions_request=$root.exonum.consensus.PoolTransactionsRequest.fromObject(object.pool_transactions_request);}return message;};/**
* Creates a plain object from an ExonumMessage message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.consensus.ExonumMessage
* @static
* @param {exonum.consensus.ExonumMessage} message ExonumMessage
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ExonumMessage.toObject=function toObject(message,options){if(!options)options={};var object={};if(message.any_tx!=null&&message.hasOwnProperty("any_tx")){object.any_tx=$root.exonum.runtime.AnyTx.toObject(message.any_tx,options);if(options.oneofs)object.kind="any_tx";}if(message.connect!=null&&message.hasOwnProperty("connect")){object.connect=$root.exonum.consensus.Connect.toObject(message.connect,options);if(options.oneofs)object.kind="connect";}if(message.status!=null&&message.hasOwnProperty("status")){object.status=$root.exonum.consensus.Status.toObject(message.status,options);if(options.oneofs)object.kind="status";}if(message.precommit!=null&&message.hasOwnProperty("precommit")){object.precommit=$root.exonum.consensus.Precommit.toObject(message.precommit,options);if(options.oneofs)object.kind="precommit";}if(message.propose!=null&&message.hasOwnProperty("propose")){object.propose=$root.exonum.consensus.Propose.toObject(message.propose,options);if(options.oneofs)object.kind="propose";}if(message.prevote!=null&&message.hasOwnProperty("prevote")){object.prevote=$root.exonum.consensus.Prevote.toObject(message.prevote,options);if(options.oneofs)object.kind="prevote";}if(message.transactions_response!=null&&message.hasOwnProperty("transactions_response")){object.transactions_response=$root.exonum.consensus.TransactionsResponse.toObject(message.transactions_response,options);if(options.oneofs)object.kind="transactions_response";}if(message.block_response!=null&&message.hasOwnProperty("block_response")){object.block_response=$root.exonum.consensus.BlockResponse.toObject(message.block_response,options);if(options.oneofs)object.kind="block_response";}if(message.propose_request!=null&&message.hasOwnProperty("propose_request")){object.propose_request=$root.exonum.consensus.ProposeRequest.toObject(message.propose_request,options);if(options.oneofs)object.kind="propose_request";}if(message.transactions_request!=null&&message.hasOwnProperty("transactions_request")){object.transactions_request=$root.exonum.consensus.TransactionsRequest.toObject(message.transactions_request,options);if(options.oneofs)object.kind="transactions_request";}if(message.prevotes_request!=null&&message.hasOwnProperty("prevotes_request")){object.prevotes_request=$root.exonum.consensus.PrevotesRequest.toObject(message.prevotes_request,options);if(options.oneofs)object.kind="prevotes_request";}if(message.peers_request!=null&&message.hasOwnProperty("peers_request")){object.peers_request=$root.exonum.consensus.PeersRequest.toObject(message.peers_request,options);if(options.oneofs)object.kind="peers_request";}if(message.block_request!=null&&message.hasOwnProperty("block_request")){object.block_request=$root.exonum.consensus.BlockRequest.toObject(message.block_request,options);if(options.oneofs)object.kind="block_request";}if(message.pool_transactions_request!=null&&message.hasOwnProperty("pool_transactions_request")){object.pool_transactions_request=$root.exonum.consensus.PoolTransactionsRequest.toObject(message.pool_transactions_request,options);if(options.oneofs)object.kind="pool_transactions_request";}return object;};/**
* Converts this ExonumMessage to JSON.
* @function toJSON
* @memberof exonum.consensus.ExonumMessage
* @instance
* @returns {Object.<string,*>} JSON object
*/ExonumMessage.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ExonumMessage;}();return consensus;}();exonum.common=function(){/**
* Namespace common.
* @memberof exonum
* @namespace
*/var common={};common.BitVec=function(){/**
* Properties of a BitVec.
* @memberof exonum.common
* @interface IBitVec
* @property {Uint8Array|null} [data] BitVec data
* @property {number|Long|null} [len] BitVec len
*/ /**
* Constructs a new BitVec.
* @memberof exonum.common
* @classdesc Represents a BitVec.
* @implements IBitVec
* @constructor
* @param {exonum.common.IBitVec=} [properties] Properties to set
*/function BitVec(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* BitVec data.
* @member {Uint8Array} data
* @memberof exonum.common.BitVec
* @instance
*/BitVec.prototype.data=$util.newBuffer([]);/**
* BitVec len.
* @member {number|Long} len
* @memberof exonum.common.BitVec
* @instance
*/BitVec.prototype.len=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Creates a new BitVec instance using the specified properties.
* @function create
* @memberof exonum.common.BitVec
* @static
* @param {exonum.common.IBitVec=} [properties] Properties to set
* @returns {exonum.common.BitVec} BitVec instance
*/BitVec.create=function create(properties){return new BitVec(properties);};/**
* Encodes the specified BitVec message. Does not implicitly {@link exonum.common.BitVec.verify|verify} messages.
* @function encode
* @memberof exonum.common.BitVec
* @static
* @param {exonum.common.IBitVec} message BitVec message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BitVec.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.data!=null&&message.hasOwnProperty("data"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.data);if(message.len!=null&&message.hasOwnProperty("len"))writer.uint32(/* id 2, wireType 0 =*/16).uint64(message.len);return writer;};/**
* Encodes the specified BitVec message, length delimited. Does not implicitly {@link exonum.common.BitVec.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.common.BitVec
* @static
* @param {exonum.common.IBitVec} message BitVec message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BitVec.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a BitVec message from the specified reader or buffer.
* @function decode
* @memberof exonum.common.BitVec
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.common.BitVec} BitVec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BitVec.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.common.BitVec();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.data=reader.bytes();break;case 2:message.len=reader.uint64();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a BitVec message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.common.BitVec
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.common.BitVec} BitVec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BitVec.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a BitVec message.
* @function verify
* @memberof exonum.common.BitVec
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/BitVec.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.data!=null&&message.hasOwnProperty("data"))if(!(message.data&&typeof message.data.length==="number"||$util.isString(message.data)))return"data: buffer expected";if(message.len!=null&&message.hasOwnProperty("len"))if(!$util.isInteger(message.len)&&!(message.len&&$util.isInteger(message.len.low)&&$util.isInteger(message.len.high)))return"len: integer|Long expected";return null;};/**
* Creates a BitVec message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.common.BitVec
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.common.BitVec} BitVec
*/BitVec.fromObject=function fromObject(object){if(object instanceof $root.exonum.common.BitVec)return object;var message=new $root.exonum.common.BitVec();if(object.data!=null)if(typeof object.data==="string")$util.base64.decode(object.data,message.data=$util.newBuffer($util.base64.length(object.data)),0);else if(object.data.length)message.data=object.data;if(object.len!=null)if($util.Long)(message.len=$util.Long.fromValue(object.len)).unsigned=true;else if(typeof object.len==="string")message.len=parseInt(object.len,10);else if(typeof object.len==="number")message.len=object.len;else if((0,_typeof2["default"])(object.len)==="object")message.len=new $util.LongBits(object.len.low>>>0,object.len.high>>>0).toNumber(true);return message;};/**
* Creates a plain object from a BitVec message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.common.BitVec
* @static
* @param {exonum.common.BitVec} message BitVec
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/BitVec.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if(options.bytes===String)object.data="";else{object.data=[];if(options.bytes!==Array)object.data=$util.newBuffer(object.data);}if($util.Long){var _long12=new $util.Long(0,0,true);object.len=options.longs===String?_long12.toString():options.longs===Number?_long12.toNumber():_long12;}else object.len=options.longs===String?"0":0;}if(message.data!=null&&message.hasOwnProperty("data"))object.data=options.bytes===String?$util.base64.encode(message.data,0,message.data.length):options.bytes===Array?Array.prototype.slice.call(message.data):message.data;if(message.len!=null&&message.hasOwnProperty("len"))if(typeof message.len==="number")object.len=options.longs===String?String(message.len):message.len;else object.len=options.longs===String?$util.Long.prototype.toString.call(message.len):options.longs===Number?new $util.LongBits(message.len.low>>>0,message.len.high>>>0).toNumber(true):message.len;return object;};/**
* Converts this BitVec to JSON.
* @function toJSON
* @memberof exonum.common.BitVec
* @instance
* @returns {Object.<string,*>} JSON object
*/BitVec.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return BitVec;}();return common;}();exonum.runtime=function(){/**
* Namespace runtime.
* @memberof exonum
* @namespace
*/var runtime={};runtime.CallInfo=function(){/**
* Properties of a CallInfo.
* @memberof exonum.runtime
* @interface ICallInfo
* @property {number|null} [instance_id] CallInfo instance_id
* @property {number|null} [method_id] CallInfo method_id
*/ /**
* Constructs a new CallInfo.
* @memberof exonum.runtime
* @classdesc Represents a CallInfo.
* @implements ICallInfo
* @constructor
* @param {exonum.runtime.ICallInfo=} [properties] Properties to set
*/function CallInfo(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* CallInfo instance_id.
* @member {number} instance_id
* @memberof exonum.runtime.CallInfo
* @instance
*/CallInfo.prototype.instance_id=0;/**
* CallInfo method_id.
* @member {number} method_id
* @memberof exonum.runtime.CallInfo
* @instance
*/CallInfo.prototype.method_id=0;/**
* Creates a new CallInfo instance using the specified properties.
* @function create
* @memberof exonum.runtime.CallInfo
* @static
* @param {exonum.runtime.ICallInfo=} [properties] Properties to set
* @returns {exonum.runtime.CallInfo} CallInfo instance
*/CallInfo.create=function create(properties){return new CallInfo(properties);};/**
* Encodes the specified CallInfo message. Does not implicitly {@link exonum.runtime.CallInfo.verify|verify} messages.
* @function encode
* @memberof exonum.runtime.CallInfo
* @static
* @param {exonum.runtime.ICallInfo} message CallInfo message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/CallInfo.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.instance_id!=null&&message.hasOwnProperty("instance_id"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.instance_id);if(message.method_id!=null&&message.hasOwnProperty("method_id"))writer.uint32(/* id 2, wireType 0 =*/16).uint32(message.method_id);return writer;};/**
* Encodes the specified CallInfo message, length delimited. Does not implicitly {@link exonum.runtime.CallInfo.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.runtime.CallInfo
* @static
* @param {exonum.runtime.ICallInfo} message CallInfo message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/CallInfo.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a CallInfo message from the specified reader or buffer.
* @function decode
* @memberof exonum.runtime.CallInfo
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.runtime.CallInfo} CallInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/CallInfo.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.runtime.CallInfo();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.instance_id=reader.uint32();break;case 2:message.method_id=reader.uint32();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a CallInfo message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.runtime.CallInfo
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.runtime.CallInfo} CallInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/CallInfo.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a CallInfo message.
* @function verify
* @memberof exonum.runtime.CallInfo
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/CallInfo.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.instance_id!=null&&message.hasOwnProperty("instance_id"))if(!$util.isInteger(message.instance_id))return"instance_id: integer expected";if(message.method_id!=null&&message.hasOwnProperty("method_id"))if(!$util.isInteger(message.method_id))return"method_id: integer expected";return null;};/**
* Creates a CallInfo message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.runtime.CallInfo
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.runtime.CallInfo} CallInfo
*/CallInfo.fromObject=function fromObject(object){if(object instanceof $root.exonum.runtime.CallInfo)return object;var message=new $root.exonum.runtime.CallInfo();if(object.instance_id!=null)message.instance_id=object.instance_id>>>0;if(object.method_id!=null)message.method_id=object.method_id>>>0;return message;};/**
* Creates a plain object from a CallInfo message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.runtime.CallInfo
* @static
* @param {exonum.runtime.CallInfo} message CallInfo
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/CallInfo.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.instance_id=0;object.method_id=0;}if(message.instance_id!=null&&message.hasOwnProperty("instance_id"))object.instance_id=message.instance_id;if(message.method_id!=null&&message.hasOwnProperty("method_id"))object.method_id=message.method_id;return object;};/**
* Converts this CallInfo to JSON.
* @function toJSON
* @memberof exonum.runtime.CallInfo
* @instance
* @returns {Object.<string,*>} JSON object
*/CallInfo.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return CallInfo;}();runtime.AnyTx=function(){/**
* Properties of an AnyTx.
* @memberof exonum.runtime
* @interface IAnyTx
* @property {exonum.runtime.ICallInfo|null} [call_info] AnyTx call_info
* @property {Uint8Array|null} ["arguments"] AnyTx arguments
*/ /**
* Constructs a new AnyTx.
* @memberof exonum.runtime
* @classdesc Represents an AnyTx.
* @implements IAnyTx
* @constructor
* @param {exonum.runtime.IAnyTx=} [properties] Properties to set
*/function AnyTx(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* AnyTx call_info.
* @member {exonum.runtime.ICallInfo|null|undefined} call_info
* @memberof exonum.runtime.AnyTx
* @instance
*/AnyTx.prototype.call_info=null;/**
* AnyTx arguments.
* @member {Uint8Array} arguments
* @memberof exonum.runtime.AnyTx
* @instance
*/AnyTx.prototype["arguments"]=$util.newBuffer([]);/**
* Creates a new AnyTx instance using the specified properties.
* @function create
* @memberof exonum.runtime.AnyTx
* @static
* @param {exonum.runtime.IAnyTx=} [properties] Properties to set
* @returns {exonum.runtime.AnyTx} AnyTx instance
*/AnyTx.create=function create(properties){return new AnyTx(properties);};/**
* Encodes the specified AnyTx message. Does not implicitly {@link exonum.runtime.AnyTx.verify|verify} messages.
* @function encode
* @memberof exonum.runtime.AnyTx
* @static
* @param {exonum.runtime.IAnyTx} message AnyTx message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/AnyTx.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.call_info!=null&&message.hasOwnProperty("call_info"))$root.exonum.runtime.CallInfo.encode(message.call_info,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message["arguments"]!=null&&message.hasOwnProperty("arguments"))writer.uint32(/* id 2, wireType 2 =*/18).bytes(message["arguments"]);return writer;};/**
* Encodes the specified AnyTx message, length delimited. Does not implicitly {@link exonum.runtime.AnyTx.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.runtime.AnyTx
* @static
* @param {exonum.runtime.IAnyTx} message AnyTx message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/AnyTx.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an AnyTx message from the specified reader or buffer.
* @function decode
* @memberof exonum.runtime.AnyTx
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.runtime.AnyTx} AnyTx
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/AnyTx.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.runtime.AnyTx();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.call_info=$root.exonum.runtime.CallInfo.decode(reader,reader.uint32());break;case 2:message["arguments"]=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an AnyTx message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.runtime.AnyTx
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.runtime.AnyTx} AnyTx
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/AnyTx.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an AnyTx message.
* @function verify
* @memberof exonum.runtime.AnyTx
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/AnyTx.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.call_info!=null&&message.hasOwnProperty("call_info")){var error=$root.exonum.runtime.CallInfo.verify(message.call_info);if(error)return"call_info."+error;}if(message["arguments"]!=null&&message.hasOwnProperty("arguments"))if(!(message["arguments"]&&typeof message["arguments"].length==="number"||$util.isString(message["arguments"])))return"arguments: buffer expected";return null;};/**
* Creates an AnyTx message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.runtime.AnyTx
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.runtime.AnyTx} AnyTx
*/AnyTx.fromObject=function fromObject(object){if(object instanceof $root.exonum.runtime.AnyTx)return object;var message=new $root.exonum.runtime.AnyTx();if(object.call_info!=null){if((0,_typeof2["default"])(object.call_info)!=="object")throw TypeError(".exonum.runtime.AnyTx.call_info: object expected");message.call_info=$root.exonum.runtime.CallInfo.fromObject(object.call_info);}if(object["arguments"]!=null)if(typeof object["arguments"]==="string")$util.base64.decode(object["arguments"],message["arguments"]=$util.newBuffer($util.base64.length(object["arguments"])),0);else if(object["arguments"].length)message["arguments"]=object["arguments"];return message;};/**
* Creates a plain object from an AnyTx message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.runtime.AnyTx
* @static
* @param {exonum.runtime.AnyTx} message AnyTx
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/AnyTx.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.call_info=null;if(options.bytes===String)object["arguments"]="";else{object["arguments"]=[];if(options.bytes!==Array)object["arguments"]=$util.newBuffer(object["arguments"]);}}if(message.call_info!=null&&message.hasOwnProperty("call_info"))object.call_info=$root.exonum.runtime.CallInfo.toObject(message.call_info,options);if(message["arguments"]!=null&&message.hasOwnProperty("arguments"))object["arguments"]=options.bytes===String?$util.base64.encode(message["arguments"],0,message["arguments"].length):options.bytes===Array?Array.prototype.slice.call(message["arguments"]):message["arguments"];return object;};/**
* Converts this AnyTx to JSON.
* @function toJSON
* @memberof exonum.runtime.AnyTx
* @instance
* @returns {Object.<string,*>} JSON object
*/AnyTx.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return AnyTx;}();runtime.ArtifactId=function(){/**
* Properties of an ArtifactId.
* @memberof exonum.runtime
* @interface IArtifactId
* @property {number|null} [runtime_id] ArtifactId runtime_id
* @property {string|null} [name] ArtifactId name
*/ /**
* Constructs a new ArtifactId.
* @memberof exonum.runtime
* @classdesc Represents an ArtifactId.
* @implements IArtifactId
* @constructor
* @param {exonum.runtime.IArtifactId=} [properties] Properties to set
*/function ArtifactId(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ArtifactId runtime_id.
* @member {number} runtime_id
* @memberof exonum.runtime.ArtifactId
* @instance
*/ArtifactId.prototype.runtime_id=0;/**
* ArtifactId name.
* @member {string} name
* @memberof exonum.runtime.ArtifactId
* @instance
*/ArtifactId.prototype.name="";/**
* Creates a new ArtifactId instance using the specified properties.
* @function create
* @memberof exonum.runtime.ArtifactId
* @static
* @param {exonum.runtime.IArtifactId=} [properties] Properties to set
* @returns {exonum.runtime.ArtifactId} ArtifactId instance
*/ArtifactId.create=function create(properties){return new ArtifactId(properties);};/**
* Encodes the specified ArtifactId message. Does not implicitly {@link exonum.runtime.ArtifactId.verify|verify} messages.
* @function encode
* @memberof exonum.runtime.ArtifactId
* @static
* @param {exonum.runtime.IArtifactId} message ArtifactId message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ArtifactId.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.runtime_id!=null&&message.hasOwnProperty("runtime_id"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.runtime_id);if(message.name!=null&&message.hasOwnProperty("name"))writer.uint32(/* id 2, wireType 2 =*/18).string(message.name);return writer;};/**
* Encodes the specified ArtifactId message, length delimited. Does not implicitly {@link exonum.runtime.ArtifactId.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.runtime.ArtifactId
* @static
* @param {exonum.runtime.IArtifactId} message ArtifactId message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ArtifactId.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an ArtifactId message from the specified reader or buffer.
* @function decode
* @memberof exonum.runtime.ArtifactId
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.runtime.ArtifactId} ArtifactId
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ArtifactId.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.runtime.ArtifactId();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.runtime_id=reader.uint32();break;case 2:message.name=reader.string();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an ArtifactId message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.runtime.ArtifactId
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.runtime.ArtifactId} ArtifactId
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ArtifactId.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an ArtifactId message.
* @function verify
* @memberof exonum.runtime.ArtifactId
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ArtifactId.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.runtime_id!=null&&message.hasOwnProperty("runtime_id"))if(!$util.isInteger(message.runtime_id))return"runtime_id: integer expected";if(message.name!=null&&message.hasOwnProperty("name"))if(!$util.isString(message.name))return"name: string expected";return null;};/**
* Creates an ArtifactId message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.runtime.ArtifactId
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.runtime.ArtifactId} ArtifactId
*/ArtifactId.fromObject=function fromObject(object){if(object instanceof $root.exonum.runtime.ArtifactId)return object;var message=new $root.exonum.runtime.ArtifactId();if(object.runtime_id!=null)message.runtime_id=object.runtime_id>>>0;if(object.name!=null)message.name=String(object.name);return message;};/**
* Creates a plain object from an ArtifactId message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.runtime.ArtifactId
* @static
* @param {exonum.runtime.ArtifactId} message ArtifactId
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ArtifactId.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.runtime_id=0;object.name="";}if(message.runtime_id!=null&&message.hasOwnProperty("runtime_id"))object.runtime_id=message.runtime_id;if(message.name!=null&&message.hasOwnProperty("name"))object.name=message.name;return object;};/**
* Converts this ArtifactId to JSON.
* @function toJSON
* @memberof exonum.runtime.ArtifactId
* @instance
* @returns {Object.<string,*>} JSON object
*/ArtifactId.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ArtifactId;}();runtime.ArtifactSpec=function(){/**
* Properties of an ArtifactSpec.
* @memberof exonum.runtime
* @interface IArtifactSpec
* @property {exonum.runtime.IArtifactId|null} [artifact] ArtifactSpec artifact
* @property {Uint8Array|null} [payload] ArtifactSpec payload
*/ /**
* Constructs a new ArtifactSpec.
* @memberof exonum.runtime
* @classdesc Represents an ArtifactSpec.
* @implements IArtifactSpec
* @constructor
* @param {exonum.runtime.IArtifactSpec=} [properties] Properties to set
*/function ArtifactSpec(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ArtifactSpec artifact.
* @member {exonum.runtime.IArtifactId|null|undefined} artifact
* @memberof exonum.runtime.ArtifactSpec
* @instance
*/ArtifactSpec.prototype.artifact=null;/**
* ArtifactSpec payload.
* @member {Uint8Array} payload
* @memberof exonum.runtime.ArtifactSpec
* @instance
*/ArtifactSpec.prototype.payload=$util.newBuffer([]);/**
* Creates a new ArtifactSpec instance using the specified properties.
* @function create
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {exonum.runtime.IArtifactSpec=} [properties] Properties to set
* @returns {exonum.runtime.ArtifactSpec} ArtifactSpec instance
*/ArtifactSpec.create=function create(properties){return new ArtifactSpec(properties);};/**
* Encodes the specified ArtifactSpec message. Does not implicitly {@link exonum.runtime.ArtifactSpec.verify|verify} messages.
* @function encode
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {exonum.runtime.IArtifactSpec} message ArtifactSpec message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ArtifactSpec.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.artifact!=null&&message.hasOwnProperty("artifact"))$root.exonum.runtime.ArtifactId.encode(message.artifact,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.payload!=null&&message.hasOwnProperty("payload"))writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.payload);return writer;};/**
* Encodes the specified ArtifactSpec message, length delimited. Does not implicitly {@link exonum.runtime.ArtifactSpec.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {exonum.runtime.IArtifactSpec} message ArtifactSpec message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ArtifactSpec.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an ArtifactSpec message from the specified reader or buffer.
* @function decode
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.runtime.ArtifactSpec} ArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ArtifactSpec.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.runtime.ArtifactSpec();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.artifact=$root.exonum.runtime.ArtifactId.decode(reader,reader.uint32());break;case 2:message.payload=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an ArtifactSpec message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.runtime.ArtifactSpec} ArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ArtifactSpec.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an ArtifactSpec message.
* @function verify
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ArtifactSpec.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.artifact!=null&&message.hasOwnProperty("artifact")){var error=$root.exonum.runtime.ArtifactId.verify(message.artifact);if(error)return"artifact."+error;}if(message.payload!=null&&message.hasOwnProperty("payload"))if(!(message.payload&&typeof message.payload.length==="number"||$util.isString(message.payload)))return"payload: buffer expected";return null;};/**
* Creates an ArtifactSpec message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.runtime.ArtifactSpec} ArtifactSpec
*/ArtifactSpec.fromObject=function fromObject(object){if(object instanceof $root.exonum.runtime.ArtifactSpec)return object;var message=new $root.exonum.runtime.ArtifactSpec();if(object.artifact!=null){if((0,_typeof2["default"])(object.artifact)!=="object")throw TypeError(".exonum.runtime.ArtifactSpec.artifact: object expected");message.artifact=$root.exonum.runtime.ArtifactId.fromObject(object.artifact);}if(object.payload!=null)if(typeof object.payload==="string")$util.base64.decode(object.payload,message.payload=$util.newBuffer($util.base64.length(object.payload)),0);else if(object.payload.length)message.payload=object.payload;return message;};/**
* Creates a plain object from an ArtifactSpec message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.runtime.ArtifactSpec
* @static
* @param {exonum.runtime.ArtifactSpec} message ArtifactSpec
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ArtifactSpec.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.artifact=null;if(options.bytes===String)object.payload="";else{object.payload=[];if(options.bytes!==Array)object.payload=$util.newBuffer(object.payload);}}if(message.artifact!=null&&message.hasOwnProperty("artifact"))object.artifact=$root.exonum.runtime.ArtifactId.toObject(message.artifact,options);if(message.payload!=null&&message.hasOwnProperty("payload"))object.payload=options.bytes===String?$util.base64.encode(message.payload,0,message.payload.length):options.bytes===Array?Array.prototype.slice.call(message.payload):message.payload;return object;};/**
* Converts this ArtifactSpec to JSON.
* @function toJSON
* @memberof exonum.runtime.ArtifactSpec
* @instance
* @returns {Object.<string,*>} JSON object
*/ArtifactSpec.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ArtifactSpec;}();runtime.InstanceSpec=function(){/**
* Properties of an InstanceSpec.
* @memberof exonum.runtime
* @interface IInstanceSpec
* @property {number|null} [id] InstanceSpec id
* @property {string|null} [name] InstanceSpec name
* @property {exonum.runtime.IArtifactId|null} [artifact] InstanceSpec artifact
*/ /**
* Constructs a new InstanceSpec.
* @memberof exonum.runtime
* @classdesc Represents an InstanceSpec.
* @implements IInstanceSpec
* @constructor
* @param {exonum.runtime.IInstanceSpec=} [properties] Properties to set
*/function InstanceSpec(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* InstanceSpec id.
* @member {number} id
* @memberof exonum.runtime.InstanceSpec
* @instance
*/InstanceSpec.prototype.id=0;/**
* InstanceSpec name.
* @member {string} name
* @memberof exonum.runtime.InstanceSpec
* @instance
*/InstanceSpec.prototype.name="";/**
* InstanceSpec artifact.
* @member {exonum.runtime.IArtifactId|null|undefined} artifact
* @memberof exonum.runtime.InstanceSpec
* @instance
*/InstanceSpec.prototype.artifact=null;/**
* Creates a new InstanceSpec instance using the specified properties.
* @function create
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {exonum.runtime.IInstanceSpec=} [properties] Properties to set
* @returns {exonum.runtime.InstanceSpec} InstanceSpec instance
*/InstanceSpec.create=function create(properties){return new InstanceSpec(properties);};/**
* Encodes the specified InstanceSpec message. Does not implicitly {@link exonum.runtime.InstanceSpec.verify|verify} messages.
* @function encode
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {exonum.runtime.IInstanceSpec} message InstanceSpec message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/InstanceSpec.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.id!=null&&message.hasOwnProperty("id"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.id);if(message.name!=null&&message.hasOwnProperty("name"))writer.uint32(/* id 2, wireType 2 =*/18).string(message.name);if(message.artifact!=null&&message.hasOwnProperty("artifact"))$root.exonum.runtime.ArtifactId.encode(message.artifact,writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();return writer;};/**
* Encodes the specified InstanceSpec message, length delimited. Does not implicitly {@link exonum.runtime.InstanceSpec.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {exonum.runtime.IInstanceSpec} message InstanceSpec message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/InstanceSpec.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an InstanceSpec message from the specified reader or buffer.
* @function decode
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.runtime.InstanceSpec} InstanceSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/InstanceSpec.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.runtime.InstanceSpec();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.id=reader.uint32();break;case 2:message.name=reader.string();break;case 3:message.artifact=$root.exonum.runtime.ArtifactId.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an InstanceSpec message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.runtime.InstanceSpec} InstanceSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/InstanceSpec.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an InstanceSpec message.
* @function verify
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/InstanceSpec.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.id!=null&&message.hasOwnProperty("id"))if(!$util.isInteger(message.id))return"id: integer expected";if(message.name!=null&&message.hasOwnProperty("name"))if(!$util.isString(message.name))return"name: string expected";if(message.artifact!=null&&message.hasOwnProperty("artifact")){var error=$root.exonum.runtime.ArtifactId.verify(message.artifact);if(error)return"artifact."+error;}return null;};/**
* Creates an InstanceSpec message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.runtime.InstanceSpec} InstanceSpec
*/InstanceSpec.fromObject=function fromObject(object){if(object instanceof $root.exonum.runtime.InstanceSpec)return object;var message=new $root.exonum.runtime.InstanceSpec();if(object.id!=null)message.id=object.id>>>0;if(object.name!=null)message.name=String(object.name);if(object.artifact!=null){if((0,_typeof2["default"])(object.artifact)!=="object")throw TypeError(".exonum.runtime.InstanceSpec.artifact: object expected");message.artifact=$root.exonum.runtime.ArtifactId.fromObject(object.artifact);}return message;};/**
* Creates a plain object from an InstanceSpec message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.runtime.InstanceSpec
* @static
* @param {exonum.runtime.InstanceSpec} message InstanceSpec
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/InstanceSpec.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.id=0;object.name="";object.artifact=null;}if(message.id!=null&&message.hasOwnProperty("id"))object.id=message.id;if(message.name!=null&&message.hasOwnProperty("name"))object.name=message.name;if(message.artifact!=null&&message.hasOwnProperty("artifact"))object.artifact=$root.exonum.runtime.ArtifactId.toObject(message.artifact,options);return object;};/**
* Converts this InstanceSpec to JSON.
* @function toJSON
* @memberof exonum.runtime.InstanceSpec
* @instance
* @returns {Object.<string,*>} JSON object
*/InstanceSpec.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return InstanceSpec;}();return runtime;}();exonum.KeyValue=function(){/**
* Properties of a KeyValue.
* @memberof exonum
* @interface IKeyValue
* @property {string|null} [key] KeyValue key
* @property {Uint8Array|null} [value] KeyValue value
*/ /**
* Constructs a new KeyValue.
* @memberof exonum
* @classdesc Represents a KeyValue.
* @implements IKeyValue
* @constructor
* @param {exonum.IKeyValue=} [properties] Properties to set
*/function KeyValue(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* KeyValue key.
* @member {string} key
* @memberof exonum.KeyValue
* @instance
*/KeyValue.prototype.key="";/**
* KeyValue value.
* @member {Uint8Array} value
* @memberof exonum.KeyValue
* @instance
*/KeyValue.prototype.value=$util.newBuffer([]);/**
* Creates a new KeyValue instance using the specified properties.
* @function create
* @memberof exonum.KeyValue
* @static
* @param {exonum.IKeyValue=} [properties] Properties to set
* @returns {exonum.KeyValue} KeyValue instance
*/KeyValue.create=function create(properties){return new KeyValue(properties);};/**
* Encodes the specified KeyValue message. Does not implicitly {@link exonum.KeyValue.verify|verify} messages.
* @function encode
* @memberof exonum.KeyValue
* @static
* @param {exonum.IKeyValue} message KeyValue message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/KeyValue.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.key!=null&&message.hasOwnProperty("key"))writer.uint32(/* id 1, wireType 2 =*/10).string(message.key);if(message.value!=null&&message.hasOwnProperty("value"))writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.value);return writer;};/**
* Encodes the specified KeyValue message, length delimited. Does not implicitly {@link exonum.KeyValue.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.KeyValue
* @static
* @param {exonum.IKeyValue} message KeyValue message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/KeyValue.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a KeyValue message from the specified reader or buffer.
* @function decode
* @memberof exonum.KeyValue
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.KeyValue} KeyValue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/KeyValue.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.KeyValue();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.key=reader.string();break;case 2:message.value=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a KeyValue message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.KeyValue
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.KeyValue} KeyValue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/KeyValue.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a KeyValue message.
* @function verify
* @memberof exonum.KeyValue
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/KeyValue.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.key!=null&&message.hasOwnProperty("key"))if(!$util.isString(message.key))return"key: string expected";if(message.value!=null&&message.hasOwnProperty("value"))if(!(message.value&&typeof message.value.length==="number"||$util.isString(message.value)))return"value: buffer expected";return null;};/**
* Creates a KeyValue message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.KeyValue
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.KeyValue} KeyValue
*/KeyValue.fromObject=function fromObject(object){if(object instanceof $root.exonum.KeyValue)return object;var message=new $root.exonum.KeyValue();if(object.key!=null)message.key=String(object.key);if(object.value!=null)if(typeof object.value==="string")$util.base64.decode(object.value,message.value=$util.newBuffer($util.base64.length(object.value)),0);else if(object.value.length)message.value=object.value;return message;};/**
* Creates a plain object from a KeyValue message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.KeyValue
* @static
* @param {exonum.KeyValue} message KeyValue
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/KeyValue.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.key="";if(options.bytes===String)object.value="";else{object.value=[];if(options.bytes!==Array)object.value=$util.newBuffer(object.value);}}if(message.key!=null&&message.hasOwnProperty("key"))object.key=message.key;if(message.value!=null&&message.hasOwnProperty("value"))object.value=options.bytes===String?$util.base64.encode(message.value,0,message.value.length):options.bytes===Array?Array.prototype.slice.call(message.value):message.value;return object;};/**
* Converts this KeyValue to JSON.
* @function toJSON
* @memberof exonum.KeyValue
* @instance
* @returns {Object.<string,*>} JSON object
*/KeyValue.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return KeyValue;}();exonum.KeyValueSequence=function(){/**
* Properties of a KeyValueSequence.
* @memberof exonum
* @interface IKeyValueSequence
* @property {Array.<exonum.IKeyValue>|null} [entry] KeyValueSequence entry
*/ /**
* Constructs a new KeyValueSequence.
* @memberof exonum
* @classdesc Represents a KeyValueSequence.
* @implements IKeyValueSequence
* @constructor
* @param {exonum.IKeyValueSequence=} [properties] Properties to set
*/function KeyValueSequence(properties){this.entry=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* KeyValueSequence entry.
* @member {Array.<exonum.IKeyValue>} entry
* @memberof exonum.KeyValueSequence
* @instance
*/KeyValueSequence.prototype.entry=$util.emptyArray;/**
* Creates a new KeyValueSequence instance using the specified properties.
* @function create
* @memberof exonum.KeyValueSequence
* @static
* @param {exonum.IKeyValueSequence=} [properties] Properties to set
* @returns {exonum.KeyValueSequence} KeyValueSequence instance
*/KeyValueSequence.create=function create(properties){return new KeyValueSequence(properties);};/**
* Encodes the specified KeyValueSequence message. Does not implicitly {@link exonum.KeyValueSequence.verify|verify} messages.
* @function encode
* @memberof exonum.KeyValueSequence
* @static
* @param {exonum.IKeyValueSequence} message KeyValueSequence message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/KeyValueSequence.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.entry!=null&&message.entry.length)for(var i=0;i<message.entry.length;++i){$root.exonum.KeyValue.encode(message.entry[i],writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();}return writer;};/**
* Encodes the specified KeyValueSequence message, length delimited. Does not implicitly {@link exonum.KeyValueSequence.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.KeyValueSequence
* @static
* @param {exonum.IKeyValueSequence} message KeyValueSequence message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/KeyValueSequence.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a KeyValueSequence message from the specified reader or buffer.
* @function decode
* @memberof exonum.KeyValueSequence
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.KeyValueSequence} KeyValueSequence
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/KeyValueSequence.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.KeyValueSequence();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:if(!(message.entry&&message.entry.length))message.entry=[];message.entry.push($root.exonum.KeyValue.decode(reader,reader.uint32()));break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a KeyValueSequence message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.KeyValueSequence
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.KeyValueSequence} KeyValueSequence
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/KeyValueSequence.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a KeyValueSequence message.
* @function verify
* @memberof exonum.KeyValueSequence
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/KeyValueSequence.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.entry!=null&&message.hasOwnProperty("entry")){if(!Array.isArray(message.entry))return"entry: array expected";for(var i=0;i<message.entry.length;++i){var error=$root.exonum.KeyValue.verify(message.entry[i]);if(error)return"entry."+error;}}return null;};/**
* Creates a KeyValueSequence message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.KeyValueSequence
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.KeyValueSequence} KeyValueSequence
*/KeyValueSequence.fromObject=function fromObject(object){if(object instanceof $root.exonum.KeyValueSequence)return object;var message=new $root.exonum.KeyValueSequence();if(object.entry){if(!Array.isArray(object.entry))throw TypeError(".exonum.KeyValueSequence.entry: array expected");message.entry=[];for(var i=0;i<object.entry.length;++i){if((0,_typeof2["default"])(object.entry[i])!=="object")throw TypeError(".exonum.KeyValueSequence.entry: object expected");message.entry[i]=$root.exonum.KeyValue.fromObject(object.entry[i]);}}return message;};/**
* Creates a plain object from a KeyValueSequence message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.KeyValueSequence
* @static
* @param {exonum.KeyValueSequence} message KeyValueSequence
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/KeyValueSequence.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.entry=[];if(message.entry&&message.entry.length){object.entry=[];for(var j=0;j<message.entry.length;++j){object.entry[j]=$root.exonum.KeyValue.toObject(message.entry[j],options);}}return object;};/**
* Converts this KeyValueSequence to JSON.
* @function toJSON
* @memberof exonum.KeyValueSequence
* @instance
* @returns {Object.<string,*>} JSON object
*/KeyValueSequence.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return KeyValueSequence;}();exonum.proofs=function(){/**
* Namespace proofs.
* @memberof exonum
* @namespace
*/var proofs={};proofs.BlockProof=function(){/**
* Properties of a BlockProof.
* @memberof exonum.proofs
* @interface IBlockProof
* @property {exonum.IBlock|null} [block] BlockProof block
* @property {Array.<exonum.consensus.ISignedMessage>|null} [precommits] BlockProof precommits
*/ /**
* Constructs a new BlockProof.
* @memberof exonum.proofs
* @classdesc Represents a BlockProof.
* @implements IBlockProof
* @constructor
* @param {exonum.proofs.IBlockProof=} [properties] Properties to set
*/function BlockProof(properties){this.precommits=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* BlockProof block.
* @member {exonum.IBlock|null|undefined} block
* @memberof exonum.proofs.BlockProof
* @instance
*/BlockProof.prototype.block=null;/**
* BlockProof precommits.
* @member {Array.<exonum.consensus.ISignedMessage>} precommits
* @memberof exonum.proofs.BlockProof
* @instance
*/BlockProof.prototype.precommits=$util.emptyArray;/**
* Creates a new BlockProof instance using the specified properties.
* @function create
* @memberof exonum.proofs.BlockProof
* @static
* @param {exonum.proofs.IBlockProof=} [properties] Properties to set
* @returns {exonum.proofs.BlockProof} BlockProof instance
*/BlockProof.create=function create(properties){return new BlockProof(properties);};/**
* Encodes the specified BlockProof message. Does not implicitly {@link exonum.proofs.BlockProof.verify|verify} messages.
* @function encode
* @memberof exonum.proofs.BlockProof
* @static
* @param {exonum.proofs.IBlockProof} message BlockProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BlockProof.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.block!=null&&message.hasOwnProperty("block"))$root.exonum.Block.encode(message.block,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.precommits!=null&&message.precommits.length)for(var i=0;i<message.precommits.length;++i){$root.exonum.consensus.SignedMessage.encode(message.precommits[i],writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();}return writer;};/**
* Encodes the specified BlockProof message, length delimited. Does not implicitly {@link exonum.proofs.BlockProof.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proofs.BlockProof
* @static
* @param {exonum.proofs.IBlockProof} message BlockProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/BlockProof.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a BlockProof message from the specified reader or buffer.
* @function decode
* @memberof exonum.proofs.BlockProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proofs.BlockProof} BlockProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BlockProof.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proofs.BlockProof();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.block=$root.exonum.Block.decode(reader,reader.uint32());break;case 2:if(!(message.precommits&&message.precommits.length))message.precommits=[];message.precommits.push($root.exonum.consensus.SignedMessage.decode(reader,reader.uint32()));break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a BlockProof message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proofs.BlockProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proofs.BlockProof} BlockProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/BlockProof.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a BlockProof message.
* @function verify
* @memberof exonum.proofs.BlockProof
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/BlockProof.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.block!=null&&message.hasOwnProperty("block")){var error=$root.exonum.Block.verify(message.block);if(error)return"block."+error;}if(message.precommits!=null&&message.hasOwnProperty("precommits")){if(!Array.isArray(message.precommits))return"precommits: array expected";for(var i=0;i<message.precommits.length;++i){var error=$root.exonum.consensus.SignedMessage.verify(message.precommits[i]);if(error)return"precommits."+error;}}return null;};/**
* Creates a BlockProof message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proofs.BlockProof
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proofs.BlockProof} BlockProof
*/BlockProof.fromObject=function fromObject(object){if(object instanceof $root.exonum.proofs.BlockProof)return object;var message=new $root.exonum.proofs.BlockProof();if(object.block!=null){if((0,_typeof2["default"])(object.block)!=="object")throw TypeError(".exonum.proofs.BlockProof.block: object expected");message.block=$root.exonum.Block.fromObject(object.block);}if(object.precommits){if(!Array.isArray(object.precommits))throw TypeError(".exonum.proofs.BlockProof.precommits: array expected");message.precommits=[];for(var i=0;i<object.precommits.length;++i){if((0,_typeof2["default"])(object.precommits[i])!=="object")throw TypeError(".exonum.proofs.BlockProof.precommits: object expected");message.precommits[i]=$root.exonum.consensus.SignedMessage.fromObject(object.precommits[i]);}}return message;};/**
* Creates a plain object from a BlockProof message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proofs.BlockProof
* @static
* @param {exonum.proofs.BlockProof} message BlockProof
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/BlockProof.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.precommits=[];if(options.defaults)object.block=null;if(message.block!=null&&message.hasOwnProperty("block"))object.block=$root.exonum.Block.toObject(message.block,options);if(message.precommits&&message.precommits.length){object.precommits=[];for(var j=0;j<message.precommits.length;++j){object.precommits[j]=$root.exonum.consensus.SignedMessage.toObject(message.precommits[j],options);}}return object;};/**
* Converts this BlockProof to JSON.
* @function toJSON
* @memberof exonum.proofs.BlockProof
* @instance
* @returns {Object.<string,*>} JSON object
*/BlockProof.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return BlockProof;}();proofs.ConfigChangeProof=function(){/**
* Properties of a ConfigChangeProof.
* @memberof exonum.proofs
* @interface IConfigChangeProof
* @property {exonum.proof.IListProof|null} [configs_proof] ConfigChangeProof configs_proof
* @property {exonum.proof.IMapProof|null} [configs_index_proof] ConfigChangeProof configs_index_proof
* @property {Array.<exonum.proofs.IBlockProof>|null} [blocks_proofs] ConfigChangeProof blocks_proofs
* @property {Uint8Array|null} [foreign_proof] ConfigChangeProof foreign_proof
*/ /**
* Constructs a new ConfigChangeProof.
* @memberof exonum.proofs
* @classdesc Represents a ConfigChangeProof.
* @implements IConfigChangeProof
* @constructor
* @param {exonum.proofs.IConfigChangeProof=} [properties] Properties to set
*/function ConfigChangeProof(properties){this.blocks_proofs=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ConfigChangeProof configs_proof.
* @member {exonum.proof.IListProof|null|undefined} configs_proof
* @memberof exonum.proofs.ConfigChangeProof
* @instance
*/ConfigChangeProof.prototype.configs_proof=null;/**
* ConfigChangeProof configs_index_proof.
* @member {exonum.proof.IMapProof|null|undefined} configs_index_proof
* @memberof exonum.proofs.ConfigChangeProof
* @instance
*/ConfigChangeProof.prototype.configs_index_proof=null;/**
* ConfigChangeProof blocks_proofs.
* @member {Array.<exonum.proofs.IBlockProof>} blocks_proofs
* @memberof exonum.proofs.ConfigChangeProof
* @instance
*/ConfigChangeProof.prototype.blocks_proofs=$util.emptyArray;/**
* ConfigChangeProof foreign_proof.
* @member {Uint8Array} foreign_proof
* @memberof exonum.proofs.ConfigChangeProof
* @instance
*/ConfigChangeProof.prototype.foreign_proof=$util.newBuffer([]);/**
* Creates a new ConfigChangeProof instance using the specified properties.
* @function create
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {exonum.proofs.IConfigChangeProof=} [properties] Properties to set
* @returns {exonum.proofs.ConfigChangeProof} ConfigChangeProof instance
*/ConfigChangeProof.create=function create(properties){return new ConfigChangeProof(properties);};/**
* Encodes the specified ConfigChangeProof message. Does not implicitly {@link exonum.proofs.ConfigChangeProof.verify|verify} messages.
* @function encode
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {exonum.proofs.IConfigChangeProof} message ConfigChangeProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ConfigChangeProof.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.configs_proof!=null&&message.hasOwnProperty("configs_proof"))$root.exonum.proof.ListProof.encode(message.configs_proof,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.configs_index_proof!=null&&message.hasOwnProperty("configs_index_proof"))$root.exonum.proof.MapProof.encode(message.configs_index_proof,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();if(message.blocks_proofs!=null&&message.blocks_proofs.length)for(var i=0;i<message.blocks_proofs.length;++i){$root.exonum.proofs.BlockProof.encode(message.blocks_proofs[i],writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();}if(message.foreign_proof!=null&&message.hasOwnProperty("foreign_proof"))writer.uint32(/* id 4, wireType 2 =*/34).bytes(message.foreign_proof);return writer;};/**
* Encodes the specified ConfigChangeProof message, length delimited. Does not implicitly {@link exonum.proofs.ConfigChangeProof.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {exonum.proofs.IConfigChangeProof} message ConfigChangeProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ConfigChangeProof.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a ConfigChangeProof message from the specified reader or buffer.
* @function decode
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proofs.ConfigChangeProof} ConfigChangeProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ConfigChangeProof.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proofs.ConfigChangeProof();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.configs_proof=$root.exonum.proof.ListProof.decode(reader,reader.uint32());break;case 2:message.configs_index_proof=$root.exonum.proof.MapProof.decode(reader,reader.uint32());break;case 3:if(!(message.blocks_proofs&&message.blocks_proofs.length))message.blocks_proofs=[];message.blocks_proofs.push($root.exonum.proofs.BlockProof.decode(reader,reader.uint32()));break;case 4:message.foreign_proof=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a ConfigChangeProof message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proofs.ConfigChangeProof} ConfigChangeProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ConfigChangeProof.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a ConfigChangeProof message.
* @function verify
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ConfigChangeProof.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.configs_proof!=null&&message.hasOwnProperty("configs_proof")){var error=$root.exonum.proof.ListProof.verify(message.configs_proof);if(error)return"configs_proof."+error;}if(message.configs_index_proof!=null&&message.hasOwnProperty("configs_index_proof")){var error=$root.exonum.proof.MapProof.verify(message.configs_index_proof);if(error)return"configs_index_proof."+error;}if(message.blocks_proofs!=null&&message.hasOwnProperty("blocks_proofs")){if(!Array.isArray(message.blocks_proofs))return"blocks_proofs: array expected";for(var i=0;i<message.blocks_proofs.length;++i){var error=$root.exonum.proofs.BlockProof.verify(message.blocks_proofs[i]);if(error)return"blocks_proofs."+error;}}if(message.foreign_proof!=null&&message.hasOwnProperty("foreign_proof"))if(!(message.foreign_proof&&typeof message.foreign_proof.length==="number"||$util.isString(message.foreign_proof)))return"foreign_proof: buffer expected";return null;};/**
* Creates a ConfigChangeProof message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proofs.ConfigChangeProof} ConfigChangeProof
*/ConfigChangeProof.fromObject=function fromObject(object){if(object instanceof $root.exonum.proofs.ConfigChangeProof)return object;var message=new $root.exonum.proofs.ConfigChangeProof();if(object.configs_proof!=null){if((0,_typeof2["default"])(object.configs_proof)!=="object")throw TypeError(".exonum.proofs.ConfigChangeProof.configs_proof: object expected");message.configs_proof=$root.exonum.proof.ListProof.fromObject(object.configs_proof);}if(object.configs_index_proof!=null){if((0,_typeof2["default"])(object.configs_index_proof)!=="object")throw TypeError(".exonum.proofs.ConfigChangeProof.configs_index_proof: object expected");message.configs_index_proof=$root.exonum.proof.MapProof.fromObject(object.configs_index_proof);}if(object.blocks_proofs){if(!Array.isArray(object.blocks_proofs))throw TypeError(".exonum.proofs.ConfigChangeProof.blocks_proofs: array expected");message.blocks_proofs=[];for(var i=0;i<object.blocks_proofs.length;++i){if((0,_typeof2["default"])(object.blocks_proofs[i])!=="object")throw TypeError(".exonum.proofs.ConfigChangeProof.blocks_proofs: object expected");message.blocks_proofs[i]=$root.exonum.proofs.BlockProof.fromObject(object.blocks_proofs[i]);}}if(object.foreign_proof!=null)if(typeof object.foreign_proof==="string")$util.base64.decode(object.foreign_proof,message.foreign_proof=$util.newBuffer($util.base64.length(object.foreign_proof)),0);else if(object.foreign_proof.length)message.foreign_proof=object.foreign_proof;return message;};/**
* Creates a plain object from a ConfigChangeProof message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proofs.ConfigChangeProof
* @static
* @param {exonum.proofs.ConfigChangeProof} message ConfigChangeProof
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ConfigChangeProof.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.blocks_proofs=[];if(options.defaults){object.configs_proof=null;object.configs_index_proof=null;if(options.bytes===String)object.foreign_proof="";else{object.foreign_proof=[];if(options.bytes!==Array)object.foreign_proof=$util.newBuffer(object.foreign_proof);}}if(message.configs_proof!=null&&message.hasOwnProperty("configs_proof"))object.configs_proof=$root.exonum.proof.ListProof.toObject(message.configs_proof,options);if(message.configs_index_proof!=null&&message.hasOwnProperty("configs_index_proof"))object.configs_index_proof=$root.exonum.proof.MapProof.toObject(message.configs_index_proof,options);if(message.blocks_proofs&&message.blocks_proofs.length){object.blocks_proofs=[];for(var j=0;j<message.blocks_proofs.length;++j){object.blocks_proofs[j]=$root.exonum.proofs.BlockProof.toObject(message.blocks_proofs[j],options);}}if(message.foreign_proof!=null&&message.hasOwnProperty("foreign_proof"))object.foreign_proof=options.bytes===String?$util.base64.encode(message.foreign_proof,0,message.foreign_proof.length):options.bytes===Array?Array.prototype.slice.call(message.foreign_proof):message.foreign_proof;return object;};/**
* Converts this ConfigChangeProof to JSON.
* @function toJSON
* @memberof exonum.proofs.ConfigChangeProof
* @instance
* @returns {Object.<string,*>} JSON object
*/ConfigChangeProof.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ConfigChangeProof;}();proofs.ForeignTxProof=function(){/**
* Properties of a ForeignTxProof.
* @memberof exonum.proofs
* @interface IForeignTxProof
* @property {Array.<exonum.consensus.ISignedMessage>|null} [txs] ForeignTxProof txs
* @property {exonum.proof.IMapProof|null} [results_proof] ForeignTxProof results_proof
* @property {exonum.proof.IMapProof|null} [results_index_proof] ForeignTxProof results_index_proof
*/ /**
* Constructs a new ForeignTxProof.
* @memberof exonum.proofs
* @classdesc Represents a ForeignTxProof.
* @implements IForeignTxProof
* @constructor
* @param {exonum.proofs.IForeignTxProof=} [properties] Properties to set
*/function ForeignTxProof(properties){this.txs=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ForeignTxProof txs.
* @member {Array.<exonum.consensus.ISignedMessage>} txs
* @memberof exonum.proofs.ForeignTxProof
* @instance
*/ForeignTxProof.prototype.txs=$util.emptyArray;/**
* ForeignTxProof results_proof.
* @member {exonum.proof.IMapProof|null|undefined} results_proof
* @memberof exonum.proofs.ForeignTxProof
* @instance
*/ForeignTxProof.prototype.results_proof=null;/**
* ForeignTxProof results_index_proof.
* @member {exonum.proof.IMapProof|null|undefined} results_index_proof
* @memberof exonum.proofs.ForeignTxProof
* @instance
*/ForeignTxProof.prototype.results_index_proof=null;/**
* Creates a new ForeignTxProof instance using the specified properties.
* @function create
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {exonum.proofs.IForeignTxProof=} [properties] Properties to set
* @returns {exonum.proofs.ForeignTxProof} ForeignTxProof instance
*/ForeignTxProof.create=function create(properties){return new ForeignTxProof(properties);};/**
* Encodes the specified ForeignTxProof message. Does not implicitly {@link exonum.proofs.ForeignTxProof.verify|verify} messages.
* @function encode
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {exonum.proofs.IForeignTxProof} message ForeignTxProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ForeignTxProof.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.txs!=null&&message.txs.length)for(var i=0;i<message.txs.length;++i){$root.exonum.consensus.SignedMessage.encode(message.txs[i],writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();}if(message.results_proof!=null&&message.hasOwnProperty("results_proof"))$root.exonum.proof.MapProof.encode(message.results_proof,writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();if(message.results_index_proof!=null&&message.hasOwnProperty("results_index_proof"))$root.exonum.proof.MapProof.encode(message.results_index_proof,writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim();return writer;};/**
* Encodes the specified ForeignTxProof message, length delimited. Does not implicitly {@link exonum.proofs.ForeignTxProof.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {exonum.proofs.IForeignTxProof} message ForeignTxProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ForeignTxProof.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a ForeignTxProof message from the specified reader or buffer.
* @function decode
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proofs.ForeignTxProof} ForeignTxProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ForeignTxProof.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proofs.ForeignTxProof();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 2:if(!(message.txs&&message.txs.length))message.txs=[];message.txs.push($root.exonum.consensus.SignedMessage.decode(reader,reader.uint32()));break;case 3:message.results_proof=$root.exonum.proof.MapProof.decode(reader,reader.uint32());break;case 4:message.results_index_proof=$root.exonum.proof.MapProof.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a ForeignTxProof message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proofs.ForeignTxProof} ForeignTxProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ForeignTxProof.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a ForeignTxProof message.
* @function verify
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ForeignTxProof.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.txs!=null&&message.hasOwnProperty("txs")){if(!Array.isArray(message.txs))return"txs: array expected";for(var i=0;i<message.txs.length;++i){var error=$root.exonum.consensus.SignedMessage.verify(message.txs[i]);if(error)return"txs."+error;}}if(message.results_proof!=null&&message.hasOwnProperty("results_proof")){var error=$root.exonum.proof.MapProof.verify(message.results_proof);if(error)return"results_proof."+error;}if(message.results_index_proof!=null&&message.hasOwnProperty("results_index_proof")){var error=$root.exonum.proof.MapProof.verify(message.results_index_proof);if(error)return"results_index_proof."+error;}return null;};/**
* Creates a ForeignTxProof message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proofs.ForeignTxProof} ForeignTxProof
*/ForeignTxProof.fromObject=function fromObject(object){if(object instanceof $root.exonum.proofs.ForeignTxProof)return object;var message=new $root.exonum.proofs.ForeignTxProof();if(object.txs){if(!Array.isArray(object.txs))throw TypeError(".exonum.proofs.ForeignTxProof.txs: array expected");message.txs=[];for(var i=0;i<object.txs.length;++i){if((0,_typeof2["default"])(object.txs[i])!=="object")throw TypeError(".exonum.proofs.ForeignTxProof.txs: object expected");message.txs[i]=$root.exonum.consensus.SignedMessage.fromObject(object.txs[i]);}}if(object.results_proof!=null){if((0,_typeof2["default"])(object.results_proof)!=="object")throw TypeError(".exonum.proofs.ForeignTxProof.results_proof: object expected");message.results_proof=$root.exonum.proof.MapProof.fromObject(object.results_proof);}if(object.results_index_proof!=null){if((0,_typeof2["default"])(object.results_index_proof)!=="object")throw TypeError(".exonum.proofs.ForeignTxProof.results_index_proof: object expected");message.results_index_proof=$root.exonum.proof.MapProof.fromObject(object.results_index_proof);}return message;};/**
* Creates a plain object from a ForeignTxProof message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proofs.ForeignTxProof
* @static
* @param {exonum.proofs.ForeignTxProof} message ForeignTxProof
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ForeignTxProof.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults)object.txs=[];if(options.defaults){object.results_proof=null;object.results_index_proof=null;}if(message.txs&&message.txs.length){object.txs=[];for(var j=0;j<message.txs.length;++j){object.txs[j]=$root.exonum.consensus.SignedMessage.toObject(message.txs[j],options);}}if(message.results_proof!=null&&message.hasOwnProperty("results_proof"))object.results_proof=$root.exonum.proof.MapProof.toObject(message.results_proof,options);if(message.results_index_proof!=null&&message.hasOwnProperty("results_index_proof"))object.results_index_proof=$root.exonum.proof.MapProof.toObject(message.results_index_proof,options);return object;};/**
* Converts this ForeignTxProof to JSON.
* @function toJSON
* @memberof exonum.proofs.ForeignTxProof
* @instance
* @returns {Object.<string,*>} JSON object
*/ForeignTxProof.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ForeignTxProof;}();return proofs;}();exonum.tests=function(){/**
* Namespace tests.
* @memberof exonum
* @namespace
*/var tests={};tests.Point=function(){/**
* Properties of a Point.
* @memberof exonum.tests
* @interface IPoint
* @property {number|null} [x] Point x
* @property {number|null} [y] Point y
*/ /**
* Constructs a new Point.
* @memberof exonum.tests
* @classdesc Represents a Point.
* @implements IPoint
* @constructor
* @param {exonum.tests.IPoint=} [properties] Properties to set
*/function Point(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Point x.
* @member {number} x
* @memberof exonum.tests.Point
* @instance
*/Point.prototype.x=0;/**
* Point y.
* @member {number} y
* @memberof exonum.tests.Point
* @instance
*/Point.prototype.y=0;/**
* Creates a new Point instance using the specified properties.
* @function create
* @memberof exonum.tests.Point
* @static
* @param {exonum.tests.IPoint=} [properties] Properties to set
* @returns {exonum.tests.Point} Point instance
*/Point.create=function create(properties){return new Point(properties);};/**
* Encodes the specified Point message. Does not implicitly {@link exonum.tests.Point.verify|verify} messages.
* @function encode
* @memberof exonum.tests.Point
* @static
* @param {exonum.tests.IPoint} message Point message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Point.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.x!=null&&message.hasOwnProperty("x"))writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.x);if(message.y!=null&&message.hasOwnProperty("y"))writer.uint32(/* id 2, wireType 0 =*/16).uint32(message.y);return writer;};/**
* Encodes the specified Point message, length delimited. Does not implicitly {@link exonum.tests.Point.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.tests.Point
* @static
* @param {exonum.tests.IPoint} message Point message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Point.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Point message from the specified reader or buffer.
* @function decode
* @memberof exonum.tests.Point
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.tests.Point} Point
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Point.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.tests.Point();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.x=reader.uint32();break;case 2:message.y=reader.uint32();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Point message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.tests.Point
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.tests.Point} Point
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Point.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Point message.
* @function verify
* @memberof exonum.tests.Point
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Point.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.x!=null&&message.hasOwnProperty("x"))if(!$util.isInteger(message.x))return"x: integer expected";if(message.y!=null&&message.hasOwnProperty("y"))if(!$util.isInteger(message.y))return"y: integer expected";return null;};/**
* Creates a Point message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.tests.Point
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.tests.Point} Point
*/Point.fromObject=function fromObject(object){if(object instanceof $root.exonum.tests.Point)return object;var message=new $root.exonum.tests.Point();if(object.x!=null)message.x=object.x>>>0;if(object.y!=null)message.y=object.y>>>0;return message;};/**
* Creates a plain object from a Point message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.tests.Point
* @static
* @param {exonum.tests.Point} message Point
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Point.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.x=0;object.y=0;}if(message.x!=null&&message.hasOwnProperty("x"))object.x=message.x;if(message.y!=null&&message.hasOwnProperty("y"))object.y=message.y;return object;};/**
* Converts this Point to JSON.
* @function toJSON
* @memberof exonum.tests.Point
* @instance
* @returns {Object.<string,*>} JSON object
*/Point.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Point;}();tests.TestProtobufConvert=function(){/**
* Properties of a TestProtobufConvert.
* @memberof exonum.tests
* @interface ITestProtobufConvert
* @property {exonum.crypto.IPublicKey|null} [key] TestProtobufConvert key
* @property {exonum.crypto.IHash|null} [hash] TestProtobufConvert hash
* @property {number|null} [unsigned_32] TestProtobufConvert unsigned_32
* @property {number|Long|null} [unsigned_64] TestProtobufConvert unsigned_64
* @property {number|null} [regular_i32] TestProtobufConvert regular_i32
* @property {number|Long|null} [regular_i64] TestProtobufConvert regular_i64
* @property {number|null} [fixed_u32] TestProtobufConvert fixed_u32
* @property {number|Long|null} [fixed_u64] TestProtobufConvert fixed_u64
* @property {number|null} [fixed_i32] TestProtobufConvert fixed_i32
* @property {number|Long|null} [fixed_i64] TestProtobufConvert fixed_i64
* @property {number|null} [float_32] TestProtobufConvert float_32
* @property {number|null} [float_64] TestProtobufConvert float_64
* @property {boolean|null} [boolean] TestProtobufConvert boolean
* @property {number|null} [s_i32] TestProtobufConvert s_i32
* @property {number|Long|null} [s_i64] TestProtobufConvert s_i64
* @property {Uint8Array|null} [bytes_field] TestProtobufConvert bytes_field
* @property {string|null} [string_field] TestProtobufConvert string_field
* @property {exonum.tests.IPoint|null} [message_field] TestProtobufConvert message_field
* @property {exonum.common.IBitVec|null} [bit_vec] TestProtobufConvert bit_vec
* @property {google.protobuf.ITimestamp|null} [time] TestProtobufConvert time
*/ /**
* Constructs a new TestProtobufConvert.
* @memberof exonum.tests
* @classdesc Represents a TestProtobufConvert.
* @implements ITestProtobufConvert
* @constructor
* @param {exonum.tests.ITestProtobufConvert=} [properties] Properties to set
*/function TestProtobufConvert(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* TestProtobufConvert key.
* @member {exonum.crypto.IPublicKey|null|undefined} key
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.key=null;/**
* TestProtobufConvert hash.
* @member {exonum.crypto.IHash|null|undefined} hash
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.hash=null;/**
* TestProtobufConvert unsigned_32.
* @member {number} unsigned_32
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.unsigned_32=0;/**
* TestProtobufConvert unsigned_64.
* @member {number|Long} unsigned_64
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.unsigned_64=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* TestProtobufConvert regular_i32.
* @member {number} regular_i32
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.regular_i32=0;/**
* TestProtobufConvert regular_i64.
* @member {number|Long} regular_i64
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.regular_i64=$util.Long?$util.Long.fromBits(0,0,false):0;/**
* TestProtobufConvert fixed_u32.
* @member {number} fixed_u32
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.fixed_u32=0;/**
* TestProtobufConvert fixed_u64.
* @member {number|Long} fixed_u64
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.fixed_u64=$util.Long?$util.Long.fromBits(0,0,false):0;/**
* TestProtobufConvert fixed_i32.
* @member {number} fixed_i32
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.fixed_i32=0;/**
* TestProtobufConvert fixed_i64.
* @member {number|Long} fixed_i64
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.fixed_i64=$util.Long?$util.Long.fromBits(0,0,false):0;/**
* TestProtobufConvert float_32.
* @member {number} float_32
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.float_32=0;/**
* TestProtobufConvert float_64.
* @member {number} float_64
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.float_64=0;/**
* TestProtobufConvert boolean.
* @member {boolean} boolean
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype["boolean"]=false;/**
* TestProtobufConvert s_i32.
* @member {number} s_i32
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.s_i32=0;/**
* TestProtobufConvert s_i64.
* @member {number|Long} s_i64
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.s_i64=$util.Long?$util.Long.fromBits(0,0,false):0;/**
* TestProtobufConvert bytes_field.
* @member {Uint8Array} bytes_field
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.bytes_field=$util.newBuffer([]);/**
* TestProtobufConvert string_field.
* @member {string} string_field
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.string_field="";/**
* TestProtobufConvert message_field.
* @member {exonum.tests.IPoint|null|undefined} message_field
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.message_field=null;/**
* TestProtobufConvert bit_vec.
* @member {exonum.common.IBitVec|null|undefined} bit_vec
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.bit_vec=null;/**
* TestProtobufConvert time.
* @member {google.protobuf.ITimestamp|null|undefined} time
* @memberof exonum.tests.TestProtobufConvert
* @instance
*/TestProtobufConvert.prototype.time=null;/**
* Creates a new TestProtobufConvert instance using the specified properties.
* @function create
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {exonum.tests.ITestProtobufConvert=} [properties] Properties to set
* @returns {exonum.tests.TestProtobufConvert} TestProtobufConvert instance
*/TestProtobufConvert.create=function create(properties){return new TestProtobufConvert(properties);};/**
* Encodes the specified TestProtobufConvert message. Does not implicitly {@link exonum.tests.TestProtobufConvert.verify|verify} messages.
* @function encode
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {exonum.tests.ITestProtobufConvert} message TestProtobufConvert message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestProtobufConvert.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.key!=null&&message.hasOwnProperty("key"))$root.exonum.crypto.PublicKey.encode(message.key,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.hash!=null&&message.hasOwnProperty("hash"))$root.exonum.crypto.Hash.encode(message.hash,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();if(message.unsigned_32!=null&&message.hasOwnProperty("unsigned_32"))writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.unsigned_32);if(message.unsigned_64!=null&&message.hasOwnProperty("unsigned_64"))writer.uint32(/* id 4, wireType 0 =*/32).uint64(message.unsigned_64);if(message.regular_i32!=null&&message.hasOwnProperty("regular_i32"))writer.uint32(/* id 5, wireType 0 =*/40).int32(message.regular_i32);if(message.regular_i64!=null&&message.hasOwnProperty("regular_i64"))writer.uint32(/* id 6, wireType 0 =*/48).int64(message.regular_i64);if(message.fixed_u32!=null&&message.hasOwnProperty("fixed_u32"))writer.uint32(/* id 7, wireType 5 =*/61).fixed32(message.fixed_u32);if(message.fixed_u64!=null&&message.hasOwnProperty("fixed_u64"))writer.uint32(/* id 8, wireType 1 =*/65).fixed64(message.fixed_u64);if(message.fixed_i32!=null&&message.hasOwnProperty("fixed_i32"))writer.uint32(/* id 9, wireType 5 =*/77).sfixed32(message.fixed_i32);if(message.fixed_i64!=null&&message.hasOwnProperty("fixed_i64"))writer.uint32(/* id 10, wireType 1 =*/81).sfixed64(message.fixed_i64);if(message.float_32!=null&&message.hasOwnProperty("float_32"))writer.uint32(/* id 11, wireType 5 =*/93)["float"](message.float_32);if(message.float_64!=null&&message.hasOwnProperty("float_64"))writer.uint32(/* id 12, wireType 1 =*/97)["double"](message.float_64);if(message["boolean"]!=null&&message.hasOwnProperty("boolean"))writer.uint32(/* id 13, wireType 0 =*/104).bool(message["boolean"]);if(message.s_i32!=null&&message.hasOwnProperty("s_i32"))writer.uint32(/* id 14, wireType 0 =*/112).sint32(message.s_i32);if(message.s_i64!=null&&message.hasOwnProperty("s_i64"))writer.uint32(/* id 15, wireType 0 =*/120).sint64(message.s_i64);if(message.bytes_field!=null&&message.hasOwnProperty("bytes_field"))writer.uint32(/* id 16, wireType 2 =*/130).bytes(message.bytes_field);if(message.string_field!=null&&message.hasOwnProperty("string_field"))writer.uint32(/* id 17, wireType 2 =*/138).string(message.string_field);if(message.message_field!=null&&message.hasOwnProperty("message_field"))$root.exonum.tests.Point.encode(message.message_field,writer.uint32(/* id 18, wireType 2 =*/146).fork()).ldelim();if(message.bit_vec!=null&&message.hasOwnProperty("bit_vec"))$root.exonum.common.BitVec.encode(message.bit_vec,writer.uint32(/* id 19, wireType 2 =*/154).fork()).ldelim();if(message.time!=null&&message.hasOwnProperty("time"))$root.google.protobuf.Timestamp.encode(message.time,writer.uint32(/* id 20, wireType 2 =*/162).fork()).ldelim();return writer;};/**
* Encodes the specified TestProtobufConvert message, length delimited. Does not implicitly {@link exonum.tests.TestProtobufConvert.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {exonum.tests.ITestProtobufConvert} message TestProtobufConvert message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestProtobufConvert.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a TestProtobufConvert message from the specified reader or buffer.
* @function decode
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.tests.TestProtobufConvert} TestProtobufConvert
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestProtobufConvert.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.tests.TestProtobufConvert();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.key=$root.exonum.crypto.PublicKey.decode(reader,reader.uint32());break;case 2:message.hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;case 3:message.unsigned_32=reader.uint32();break;case 4:message.unsigned_64=reader.uint64();break;case 5:message.regular_i32=reader.int32();break;case 6:message.regular_i64=reader.int64();break;case 7:message.fixed_u32=reader.fixed32();break;case 8:message.fixed_u64=reader.fixed64();break;case 9:message.fixed_i32=reader.sfixed32();break;case 10:message.fixed_i64=reader.sfixed64();break;case 11:message.float_32=reader["float"]();break;case 12:message.float_64=reader["double"]();break;case 13:message["boolean"]=reader.bool();break;case 14:message.s_i32=reader.sint32();break;case 15:message.s_i64=reader.sint64();break;case 16:message.bytes_field=reader.bytes();break;case 17:message.string_field=reader.string();break;case 18:message.message_field=$root.exonum.tests.Point.decode(reader,reader.uint32());break;case 19:message.bit_vec=$root.exonum.common.BitVec.decode(reader,reader.uint32());break;case 20:message.time=$root.google.protobuf.Timestamp.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a TestProtobufConvert message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.tests.TestProtobufConvert} TestProtobufConvert
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestProtobufConvert.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a TestProtobufConvert message.
* @function verify
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/TestProtobufConvert.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.key!=null&&message.hasOwnProperty("key")){var error=$root.exonum.crypto.PublicKey.verify(message.key);if(error)return"key."+error;}if(message.hash!=null&&message.hasOwnProperty("hash")){var error=$root.exonum.crypto.Hash.verify(message.hash);if(error)return"hash."+error;}if(message.unsigned_32!=null&&message.hasOwnProperty("unsigned_32"))if(!$util.isInteger(message.unsigned_32))return"unsigned_32: integer expected";if(message.unsigned_64!=null&&message.hasOwnProperty("unsigned_64"))if(!$util.isInteger(message.unsigned_64)&&!(message.unsigned_64&&$util.isInteger(message.unsigned_64.low)&&$util.isInteger(message.unsigned_64.high)))return"unsigned_64: integer|Long expected";if(message.regular_i32!=null&&message.hasOwnProperty("regular_i32"))if(!$util.isInteger(message.regular_i32))return"regular_i32: integer expected";if(message.regular_i64!=null&&message.hasOwnProperty("regular_i64"))if(!$util.isInteger(message.regular_i64)&&!(message.regular_i64&&$util.isInteger(message.regular_i64.low)&&$util.isInteger(message.regular_i64.high)))return"regular_i64: integer|Long expected";if(message.fixed_u32!=null&&message.hasOwnProperty("fixed_u32"))if(!$util.isInteger(message.fixed_u32))return"fixed_u32: integer expected";if(message.fixed_u64!=null&&message.hasOwnProperty("fixed_u64"))if(!$util.isInteger(message.fixed_u64)&&!(message.fixed_u64&&$util.isInteger(message.fixed_u64.low)&&$util.isInteger(message.fixed_u64.high)))return"fixed_u64: integer|Long expected";if(message.fixed_i32!=null&&message.hasOwnProperty("fixed_i32"))if(!$util.isInteger(message.fixed_i32))return"fixed_i32: integer expected";if(message.fixed_i64!=null&&message.hasOwnProperty("fixed_i64"))if(!$util.isInteger(message.fixed_i64)&&!(message.fixed_i64&&$util.isInteger(message.fixed_i64.low)&&$util.isInteger(message.fixed_i64.high)))return"fixed_i64: integer|Long expected";if(message.float_32!=null&&message.hasOwnProperty("float_32"))if(typeof message.float_32!=="number")return"float_32: number expected";if(message.float_64!=null&&message.hasOwnProperty("float_64"))if(typeof message.float_64!=="number")return"float_64: number expected";if(message["boolean"]!=null&&message.hasOwnProperty("boolean"))if(typeof message["boolean"]!=="boolean")return"boolean: boolean expected";if(message.s_i32!=null&&message.hasOwnProperty("s_i32"))if(!$util.isInteger(message.s_i32))return"s_i32: integer expected";if(message.s_i64!=null&&message.hasOwnProperty("s_i64"))if(!$util.isInteger(message.s_i64)&&!(message.s_i64&&$util.isInteger(message.s_i64.low)&&$util.isInteger(message.s_i64.high)))return"s_i64: integer|Long expected";if(message.bytes_field!=null&&message.hasOwnProperty("bytes_field"))if(!(message.bytes_field&&typeof message.bytes_field.length==="number"||$util.isString(message.bytes_field)))return"bytes_field: buffer expected";if(message.string_field!=null&&message.hasOwnProperty("string_field"))if(!$util.isString(message.string_field))return"string_field: string expected";if(message.message_field!=null&&message.hasOwnProperty("message_field")){var error=$root.exonum.tests.Point.verify(message.message_field);if(error)return"message_field."+error;}if(message.bit_vec!=null&&message.hasOwnProperty("bit_vec")){var error=$root.exonum.common.BitVec.verify(message.bit_vec);if(error)return"bit_vec."+error;}if(message.time!=null&&message.hasOwnProperty("time")){var error=$root.google.protobuf.Timestamp.verify(message.time);if(error)return"time."+error;}return null;};/**
* Creates a TestProtobufConvert message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.tests.TestProtobufConvert} TestProtobufConvert
*/TestProtobufConvert.fromObject=function fromObject(object){if(object instanceof $root.exonum.tests.TestProtobufConvert)return object;var message=new $root.exonum.tests.TestProtobufConvert();if(object.key!=null){if((0,_typeof2["default"])(object.key)!=="object")throw TypeError(".exonum.tests.TestProtobufConvert.key: object expected");message.key=$root.exonum.crypto.PublicKey.fromObject(object.key);}if(object.hash!=null){if((0,_typeof2["default"])(object.hash)!=="object")throw TypeError(".exonum.tests.TestProtobufConvert.hash: object expected");message.hash=$root.exonum.crypto.Hash.fromObject(object.hash);}if(object.unsigned_32!=null)message.unsigned_32=object.unsigned_32>>>0;if(object.unsigned_64!=null)if($util.Long)(message.unsigned_64=$util.Long.fromValue(object.unsigned_64)).unsigned=true;else if(typeof object.unsigned_64==="string")message.unsigned_64=parseInt(object.unsigned_64,10);else if(typeof object.unsigned_64==="number")message.unsigned_64=object.unsigned_64;else if((0,_typeof2["default"])(object.unsigned_64)==="object")message.unsigned_64=new $util.LongBits(object.unsigned_64.low>>>0,object.unsigned_64.high>>>0).toNumber(true);if(object.regular_i32!=null)message.regular_i32=object.regular_i32|0;if(object.regular_i64!=null)if($util.Long)(message.regular_i64=$util.Long.fromValue(object.regular_i64)).unsigned=false;else if(typeof object.regular_i64==="string")message.regular_i64=parseInt(object.regular_i64,10);else if(typeof object.regular_i64==="number")message.regular_i64=object.regular_i64;else if((0,_typeof2["default"])(object.regular_i64)==="object")message.regular_i64=new $util.LongBits(object.regular_i64.low>>>0,object.regular_i64.high>>>0).toNumber();if(object.fixed_u32!=null)message.fixed_u32=object.fixed_u32>>>0;if(object.fixed_u64!=null)if($util.Long)(message.fixed_u64=$util.Long.fromValue(object.fixed_u64)).unsigned=false;else if(typeof object.fixed_u64==="string")message.fixed_u64=parseInt(object.fixed_u64,10);else if(typeof object.fixed_u64==="number")message.fixed_u64=object.fixed_u64;else if((0,_typeof2["default"])(object.fixed_u64)==="object")message.fixed_u64=new $util.LongBits(object.fixed_u64.low>>>0,object.fixed_u64.high>>>0).toNumber();if(object.fixed_i32!=null)message.fixed_i32=object.fixed_i32|0;if(object.fixed_i64!=null)if($util.Long)(message.fixed_i64=$util.Long.fromValue(object.fixed_i64)).unsigned=false;else if(typeof object.fixed_i64==="string")message.fixed_i64=parseInt(object.fixed_i64,10);else if(typeof object.fixed_i64==="number")message.fixed_i64=object.fixed_i64;else if((0,_typeof2["default"])(object.fixed_i64)==="object")message.fixed_i64=new $util.LongBits(object.fixed_i64.low>>>0,object.fixed_i64.high>>>0).toNumber();if(object.float_32!=null)message.float_32=Number(object.float_32);if(object.float_64!=null)message.float_64=Number(object.float_64);if(object["boolean"]!=null)message["boolean"]=Boolean(object["boolean"]);if(object.s_i32!=null)message.s_i32=object.s_i32|0;if(object.s_i64!=null)if($util.Long)(message.s_i64=$util.Long.fromValue(object.s_i64)).unsigned=false;else if(typeof object.s_i64==="string")message.s_i64=parseInt(object.s_i64,10);else if(typeof object.s_i64==="number")message.s_i64=object.s_i64;else if((0,_typeof2["default"])(object.s_i64)==="object")message.s_i64=new $util.LongBits(object.s_i64.low>>>0,object.s_i64.high>>>0).toNumber();if(object.bytes_field!=null)if(typeof object.bytes_field==="string")$util.base64.decode(object.bytes_field,message.bytes_field=$util.newBuffer($util.base64.length(object.bytes_field)),0);else if(object.bytes_field.length)message.bytes_field=object.bytes_field;if(object.string_field!=null)message.string_field=String(object.string_field);if(object.message_field!=null){if((0,_typeof2["default"])(object.message_field)!=="object")throw TypeError(".exonum.tests.TestProtobufConvert.message_field: object expected");message.message_field=$root.exonum.tests.Point.fromObject(object.message_field);}if(object.bit_vec!=null){if((0,_typeof2["default"])(object.bit_vec)!=="object")throw TypeError(".exonum.tests.TestProtobufConvert.bit_vec: object expected");message.bit_vec=$root.exonum.common.BitVec.fromObject(object.bit_vec);}if(object.time!=null){if((0,_typeof2["default"])(object.time)!=="object")throw TypeError(".exonum.tests.TestProtobufConvert.time: object expected");message.time=$root.google.protobuf.Timestamp.fromObject(object.time);}return message;};/**
* Creates a plain object from a TestProtobufConvert message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.tests.TestProtobufConvert
* @static
* @param {exonum.tests.TestProtobufConvert} message TestProtobufConvert
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/TestProtobufConvert.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.key=null;object.hash=null;object.unsigned_32=0;if($util.Long){var _long13=new $util.Long(0,0,true);object.unsigned_64=options.longs===String?_long13.toString():options.longs===Number?_long13.toNumber():_long13;}else object.unsigned_64=options.longs===String?"0":0;object.regular_i32=0;if($util.Long){var _long13=new $util.Long(0,0,false);object.regular_i64=options.longs===String?_long13.toString():options.longs===Number?_long13.toNumber():_long13;}else object.regular_i64=options.longs===String?"0":0;object.fixed_u32=0;if($util.Long){var _long13=new $util.Long(0,0,false);object.fixed_u64=options.longs===String?_long13.toString():options.longs===Number?_long13.toNumber():_long13;}else object.fixed_u64=options.longs===String?"0":0;object.fixed_i32=0;if($util.Long){var _long13=new $util.Long(0,0,false);object.fixed_i64=options.longs===String?_long13.toString():options.longs===Number?_long13.toNumber():_long13;}else object.fixed_i64=options.longs===String?"0":0;object.float_32=0;object.float_64=0;object["boolean"]=false;object.s_i32=0;if($util.Long){var _long13=new $util.Long(0,0,false);object.s_i64=options.longs===String?_long13.toString():options.longs===Number?_long13.toNumber():_long13;}else object.s_i64=options.longs===String?"0":0;if(options.bytes===String)object.bytes_field="";else{object.bytes_field=[];if(options.bytes!==Array)object.bytes_field=$util.newBuffer(object.bytes_field);}object.string_field="";object.message_field=null;object.bit_vec=null;object.time=null;}if(message.key!=null&&message.hasOwnProperty("key"))object.key=$root.exonum.crypto.PublicKey.toObject(message.key,options);if(message.hash!=null&&message.hasOwnProperty("hash"))object.hash=$root.exonum.crypto.Hash.toObject(message.hash,options);if(message.unsigned_32!=null&&message.hasOwnProperty("unsigned_32"))object.unsigned_32=message.unsigned_32;if(message.unsigned_64!=null&&message.hasOwnProperty("unsigned_64"))if(typeof message.unsigned_64==="number")object.unsigned_64=options.longs===String?String(message.unsigned_64):message.unsigned_64;else object.unsigned_64=options.longs===String?$util.Long.prototype.toString.call(message.unsigned_64):options.longs===Number?new $util.LongBits(message.unsigned_64.low>>>0,message.unsigned_64.high>>>0).toNumber(true):message.unsigned_64;if(message.regular_i32!=null&&message.hasOwnProperty("regular_i32"))object.regular_i32=message.regular_i32;if(message.regular_i64!=null&&message.hasOwnProperty("regular_i64"))if(typeof message.regular_i64==="number")object.regular_i64=options.longs===String?String(message.regular_i64):message.regular_i64;else object.regular_i64=options.longs===String?$util.Long.prototype.toString.call(message.regular_i64):options.longs===Number?new $util.LongBits(message.regular_i64.low>>>0,message.regular_i64.high>>>0).toNumber():message.regular_i64;if(message.fixed_u32!=null&&message.hasOwnProperty("fixed_u32"))object.fixed_u32=message.fixed_u32;if(message.fixed_u64!=null&&message.hasOwnProperty("fixed_u64"))if(typeof message.fixed_u64==="number")object.fixed_u64=options.longs===String?String(message.fixed_u64):message.fixed_u64;else object.fixed_u64=options.longs===String?$util.Long.prototype.toString.call(message.fixed_u64):options.longs===Number?new $util.LongBits(message.fixed_u64.low>>>0,message.fixed_u64.high>>>0).toNumber():message.fixed_u64;if(message.fixed_i32!=null&&message.hasOwnProperty("fixed_i32"))object.fixed_i32=message.fixed_i32;if(message.fixed_i64!=null&&message.hasOwnProperty("fixed_i64"))if(typeof message.fixed_i64==="number")object.fixed_i64=options.longs===String?String(message.fixed_i64):message.fixed_i64;else object.fixed_i64=options.longs===String?$util.Long.prototype.toString.call(message.fixed_i64):options.longs===Number?new $util.LongBits(message.fixed_i64.low>>>0,message.fixed_i64.high>>>0).toNumber():message.fixed_i64;if(message.float_32!=null&&message.hasOwnProperty("float_32"))object.float_32=options.json&&!isFinite(message.float_32)?String(message.float_32):message.float_32;if(message.float_64!=null&&message.hasOwnProperty("float_64"))object.float_64=options.json&&!isFinite(message.float_64)?String(message.float_64):message.float_64;if(message["boolean"]!=null&&message.hasOwnProperty("boolean"))object["boolean"]=message["boolean"];if(message.s_i32!=null&&message.hasOwnProperty("s_i32"))object.s_i32=message.s_i32;if(message.s_i64!=null&&message.hasOwnProperty("s_i64"))if(typeof message.s_i64==="number")object.s_i64=options.longs===String?String(message.s_i64):message.s_i64;else object.s_i64=options.longs===String?$util.Long.prototype.toString.call(message.s_i64):options.longs===Number?new $util.LongBits(message.s_i64.low>>>0,message.s_i64.high>>>0).toNumber():message.s_i64;if(message.bytes_field!=null&&message.hasOwnProperty("bytes_field"))object.bytes_field=options.bytes===String?$util.base64.encode(message.bytes_field,0,message.bytes_field.length):options.bytes===Array?Array.prototype.slice.call(message.bytes_field):message.bytes_field;if(message.string_field!=null&&message.hasOwnProperty("string_field"))object.string_field=message.string_field;if(message.message_field!=null&&message.hasOwnProperty("message_field"))object.message_field=$root.exonum.tests.Point.toObject(message.message_field,options);if(message.bit_vec!=null&&message.hasOwnProperty("bit_vec"))object.bit_vec=$root.exonum.common.BitVec.toObject(message.bit_vec,options);if(message.time!=null&&message.hasOwnProperty("time"))object.time=$root.google.protobuf.Timestamp.toObject(message.time,options);return object;};/**
* Converts this TestProtobufConvert to JSON.
* @function toJSON
* @memberof exonum.tests.TestProtobufConvert
* @instance
* @returns {Object.<string,*>} JSON object
*/TestProtobufConvert.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return TestProtobufConvert;}();tests.TestProtobufConvertRepeated=function(){/**
* Properties of a TestProtobufConvertRepeated.
* @memberof exonum.tests
* @interface ITestProtobufConvertRepeated
* @property {Array.<exonum.crypto.IPublicKey>|null} [keys] TestProtobufConvertRepeated keys
* @property {Array.<Uint8Array>|null} [bytes_array] TestProtobufConvertRepeated bytes_array
* @property {Array.<string>|null} [string_array] TestProtobufConvertRepeated string_array
* @property {Array.<number>|null} [num_array] TestProtobufConvertRepeated num_array
*/ /**
* Constructs a new TestProtobufConvertRepeated.
* @memberof exonum.tests
* @classdesc Represents a TestProtobufConvertRepeated.
* @implements ITestProtobufConvertRepeated
* @constructor
* @param {exonum.tests.ITestProtobufConvertRepeated=} [properties] Properties to set
*/function TestProtobufConvertRepeated(properties){this.keys=[];this.bytes_array=[];this.string_array=[];this.num_array=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* TestProtobufConvertRepeated keys.
* @member {Array.<exonum.crypto.IPublicKey>} keys
* @memberof exonum.tests.TestProtobufConvertRepeated
* @instance
*/TestProtobufConvertRepeated.prototype.keys=$util.emptyArray;/**
* TestProtobufConvertRepeated bytes_array.
* @member {Array.<Uint8Array>} bytes_array
* @memberof exonum.tests.TestProtobufConvertRepeated
* @instance
*/TestProtobufConvertRepeated.prototype.bytes_array=$util.emptyArray;/**
* TestProtobufConvertRepeated string_array.
* @member {Array.<string>} string_array
* @memberof exonum.tests.TestProtobufConvertRepeated
* @instance
*/TestProtobufConvertRepeated.prototype.string_array=$util.emptyArray;/**
* TestProtobufConvertRepeated num_array.
* @member {Array.<number>} num_array
* @memberof exonum.tests.TestProtobufConvertRepeated
* @instance
*/TestProtobufConvertRepeated.prototype.num_array=$util.emptyArray;/**
* Creates a new TestProtobufConvertRepeated instance using the specified properties.
* @function create
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {exonum.tests.ITestProtobufConvertRepeated=} [properties] Properties to set
* @returns {exonum.tests.TestProtobufConvertRepeated} TestProtobufConvertRepeated instance
*/TestProtobufConvertRepeated.create=function create(properties){return new TestProtobufConvertRepeated(properties);};/**
* Encodes the specified TestProtobufConvertRepeated message. Does not implicitly {@link exonum.tests.TestProtobufConvertRepeated.verify|verify} messages.
* @function encode
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {exonum.tests.ITestProtobufConvertRepeated} message TestProtobufConvertRepeated message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestProtobufConvertRepeated.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.keys!=null&&message.keys.length)for(var i=0;i<message.keys.length;++i){$root.exonum.crypto.PublicKey.encode(message.keys[i],writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();}if(message.bytes_array!=null&&message.bytes_array.length)for(var i=0;i<message.bytes_array.length;++i){writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.bytes_array[i]);}if(message.string_array!=null&&message.string_array.length)for(var i=0;i<message.string_array.length;++i){writer.uint32(/* id 3, wireType 2 =*/26).string(message.string_array[i]);}if(message.num_array!=null&&message.num_array.length){writer.uint32(/* id 4, wireType 2 =*/34).fork();for(var i=0;i<message.num_array.length;++i){writer.uint32(message.num_array[i]);}writer.ldelim();}return writer;};/**
* Encodes the specified TestProtobufConvertRepeated message, length delimited. Does not implicitly {@link exonum.tests.TestProtobufConvertRepeated.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {exonum.tests.ITestProtobufConvertRepeated} message TestProtobufConvertRepeated message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestProtobufConvertRepeated.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a TestProtobufConvertRepeated message from the specified reader or buffer.
* @function decode
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.tests.TestProtobufConvertRepeated} TestProtobufConvertRepeated
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestProtobufConvertRepeated.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.tests.TestProtobufConvertRepeated();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:if(!(message.keys&&message.keys.length))message.keys=[];message.keys.push($root.exonum.crypto.PublicKey.decode(reader,reader.uint32()));break;case 2:if(!(message.bytes_array&&message.bytes_array.length))message.bytes_array=[];message.bytes_array.push(reader.bytes());break;case 3:if(!(message.string_array&&message.string_array.length))message.string_array=[];message.string_array.push(reader.string());break;case 4:if(!(message.num_array&&message.num_array.length))message.num_array=[];if((tag&7)===2){var end2=reader.uint32()+reader.pos;while(reader.pos<end2){message.num_array.push(reader.uint32());}}else message.num_array.push(reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a TestProtobufConvertRepeated message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.tests.TestProtobufConvertRepeated} TestProtobufConvertRepeated
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestProtobufConvertRepeated.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a TestProtobufConvertRepeated message.
* @function verify
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/TestProtobufConvertRepeated.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.keys!=null&&message.hasOwnProperty("keys")){if(!Array.isArray(message.keys))return"keys: array expected";for(var i=0;i<message.keys.length;++i){var error=$root.exonum.crypto.PublicKey.verify(message.keys[i]);if(error)return"keys."+error;}}if(message.bytes_array!=null&&message.hasOwnProperty("bytes_array")){if(!Array.isArray(message.bytes_array))return"bytes_array: array expected";for(var i=0;i<message.bytes_array.length;++i){if(!(message.bytes_array[i]&&typeof message.bytes_array[i].length==="number"||$util.isString(message.bytes_array[i])))return"bytes_array: buffer[] expected";}}if(message.string_array!=null&&message.hasOwnProperty("string_array")){if(!Array.isArray(message.string_array))return"string_array: array expected";for(var i=0;i<message.string_array.length;++i){if(!$util.isString(message.string_array[i]))return"string_array: string[] expected";}}if(message.num_array!=null&&message.hasOwnProperty("num_array")){if(!Array.isArray(message.num_array))return"num_array: array expected";for(var i=0;i<message.num_array.length;++i){if(!$util.isInteger(message.num_array[i]))return"num_array: integer[] expected";}}return null;};/**
* Creates a TestProtobufConvertRepeated message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.tests.TestProtobufConvertRepeated} TestProtobufConvertRepeated
*/TestProtobufConvertRepeated.fromObject=function fromObject(object){if(object instanceof $root.exonum.tests.TestProtobufConvertRepeated)return object;var message=new $root.exonum.tests.TestProtobufConvertRepeated();if(object.keys){if(!Array.isArray(object.keys))throw TypeError(".exonum.tests.TestProtobufConvertRepeated.keys: array expected");message.keys=[];for(var i=0;i<object.keys.length;++i){if((0,_typeof2["default"])(object.keys[i])!=="object")throw TypeError(".exonum.tests.TestProtobufConvertRepeated.keys: object expected");message.keys[i]=$root.exonum.crypto.PublicKey.fromObject(object.keys[i]);}}if(object.bytes_array){if(!Array.isArray(object.bytes_array))throw TypeError(".exonum.tests.TestProtobufConvertRepeated.bytes_array: array expected");message.bytes_array=[];for(var i=0;i<object.bytes_array.length;++i){if(typeof object.bytes_array[i]==="string")$util.base64.decode(object.bytes_array[i],message.bytes_array[i]=$util.newBuffer($util.base64.length(object.bytes_array[i])),0);else if(object.bytes_array[i].length)message.bytes_array[i]=object.bytes_array[i];}}if(object.string_array){if(!Array.isArray(object.string_array))throw TypeError(".exonum.tests.TestProtobufConvertRepeated.string_array: array expected");message.string_array=[];for(var i=0;i<object.string_array.length;++i){message.string_array[i]=String(object.string_array[i]);}}if(object.num_array){if(!Array.isArray(object.num_array))throw TypeError(".exonum.tests.TestProtobufConvertRepeated.num_array: array expected");message.num_array=[];for(var i=0;i<object.num_array.length;++i){message.num_array[i]=object.num_array[i]>>>0;}}return message;};/**
* Creates a plain object from a TestProtobufConvertRepeated message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.tests.TestProtobufConvertRepeated
* @static
* @param {exonum.tests.TestProtobufConvertRepeated} message TestProtobufConvertRepeated
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/TestProtobufConvertRepeated.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults){object.keys=[];object.bytes_array=[];object.string_array=[];object.num_array=[];}if(message.keys&&message.keys.length){object.keys=[];for(var j=0;j<message.keys.length;++j){object.keys[j]=$root.exonum.crypto.PublicKey.toObject(message.keys[j],options);}}if(message.bytes_array&&message.bytes_array.length){object.bytes_array=[];for(var j=0;j<message.bytes_array.length;++j){object.bytes_array[j]=options.bytes===String?$util.base64.encode(message.bytes_array[j],0,message.bytes_array[j].length):options.bytes===Array?Array.prototype.slice.call(message.bytes_array[j]):message.bytes_array[j];}}if(message.string_array&&message.string_array.length){object.string_array=[];for(var j=0;j<message.string_array.length;++j){object.string_array[j]=message.string_array[j];}}if(message.num_array&&message.num_array.length){object.num_array=[];for(var j=0;j<message.num_array.length;++j){object.num_array[j]=message.num_array[j];}}return object;};/**
* Converts this TestProtobufConvertRepeated to JSON.
* @function toJSON
* @memberof exonum.tests.TestProtobufConvertRepeated
* @instance
* @returns {Object.<string,*>} JSON object
*/TestProtobufConvertRepeated.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return TestProtobufConvertRepeated;}();tests.TestProtobufConvertMap=function(){/**
* Properties of a TestProtobufConvertMap.
* @memberof exonum.tests
* @interface ITestProtobufConvertMap
* @property {Object.<string,number|Long>|null} [num_map] TestProtobufConvertMap num_map
* @property {Object.<string,string>|null} [string_map] TestProtobufConvertMap string_map
* @property {Object.<string,Uint8Array>|null} [bytes_map] TestProtobufConvertMap bytes_map
* @property {Object.<string,exonum.tests.IPoint>|null} [point_map] TestProtobufConvertMap point_map
* @property {Object.<string,number|Long>|null} [key_string_map] TestProtobufConvertMap key_string_map
*/ /**
* Constructs a new TestProtobufConvertMap.
* @memberof exonum.tests
* @classdesc Represents a TestProtobufConvertMap.
* @implements ITestProtobufConvertMap
* @constructor
* @param {exonum.tests.ITestProtobufConvertMap=} [properties] Properties to set
*/function TestProtobufConvertMap(properties){this.num_map={};this.string_map={};this.bytes_map={};this.point_map={};this.key_string_map={};if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* TestProtobufConvertMap num_map.
* @member {Object.<string,number|Long>} num_map
* @memberof exonum.tests.TestProtobufConvertMap
* @instance
*/TestProtobufConvertMap.prototype.num_map=$util.emptyObject;/**
* TestProtobufConvertMap string_map.
* @member {Object.<string,string>} string_map
* @memberof exonum.tests.TestProtobufConvertMap
* @instance
*/TestProtobufConvertMap.prototype.string_map=$util.emptyObject;/**
* TestProtobufConvertMap bytes_map.
* @member {Object.<string,Uint8Array>} bytes_map
* @memberof exonum.tests.TestProtobufConvertMap
* @instance
*/TestProtobufConvertMap.prototype.bytes_map=$util.emptyObject;/**
* TestProtobufConvertMap point_map.
* @member {Object.<string,exonum.tests.IPoint>} point_map
* @memberof exonum.tests.TestProtobufConvertMap
* @instance
*/TestProtobufConvertMap.prototype.point_map=$util.emptyObject;/**
* TestProtobufConvertMap key_string_map.
* @member {Object.<string,number|Long>} key_string_map
* @memberof exonum.tests.TestProtobufConvertMap
* @instance
*/TestProtobufConvertMap.prototype.key_string_map=$util.emptyObject;/**
* Creates a new TestProtobufConvertMap instance using the specified properties.
* @function create
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {exonum.tests.ITestProtobufConvertMap=} [properties] Properties to set
* @returns {exonum.tests.TestProtobufConvertMap} TestProtobufConvertMap instance
*/TestProtobufConvertMap.create=function create(properties){return new TestProtobufConvertMap(properties);};/**
* Encodes the specified TestProtobufConvertMap message. Does not implicitly {@link exonum.tests.TestProtobufConvertMap.verify|verify} messages.
* @function encode
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {exonum.tests.ITestProtobufConvertMap} message TestProtobufConvertMap message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestProtobufConvertMap.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.num_map!=null&&message.hasOwnProperty("num_map"))for(var keys=Object.keys(message.num_map),i=0;i<keys.length;++i){writer.uint32(/* id 1, wireType 2 =*/10).fork().uint32(/* id 1, wireType 0 =*/8).uint32(keys[i]).uint32(/* id 2, wireType 0 =*/16).uint64(message.num_map[keys[i]]).ldelim();}if(message.string_map!=null&&message.hasOwnProperty("string_map"))for(var keys=Object.keys(message.string_map),i=0;i<keys.length;++i){writer.uint32(/* id 2, wireType 2 =*/18).fork().uint32(/* id 1, wireType 0 =*/8).uint32(keys[i]).uint32(/* id 2, wireType 2 =*/18).string(message.string_map[keys[i]]).ldelim();}if(message.bytes_map!=null&&message.hasOwnProperty("bytes_map"))for(var keys=Object.keys(message.bytes_map),i=0;i<keys.length;++i){writer.uint32(/* id 4, wireType 2 =*/34).fork().uint32(/* id 1, wireType 0 =*/8).uint32(keys[i]).uint32(/* id 2, wireType 2 =*/18).bytes(message.bytes_map[keys[i]]).ldelim();}if(message.point_map!=null&&message.hasOwnProperty("point_map"))for(var keys=Object.keys(message.point_map),i=0;i<keys.length;++i){writer.uint32(/* id 5, wireType 2 =*/42).fork().uint32(/* id 1, wireType 0 =*/8).uint32(keys[i]);$root.exonum.tests.Point.encode(message.point_map[keys[i]],writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim().ldelim();}if(message.key_string_map!=null&&message.hasOwnProperty("key_string_map"))for(var keys=Object.keys(message.key_string_map),i=0;i<keys.length;++i){writer.uint32(/* id 6, wireType 2 =*/50).fork().uint32(/* id 1, wireType 2 =*/10).string(keys[i]).uint32(/* id 2, wireType 0 =*/16).uint64(message.key_string_map[keys[i]]).ldelim();}return writer;};/**
* Encodes the specified TestProtobufConvertMap message, length delimited. Does not implicitly {@link exonum.tests.TestProtobufConvertMap.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {exonum.tests.ITestProtobufConvertMap} message TestProtobufConvertMap message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestProtobufConvertMap.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a TestProtobufConvertMap message from the specified reader or buffer.
* @function decode
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.tests.TestProtobufConvertMap} TestProtobufConvertMap
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestProtobufConvertMap.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.tests.TestProtobufConvertMap(),key;while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:reader.skip().pos++;if(message.num_map===$util.emptyObject)message.num_map={};key=reader.uint32();reader.pos++;message.num_map[key]=reader.uint64();break;case 2:reader.skip().pos++;if(message.string_map===$util.emptyObject)message.string_map={};key=reader.uint32();reader.pos++;message.string_map[key]=reader.string();break;case 4:reader.skip().pos++;if(message.bytes_map===$util.emptyObject)message.bytes_map={};key=reader.uint32();reader.pos++;message.bytes_map[key]=reader.bytes();break;case 5:reader.skip().pos++;if(message.point_map===$util.emptyObject)message.point_map={};key=reader.uint32();reader.pos++;message.point_map[key]=$root.exonum.tests.Point.decode(reader,reader.uint32());break;case 6:reader.skip().pos++;if(message.key_string_map===$util.emptyObject)message.key_string_map={};key=reader.string();reader.pos++;message.key_string_map[key]=reader.uint64();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a TestProtobufConvertMap message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.tests.TestProtobufConvertMap} TestProtobufConvertMap
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestProtobufConvertMap.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a TestProtobufConvertMap message.
* @function verify
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/TestProtobufConvertMap.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.num_map!=null&&message.hasOwnProperty("num_map")){if(!$util.isObject(message.num_map))return"num_map: object expected";var key=Object.keys(message.num_map);for(var i=0;i<key.length;++i){if(!$util.key32Re.test(key[i]))return"num_map: integer key{k:uint32} expected";if(!$util.isInteger(message.num_map[key[i]])&&!(message.num_map[key[i]]&&$util.isInteger(message.num_map[key[i]].low)&&$util.isInteger(message.num_map[key[i]].high)))return"num_map: integer|Long{k:uint32} expected";}}if(message.string_map!=null&&message.hasOwnProperty("string_map")){if(!$util.isObject(message.string_map))return"string_map: object expected";var key=Object.keys(message.string_map);for(var i=0;i<key.length;++i){if(!$util.key32Re.test(key[i]))return"string_map: integer key{k:uint32} expected";if(!$util.isString(message.string_map[key[i]]))return"string_map: string{k:uint32} expected";}}if(message.bytes_map!=null&&message.hasOwnProperty("bytes_map")){if(!$util.isObject(message.bytes_map))return"bytes_map: object expected";var key=Object.keys(message.bytes_map);for(var i=0;i<key.length;++i){if(!$util.key32Re.test(key[i]))return"bytes_map: integer key{k:uint32} expected";if(!(message.bytes_map[key[i]]&&typeof message.bytes_map[key[i]].length==="number"||$util.isString(message.bytes_map[key[i]])))return"bytes_map: buffer{k:uint32} expected";}}if(message.point_map!=null&&message.hasOwnProperty("point_map")){if(!$util.isObject(message.point_map))return"point_map: object expected";var key=Object.keys(message.point_map);for(var i=0;i<key.length;++i){if(!$util.key32Re.test(key[i]))return"point_map: integer key{k:uint32} expected";{var error=$root.exonum.tests.Point.verify(message.point_map[key[i]]);if(error)return"point_map."+error;}}}if(message.key_string_map!=null&&message.hasOwnProperty("key_string_map")){if(!$util.isObject(message.key_string_map))return"key_string_map: object expected";var key=Object.keys(message.key_string_map);for(var i=0;i<key.length;++i){if(!$util.isInteger(message.key_string_map[key[i]])&&!(message.key_string_map[key[i]]&&$util.isInteger(message.key_string_map[key[i]].low)&&$util.isInteger(message.key_string_map[key[i]].high)))return"key_string_map: integer|Long{k:string} expected";}}return null;};/**
* Creates a TestProtobufConvertMap message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.tests.TestProtobufConvertMap} TestProtobufConvertMap
*/TestProtobufConvertMap.fromObject=function fromObject(object){if(object instanceof $root.exonum.tests.TestProtobufConvertMap)return object;var message=new $root.exonum.tests.TestProtobufConvertMap();if(object.num_map){if((0,_typeof2["default"])(object.num_map)!=="object")throw TypeError(".exonum.tests.TestProtobufConvertMap.num_map: object expected");message.num_map={};for(var keys=Object.keys(object.num_map),i=0;i<keys.length;++i){if($util.Long)(message.num_map[keys[i]]=$util.Long.fromValue(object.num_map[keys[i]])).unsigned=true;else if(typeof object.num_map[keys[i]]==="string")message.num_map[keys[i]]=parseInt(object.num_map[keys[i]],10);else if(typeof object.num_map[keys[i]]==="number")message.num_map[keys[i]]=object.num_map[keys[i]];else if((0,_typeof2["default"])(object.num_map[keys[i]])==="object")message.num_map[keys[i]]=new $util.LongBits(object.num_map[keys[i]].low>>>0,object.num_map[keys[i]].high>>>0).toNumber(true);}}if(object.string_map){if((0,_typeof2["default"])(object.string_map)!=="object")throw TypeError(".exonum.tests.TestProtobufConvertMap.string_map: object expected");message.string_map={};for(var keys=Object.keys(object.string_map),i=0;i<keys.length;++i){message.string_map[keys[i]]=String(object.string_map[keys[i]]);}}if(object.bytes_map){if((0,_typeof2["default"])(object.bytes_map)!=="object")throw TypeError(".exonum.tests.TestProtobufConvertMap.bytes_map: object expected");message.bytes_map={};for(var keys=Object.keys(object.bytes_map),i=0;i<keys.length;++i){if(typeof object.bytes_map[keys[i]]==="string")$util.base64.decode(object.bytes_map[keys[i]],message.bytes_map[keys[i]]=$util.newBuffer($util.base64.length(object.bytes_map[keys[i]])),0);else if(object.bytes_map[keys[i]].length)message.bytes_map[keys[i]]=object.bytes_map[keys[i]];}}if(object.point_map){if((0,_typeof2["default"])(object.point_map)!=="object")throw TypeError(".exonum.tests.TestProtobufConvertMap.point_map: object expected");message.point_map={};for(var keys=Object.keys(object.point_map),i=0;i<keys.length;++i){if((0,_typeof2["default"])(object.point_map[keys[i]])!=="object")throw TypeError(".exonum.tests.TestProtobufConvertMap.point_map: object expected");message.point_map[keys[i]]=$root.exonum.tests.Point.fromObject(object.point_map[keys[i]]);}}if(object.key_string_map){if((0,_typeof2["default"])(object.key_string_map)!=="object")throw TypeError(".exonum.tests.TestProtobufConvertMap.key_string_map: object expected");message.key_string_map={};for(var keys=Object.keys(object.key_string_map),i=0;i<keys.length;++i){if($util.Long)(message.key_string_map[keys[i]]=$util.Long.fromValue(object.key_string_map[keys[i]])).unsigned=true;else if(typeof object.key_string_map[keys[i]]==="string")message.key_string_map[keys[i]]=parseInt(object.key_string_map[keys[i]],10);else if(typeof object.key_string_map[keys[i]]==="number")message.key_string_map[keys[i]]=object.key_string_map[keys[i]];else if((0,_typeof2["default"])(object.key_string_map[keys[i]])==="object")message.key_string_map[keys[i]]=new $util.LongBits(object.key_string_map[keys[i]].low>>>0,object.key_string_map[keys[i]].high>>>0).toNumber(true);}}return message;};/**
* Creates a plain object from a TestProtobufConvertMap message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.tests.TestProtobufConvertMap
* @static
* @param {exonum.tests.TestProtobufConvertMap} message TestProtobufConvertMap
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/TestProtobufConvertMap.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.objects||options.defaults){object.num_map={};object.string_map={};object.bytes_map={};object.point_map={};object.key_string_map={};}var keys2;if(message.num_map&&(keys2=Object.keys(message.num_map)).length){object.num_map={};for(var j=0;j<keys2.length;++j){if(typeof message.num_map[keys2[j]]==="number")object.num_map[keys2[j]]=options.longs===String?String(message.num_map[keys2[j]]):message.num_map[keys2[j]];else object.num_map[keys2[j]]=options.longs===String?$util.Long.prototype.toString.call(message.num_map[keys2[j]]):options.longs===Number?new $util.LongBits(message.num_map[keys2[j]].low>>>0,message.num_map[keys2[j]].high>>>0).toNumber(true):message.num_map[keys2[j]];}}if(message.string_map&&(keys2=Object.keys(message.string_map)).length){object.string_map={};for(var j=0;j<keys2.length;++j){object.string_map[keys2[j]]=message.string_map[keys2[j]];}}if(message.bytes_map&&(keys2=Object.keys(message.bytes_map)).length){object.bytes_map={};for(var j=0;j<keys2.length;++j){object.bytes_map[keys2[j]]=options.bytes===String?$util.base64.encode(message.bytes_map[keys2[j]],0,message.bytes_map[keys2[j]].length):options.bytes===Array?Array.prototype.slice.call(message.bytes_map[keys2[j]]):message.bytes_map[keys2[j]];}}if(message.point_map&&(keys2=Object.keys(message.point_map)).length){object.point_map={};for(var j=0;j<keys2.length;++j){object.point_map[keys2[j]]=$root.exonum.tests.Point.toObject(message.point_map[keys2[j]],options);}}if(message.key_string_map&&(keys2=Object.keys(message.key_string_map)).length){object.key_string_map={};for(var j=0;j<keys2.length;++j){if(typeof message.key_string_map[keys2[j]]==="number")object.key_string_map[keys2[j]]=options.longs===String?String(message.key_string_map[keys2[j]]):message.key_string_map[keys2[j]];else object.key_string_map[keys2[j]]=options.longs===String?$util.Long.prototype.toString.call(message.key_string_map[keys2[j]]):options.longs===Number?new $util.LongBits(message.key_string_map[keys2[j]].low>>>0,message.key_string_map[keys2[j]].high>>>0).toNumber(true):message.key_string_map[keys2[j]];}}return object;};/**
* Converts this TestProtobufConvertMap to JSON.
* @function toJSON
* @memberof exonum.tests.TestProtobufConvertMap
* @instance
* @returns {Object.<string,*>} JSON object
*/TestProtobufConvertMap.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return TestProtobufConvertMap;}();tests.TestFixedArrays=function(){/**
* Properties of a TestFixedArrays.
* @memberof exonum.tests
* @interface ITestFixedArrays
* @property {Uint8Array|null} [fixed_array_8] TestFixedArrays fixed_array_8
* @property {Uint8Array|null} [fixed_array_16] TestFixedArrays fixed_array_16
* @property {Uint8Array|null} [fixed_array_32] TestFixedArrays fixed_array_32
*/ /**
* Constructs a new TestFixedArrays.
* @memberof exonum.tests
* @classdesc Represents a TestFixedArrays.
* @implements ITestFixedArrays
* @constructor
* @param {exonum.tests.ITestFixedArrays=} [properties] Properties to set
*/function TestFixedArrays(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* TestFixedArrays fixed_array_8.
* @member {Uint8Array} fixed_array_8
* @memberof exonum.tests.TestFixedArrays
* @instance
*/TestFixedArrays.prototype.fixed_array_8=$util.newBuffer([]);/**
* TestFixedArrays fixed_array_16.
* @member {Uint8Array} fixed_array_16
* @memberof exonum.tests.TestFixedArrays
* @instance
*/TestFixedArrays.prototype.fixed_array_16=$util.newBuffer([]);/**
* TestFixedArrays fixed_array_32.
* @member {Uint8Array} fixed_array_32
* @memberof exonum.tests.TestFixedArrays
* @instance
*/TestFixedArrays.prototype.fixed_array_32=$util.newBuffer([]);/**
* Creates a new TestFixedArrays instance using the specified properties.
* @function create
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {exonum.tests.ITestFixedArrays=} [properties] Properties to set
* @returns {exonum.tests.TestFixedArrays} TestFixedArrays instance
*/TestFixedArrays.create=function create(properties){return new TestFixedArrays(properties);};/**
* Encodes the specified TestFixedArrays message. Does not implicitly {@link exonum.tests.TestFixedArrays.verify|verify} messages.
* @function encode
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {exonum.tests.ITestFixedArrays} message TestFixedArrays message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestFixedArrays.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.fixed_array_8!=null&&message.hasOwnProperty("fixed_array_8"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.fixed_array_8);if(message.fixed_array_16!=null&&message.hasOwnProperty("fixed_array_16"))writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.fixed_array_16);if(message.fixed_array_32!=null&&message.hasOwnProperty("fixed_array_32"))writer.uint32(/* id 3, wireType 2 =*/26).bytes(message.fixed_array_32);return writer;};/**
* Encodes the specified TestFixedArrays message, length delimited. Does not implicitly {@link exonum.tests.TestFixedArrays.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {exonum.tests.ITestFixedArrays} message TestFixedArrays message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/TestFixedArrays.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a TestFixedArrays message from the specified reader or buffer.
* @function decode
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.tests.TestFixedArrays} TestFixedArrays
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestFixedArrays.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.tests.TestFixedArrays();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.fixed_array_8=reader.bytes();break;case 2:message.fixed_array_16=reader.bytes();break;case 3:message.fixed_array_32=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a TestFixedArrays message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.tests.TestFixedArrays} TestFixedArrays
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/TestFixedArrays.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a TestFixedArrays message.
* @function verify
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/TestFixedArrays.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.fixed_array_8!=null&&message.hasOwnProperty("fixed_array_8"))if(!(message.fixed_array_8&&typeof message.fixed_array_8.length==="number"||$util.isString(message.fixed_array_8)))return"fixed_array_8: buffer expected";if(message.fixed_array_16!=null&&message.hasOwnProperty("fixed_array_16"))if(!(message.fixed_array_16&&typeof message.fixed_array_16.length==="number"||$util.isString(message.fixed_array_16)))return"fixed_array_16: buffer expected";if(message.fixed_array_32!=null&&message.hasOwnProperty("fixed_array_32"))if(!(message.fixed_array_32&&typeof message.fixed_array_32.length==="number"||$util.isString(message.fixed_array_32)))return"fixed_array_32: buffer expected";return null;};/**
* Creates a TestFixedArrays message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.tests.TestFixedArrays} TestFixedArrays
*/TestFixedArrays.fromObject=function fromObject(object){if(object instanceof $root.exonum.tests.TestFixedArrays)return object;var message=new $root.exonum.tests.TestFixedArrays();if(object.fixed_array_8!=null)if(typeof object.fixed_array_8==="string")$util.base64.decode(object.fixed_array_8,message.fixed_array_8=$util.newBuffer($util.base64.length(object.fixed_array_8)),0);else if(object.fixed_array_8.length)message.fixed_array_8=object.fixed_array_8;if(object.fixed_array_16!=null)if(typeof object.fixed_array_16==="string")$util.base64.decode(object.fixed_array_16,message.fixed_array_16=$util.newBuffer($util.base64.length(object.fixed_array_16)),0);else if(object.fixed_array_16.length)message.fixed_array_16=object.fixed_array_16;if(object.fixed_array_32!=null)if(typeof object.fixed_array_32==="string")$util.base64.decode(object.fixed_array_32,message.fixed_array_32=$util.newBuffer($util.base64.length(object.fixed_array_32)),0);else if(object.fixed_array_32.length)message.fixed_array_32=object.fixed_array_32;return message;};/**
* Creates a plain object from a TestFixedArrays message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.tests.TestFixedArrays
* @static
* @param {exonum.tests.TestFixedArrays} message TestFixedArrays
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/TestFixedArrays.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if(options.bytes===String)object.fixed_array_8="";else{object.fixed_array_8=[];if(options.bytes!==Array)object.fixed_array_8=$util.newBuffer(object.fixed_array_8);}if(options.bytes===String)object.fixed_array_16="";else{object.fixed_array_16=[];if(options.bytes!==Array)object.fixed_array_16=$util.newBuffer(object.fixed_array_16);}if(options.bytes===String)object.fixed_array_32="";else{object.fixed_array_32=[];if(options.bytes!==Array)object.fixed_array_32=$util.newBuffer(object.fixed_array_32);}}if(message.fixed_array_8!=null&&message.hasOwnProperty("fixed_array_8"))object.fixed_array_8=options.bytes===String?$util.base64.encode(message.fixed_array_8,0,message.fixed_array_8.length):options.bytes===Array?Array.prototype.slice.call(message.fixed_array_8):message.fixed_array_8;if(message.fixed_array_16!=null&&message.hasOwnProperty("fixed_array_16"))object.fixed_array_16=options.bytes===String?$util.base64.encode(message.fixed_array_16,0,message.fixed_array_16.length):options.bytes===Array?Array.prototype.slice.call(message.fixed_array_16):message.fixed_array_16;if(message.fixed_array_32!=null&&message.hasOwnProperty("fixed_array_32"))object.fixed_array_32=options.bytes===String?$util.base64.encode(message.fixed_array_32,0,message.fixed_array_32.length):options.bytes===Array?Array.prototype.slice.call(message.fixed_array_32):message.fixed_array_32;return object;};/**
* Converts this TestFixedArrays to JSON.
* @function toJSON
* @memberof exonum.tests.TestFixedArrays
* @instance
* @returns {Object.<string,*>} JSON object
*/TestFixedArrays.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return TestFixedArrays;}();return tests;}();exonum.proof=function(){/**
* Namespace proof.
* @memberof exonum
* @namespace
*/var proof={};proof.ListProof=function(){/**
* Properties of a ListProof.
* @memberof exonum.proof
* @interface IListProof
* @property {Array.<exonum.proof.IHashedEntry>|null} [proof] ListProof proof
* @property {Array.<exonum.proof.IListProofEntry>|null} [entries] ListProof entries
* @property {number|Long|null} [length] ListProof length
*/ /**
* Constructs a new ListProof.
* @memberof exonum.proof
* @classdesc Represents a ListProof.
* @implements IListProof
* @constructor
* @param {exonum.proof.IListProof=} [properties] Properties to set
*/function ListProof(properties){this.proof=[];this.entries=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ListProof proof.
* @member {Array.<exonum.proof.IHashedEntry>} proof
* @memberof exonum.proof.ListProof
* @instance
*/ListProof.prototype.proof=$util.emptyArray;/**
* ListProof entries.
* @member {Array.<exonum.proof.IListProofEntry>} entries
* @memberof exonum.proof.ListProof
* @instance
*/ListProof.prototype.entries=$util.emptyArray;/**
* ListProof length.
* @member {number|Long} length
* @memberof exonum.proof.ListProof
* @instance
*/ListProof.prototype.length=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* Creates a new ListProof instance using the specified properties.
* @function create
* @memberof exonum.proof.ListProof
* @static
* @param {exonum.proof.IListProof=} [properties] Properties to set
* @returns {exonum.proof.ListProof} ListProof instance
*/ListProof.create=function create(properties){return new ListProof(properties);};/**
* Encodes the specified ListProof message. Does not implicitly {@link exonum.proof.ListProof.verify|verify} messages.
* @function encode
* @memberof exonum.proof.ListProof
* @static
* @param {exonum.proof.IListProof} message ListProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ListProof.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.proof!=null&&message.proof.length)for(var i=0;i<message.proof.length;++i){$root.exonum.proof.HashedEntry.encode(message.proof[i],writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();}if(message.entries!=null&&message.entries.length)for(var i=0;i<message.entries.length;++i){$root.exonum.proof.ListProofEntry.encode(message.entries[i],writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();}if(message.length!=null&&message.hasOwnProperty("length"))writer.uint32(/* id 3, wireType 0 =*/24).uint64(message.length);return writer;};/**
* Encodes the specified ListProof message, length delimited. Does not implicitly {@link exonum.proof.ListProof.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proof.ListProof
* @static
* @param {exonum.proof.IListProof} message ListProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ListProof.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a ListProof message from the specified reader or buffer.
* @function decode
* @memberof exonum.proof.ListProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proof.ListProof} ListProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ListProof.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proof.ListProof();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:if(!(message.proof&&message.proof.length))message.proof=[];message.proof.push($root.exonum.proof.HashedEntry.decode(reader,reader.uint32()));break;case 2:if(!(message.entries&&message.entries.length))message.entries=[];message.entries.push($root.exonum.proof.ListProofEntry.decode(reader,reader.uint32()));break;case 3:message.length=reader.uint64();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a ListProof message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proof.ListProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proof.ListProof} ListProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ListProof.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a ListProof message.
* @function verify
* @memberof exonum.proof.ListProof
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ListProof.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.proof!=null&&message.hasOwnProperty("proof")){if(!Array.isArray(message.proof))return"proof: array expected";for(var i=0;i<message.proof.length;++i){var error=$root.exonum.proof.HashedEntry.verify(message.proof[i]);if(error)return"proof."+error;}}if(message.entries!=null&&message.hasOwnProperty("entries")){if(!Array.isArray(message.entries))return"entries: array expected";for(var i=0;i<message.entries.length;++i){var error=$root.exonum.proof.ListProofEntry.verify(message.entries[i]);if(error)return"entries."+error;}}if(message.length!=null&&message.hasOwnProperty("length"))if(!$util.isInteger(message.length)&&!(message.length&&$util.isInteger(message.length.low)&&$util.isInteger(message.length.high)))return"length: integer|Long expected";return null;};/**
* Creates a ListProof message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proof.ListProof
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proof.ListProof} ListProof
*/ListProof.fromObject=function fromObject(object){if(object instanceof $root.exonum.proof.ListProof)return object;var message=new $root.exonum.proof.ListProof();if(object.proof){if(!Array.isArray(object.proof))throw TypeError(".exonum.proof.ListProof.proof: array expected");message.proof=[];for(var i=0;i<object.proof.length;++i){if((0,_typeof2["default"])(object.proof[i])!=="object")throw TypeError(".exonum.proof.ListProof.proof: object expected");message.proof[i]=$root.exonum.proof.HashedEntry.fromObject(object.proof[i]);}}if(object.entries){if(!Array.isArray(object.entries))throw TypeError(".exonum.proof.ListProof.entries: array expected");message.entries=[];for(var i=0;i<object.entries.length;++i){if((0,_typeof2["default"])(object.entries[i])!=="object")throw TypeError(".exonum.proof.ListProof.entries: object expected");message.entries[i]=$root.exonum.proof.ListProofEntry.fromObject(object.entries[i]);}}if(object.length!=null)if($util.Long)(message.length=$util.Long.fromValue(object.length)).unsigned=true;else if(typeof object.length==="string")message.length=parseInt(object.length,10);else if(typeof object.length==="number")message.length=object.length;else if((0,_typeof2["default"])(object.length)==="object")message.length=new $util.LongBits(object.length.low>>>0,object.length.high>>>0).toNumber(true);return message;};/**
* Creates a plain object from a ListProof message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proof.ListProof
* @static
* @param {exonum.proof.ListProof} message ListProof
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ListProof.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults){object.proof=[];object.entries=[];}if(options.defaults)if($util.Long){var _long14=new $util.Long(0,0,true);object.length=options.longs===String?_long14.toString():options.longs===Number?_long14.toNumber():_long14;}else object.length=options.longs===String?"0":0;if(message.proof&&message.proof.length){object.proof=[];for(var j=0;j<message.proof.length;++j){object.proof[j]=$root.exonum.proof.HashedEntry.toObject(message.proof[j],options);}}if(message.entries&&message.entries.length){object.entries=[];for(var j=0;j<message.entries.length;++j){object.entries[j]=$root.exonum.proof.ListProofEntry.toObject(message.entries[j],options);}}if(message.length!=null&&message.hasOwnProperty("length"))if(typeof message.length==="number")object.length=options.longs===String?String(message.length):message.length;else object.length=options.longs===String?$util.Long.prototype.toString.call(message.length):options.longs===Number?new $util.LongBits(message.length.low>>>0,message.length.high>>>0).toNumber(true):message.length;return object;};/**
* Converts this ListProof to JSON.
* @function toJSON
* @memberof exonum.proof.ListProof
* @instance
* @returns {Object.<string,*>} JSON object
*/ListProof.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ListProof;}();proof.HashedEntry=function(){/**
* Properties of a HashedEntry.
* @memberof exonum.proof
* @interface IHashedEntry
* @property {exonum.proof.IProofListKey|null} [key] HashedEntry key
* @property {exonum.crypto.IHash|null} [hash] HashedEntry hash
*/ /**
* Constructs a new HashedEntry.
* @memberof exonum.proof
* @classdesc Represents a HashedEntry.
* @implements IHashedEntry
* @constructor
* @param {exonum.proof.IHashedEntry=} [properties] Properties to set
*/function HashedEntry(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* HashedEntry key.
* @member {exonum.proof.IProofListKey|null|undefined} key
* @memberof exonum.proof.HashedEntry
* @instance
*/HashedEntry.prototype.key=null;/**
* HashedEntry hash.
* @member {exonum.crypto.IHash|null|undefined} hash
* @memberof exonum.proof.HashedEntry
* @instance
*/HashedEntry.prototype.hash=null;/**
* Creates a new HashedEntry instance using the specified properties.
* @function create
* @memberof exonum.proof.HashedEntry
* @static
* @param {exonum.proof.IHashedEntry=} [properties] Properties to set
* @returns {exonum.proof.HashedEntry} HashedEntry instance
*/HashedEntry.create=function create(properties){return new HashedEntry(properties);};/**
* Encodes the specified HashedEntry message. Does not implicitly {@link exonum.proof.HashedEntry.verify|verify} messages.
* @function encode
* @memberof exonum.proof.HashedEntry
* @static
* @param {exonum.proof.IHashedEntry} message HashedEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/HashedEntry.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.key!=null&&message.hasOwnProperty("key"))$root.exonum.proof.ProofListKey.encode(message.key,writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();if(message.hash!=null&&message.hasOwnProperty("hash"))$root.exonum.crypto.Hash.encode(message.hash,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();return writer;};/**
* Encodes the specified HashedEntry message, length delimited. Does not implicitly {@link exonum.proof.HashedEntry.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proof.HashedEntry
* @static
* @param {exonum.proof.IHashedEntry} message HashedEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/HashedEntry.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a HashedEntry message from the specified reader or buffer.
* @function decode
* @memberof exonum.proof.HashedEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proof.HashedEntry} HashedEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/HashedEntry.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proof.HashedEntry();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.key=$root.exonum.proof.ProofListKey.decode(reader,reader.uint32());break;case 2:message.hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a HashedEntry message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proof.HashedEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proof.HashedEntry} HashedEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/HashedEntry.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a HashedEntry message.
* @function verify
* @memberof exonum.proof.HashedEntry
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/HashedEntry.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.key!=null&&message.hasOwnProperty("key")){var error=$root.exonum.proof.ProofListKey.verify(message.key);if(error)return"key."+error;}if(message.hash!=null&&message.hasOwnProperty("hash")){var error=$root.exonum.crypto.Hash.verify(message.hash);if(error)return"hash."+error;}return null;};/**
* Creates a HashedEntry message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proof.HashedEntry
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proof.HashedEntry} HashedEntry
*/HashedEntry.fromObject=function fromObject(object){if(object instanceof $root.exonum.proof.HashedEntry)return object;var message=new $root.exonum.proof.HashedEntry();if(object.key!=null){if((0,_typeof2["default"])(object.key)!=="object")throw TypeError(".exonum.proof.HashedEntry.key: object expected");message.key=$root.exonum.proof.ProofListKey.fromObject(object.key);}if(object.hash!=null){if((0,_typeof2["default"])(object.hash)!=="object")throw TypeError(".exonum.proof.HashedEntry.hash: object expected");message.hash=$root.exonum.crypto.Hash.fromObject(object.hash);}return message;};/**
* Creates a plain object from a HashedEntry message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proof.HashedEntry
* @static
* @param {exonum.proof.HashedEntry} message HashedEntry
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/HashedEntry.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){object.key=null;object.hash=null;}if(message.key!=null&&message.hasOwnProperty("key"))object.key=$root.exonum.proof.ProofListKey.toObject(message.key,options);if(message.hash!=null&&message.hasOwnProperty("hash"))object.hash=$root.exonum.crypto.Hash.toObject(message.hash,options);return object;};/**
* Converts this HashedEntry to JSON.
* @function toJSON
* @memberof exonum.proof.HashedEntry
* @instance
* @returns {Object.<string,*>} JSON object
*/HashedEntry.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return HashedEntry;}();proof.ListProofEntry=function(){/**
* Properties of a ListProofEntry.
* @memberof exonum.proof
* @interface IListProofEntry
* @property {number|Long|null} [index] ListProofEntry index
* @property {Uint8Array|null} [value] ListProofEntry value
*/ /**
* Constructs a new ListProofEntry.
* @memberof exonum.proof
* @classdesc Represents a ListProofEntry.
* @implements IListProofEntry
* @constructor
* @param {exonum.proof.IListProofEntry=} [properties] Properties to set
*/function ListProofEntry(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ListProofEntry index.
* @member {number|Long} index
* @memberof exonum.proof.ListProofEntry
* @instance
*/ListProofEntry.prototype.index=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* ListProofEntry value.
* @member {Uint8Array} value
* @memberof exonum.proof.ListProofEntry
* @instance
*/ListProofEntry.prototype.value=$util.newBuffer([]);/**
* Creates a new ListProofEntry instance using the specified properties.
* @function create
* @memberof exonum.proof.ListProofEntry
* @static
* @param {exonum.proof.IListProofEntry=} [properties] Properties to set
* @returns {exonum.proof.ListProofEntry} ListProofEntry instance
*/ListProofEntry.create=function create(properties){return new ListProofEntry(properties);};/**
* Encodes the specified ListProofEntry message. Does not implicitly {@link exonum.proof.ListProofEntry.verify|verify} messages.
* @function encode
* @memberof exonum.proof.ListProofEntry
* @static
* @param {exonum.proof.IListProofEntry} message ListProofEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ListProofEntry.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.index!=null&&message.hasOwnProperty("index"))writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.index);if(message.value!=null&&message.hasOwnProperty("value"))writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.value);return writer;};/**
* Encodes the specified ListProofEntry message, length delimited. Does not implicitly {@link exonum.proof.ListProofEntry.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proof.ListProofEntry
* @static
* @param {exonum.proof.IListProofEntry} message ListProofEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ListProofEntry.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a ListProofEntry message from the specified reader or buffer.
* @function decode
* @memberof exonum.proof.ListProofEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proof.ListProofEntry} ListProofEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ListProofEntry.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proof.ListProofEntry();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.index=reader.uint64();break;case 2:message.value=reader.bytes();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a ListProofEntry message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proof.ListProofEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proof.ListProofEntry} ListProofEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ListProofEntry.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a ListProofEntry message.
* @function verify
* @memberof exonum.proof.ListProofEntry
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ListProofEntry.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.index!=null&&message.hasOwnProperty("index"))if(!$util.isInteger(message.index)&&!(message.index&&$util.isInteger(message.index.low)&&$util.isInteger(message.index.high)))return"index: integer|Long expected";if(message.value!=null&&message.hasOwnProperty("value"))if(!(message.value&&typeof message.value.length==="number"||$util.isString(message.value)))return"value: buffer expected";return null;};/**
* Creates a ListProofEntry message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proof.ListProofEntry
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proof.ListProofEntry} ListProofEntry
*/ListProofEntry.fromObject=function fromObject(object){if(object instanceof $root.exonum.proof.ListProofEntry)return object;var message=new $root.exonum.proof.ListProofEntry();if(object.index!=null)if($util.Long)(message.index=$util.Long.fromValue(object.index)).unsigned=true;else if(typeof object.index==="string")message.index=parseInt(object.index,10);else if(typeof object.index==="number")message.index=object.index;else if((0,_typeof2["default"])(object.index)==="object")message.index=new $util.LongBits(object.index.low>>>0,object.index.high>>>0).toNumber(true);if(object.value!=null)if(typeof object.value==="string")$util.base64.decode(object.value,message.value=$util.newBuffer($util.base64.length(object.value)),0);else if(object.value.length)message.value=object.value;return message;};/**
* Creates a plain object from a ListProofEntry message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proof.ListProofEntry
* @static
* @param {exonum.proof.ListProofEntry} message ListProofEntry
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ListProofEntry.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if($util.Long){var _long15=new $util.Long(0,0,true);object.index=options.longs===String?_long15.toString():options.longs===Number?_long15.toNumber():_long15;}else object.index=options.longs===String?"0":0;if(options.bytes===String)object.value="";else{object.value=[];if(options.bytes!==Array)object.value=$util.newBuffer(object.value);}}if(message.index!=null&&message.hasOwnProperty("index"))if(typeof message.index==="number")object.index=options.longs===String?String(message.index):message.index;else object.index=options.longs===String?$util.Long.prototype.toString.call(message.index):options.longs===Number?new $util.LongBits(message.index.low>>>0,message.index.high>>>0).toNumber(true):message.index;if(message.value!=null&&message.hasOwnProperty("value"))object.value=options.bytes===String?$util.base64.encode(message.value,0,message.value.length):options.bytes===Array?Array.prototype.slice.call(message.value):message.value;return object;};/**
* Converts this ListProofEntry to JSON.
* @function toJSON
* @memberof exonum.proof.ListProofEntry
* @instance
* @returns {Object.<string,*>} JSON object
*/ListProofEntry.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ListProofEntry;}();proof.ProofListKey=function(){/**
* Properties of a ProofListKey.
* @memberof exonum.proof
* @interface IProofListKey
* @property {number|Long|null} [index] ProofListKey index
* @property {number|null} [height] ProofListKey height
*/ /**
* Constructs a new ProofListKey.
* @memberof exonum.proof
* @classdesc Represents a ProofListKey.
* @implements IProofListKey
* @constructor
* @param {exonum.proof.IProofListKey=} [properties] Properties to set
*/function ProofListKey(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* ProofListKey index.
* @member {number|Long} index
* @memberof exonum.proof.ProofListKey
* @instance
*/ProofListKey.prototype.index=$util.Long?$util.Long.fromBits(0,0,true):0;/**
* ProofListKey height.
* @member {number} height
* @memberof exonum.proof.ProofListKey
* @instance
*/ProofListKey.prototype.height=0;/**
* Creates a new ProofListKey instance using the specified properties.
* @function create
* @memberof exonum.proof.ProofListKey
* @static
* @param {exonum.proof.IProofListKey=} [properties] Properties to set
* @returns {exonum.proof.ProofListKey} ProofListKey instance
*/ProofListKey.create=function create(properties){return new ProofListKey(properties);};/**
* Encodes the specified ProofListKey message. Does not implicitly {@link exonum.proof.ProofListKey.verify|verify} messages.
* @function encode
* @memberof exonum.proof.ProofListKey
* @static
* @param {exonum.proof.IProofListKey} message ProofListKey message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ProofListKey.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.index!=null&&message.hasOwnProperty("index"))writer.uint32(/* id 1, wireType 0 =*/8).uint64(message.index);if(message.height!=null&&message.hasOwnProperty("height"))writer.uint32(/* id 2, wireType 0 =*/16).uint32(message.height);return writer;};/**
* Encodes the specified ProofListKey message, length delimited. Does not implicitly {@link exonum.proof.ProofListKey.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proof.ProofListKey
* @static
* @param {exonum.proof.IProofListKey} message ProofListKey message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/ProofListKey.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a ProofListKey message from the specified reader or buffer.
* @function decode
* @memberof exonum.proof.ProofListKey
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proof.ProofListKey} ProofListKey
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ProofListKey.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proof.ProofListKey();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.index=reader.uint64();break;case 2:message.height=reader.uint32();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a ProofListKey message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proof.ProofListKey
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proof.ProofListKey} ProofListKey
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/ProofListKey.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a ProofListKey message.
* @function verify
* @memberof exonum.proof.ProofListKey
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/ProofListKey.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.index!=null&&message.hasOwnProperty("index"))if(!$util.isInteger(message.index)&&!(message.index&&$util.isInteger(message.index.low)&&$util.isInteger(message.index.high)))return"index: integer|Long expected";if(message.height!=null&&message.hasOwnProperty("height"))if(!$util.isInteger(message.height))return"height: integer expected";return null;};/**
* Creates a ProofListKey message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proof.ProofListKey
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proof.ProofListKey} ProofListKey
*/ProofListKey.fromObject=function fromObject(object){if(object instanceof $root.exonum.proof.ProofListKey)return object;var message=new $root.exonum.proof.ProofListKey();if(object.index!=null)if($util.Long)(message.index=$util.Long.fromValue(object.index)).unsigned=true;else if(typeof object.index==="string")message.index=parseInt(object.index,10);else if(typeof object.index==="number")message.index=object.index;else if((0,_typeof2["default"])(object.index)==="object")message.index=new $util.LongBits(object.index.low>>>0,object.index.high>>>0).toNumber(true);if(object.height!=null)message.height=object.height>>>0;return message;};/**
* Creates a plain object from a ProofListKey message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proof.ProofListKey
* @static
* @param {exonum.proof.ProofListKey} message ProofListKey
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/ProofListKey.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if($util.Long){var _long16=new $util.Long(0,0,true);object.index=options.longs===String?_long16.toString():options.longs===Number?_long16.toNumber():_long16;}else object.index=options.longs===String?"0":0;object.height=0;}if(message.index!=null&&message.hasOwnProperty("index"))if(typeof message.index==="number")object.index=options.longs===String?String(message.index):message.index;else object.index=options.longs===String?$util.Long.prototype.toString.call(message.index):options.longs===Number?new $util.LongBits(message.index.low>>>0,message.index.high>>>0).toNumber(true):message.index;if(message.height!=null&&message.hasOwnProperty("height"))object.height=message.height;return object;};/**
* Converts this ProofListKey to JSON.
* @function toJSON
* @memberof exonum.proof.ProofListKey
* @instance
* @returns {Object.<string,*>} JSON object
*/ProofListKey.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return ProofListKey;}();proof.MapProof=function(){/**
* Properties of a MapProof.
* @memberof exonum.proof
* @interface IMapProof
* @property {Array.<exonum.proof.IOptionalEntry>|null} [entries] MapProof entries
* @property {Array.<exonum.proof.IMapProofEntry>|null} [proof] MapProof proof
*/ /**
* Constructs a new MapProof.
* @memberof exonum.proof
* @classdesc Represents a MapProof.
* @implements IMapProof
* @constructor
* @param {exonum.proof.IMapProof=} [properties] Properties to set
*/function MapProof(properties){this.entries=[];this.proof=[];if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* MapProof entries.
* @member {Array.<exonum.proof.IOptionalEntry>} entries
* @memberof exonum.proof.MapProof
* @instance
*/MapProof.prototype.entries=$util.emptyArray;/**
* MapProof proof.
* @member {Array.<exonum.proof.IMapProofEntry>} proof
* @memberof exonum.proof.MapProof
* @instance
*/MapProof.prototype.proof=$util.emptyArray;/**
* Creates a new MapProof instance using the specified properties.
* @function create
* @memberof exonum.proof.MapProof
* @static
* @param {exonum.proof.IMapProof=} [properties] Properties to set
* @returns {exonum.proof.MapProof} MapProof instance
*/MapProof.create=function create(properties){return new MapProof(properties);};/**
* Encodes the specified MapProof message. Does not implicitly {@link exonum.proof.MapProof.verify|verify} messages.
* @function encode
* @memberof exonum.proof.MapProof
* @static
* @param {exonum.proof.IMapProof} message MapProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/MapProof.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.entries!=null&&message.entries.length)for(var i=0;i<message.entries.length;++i){$root.exonum.proof.OptionalEntry.encode(message.entries[i],writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim();}if(message.proof!=null&&message.proof.length)for(var i=0;i<message.proof.length;++i){$root.exonum.proof.MapProofEntry.encode(message.proof[i],writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();}return writer;};/**
* Encodes the specified MapProof message, length delimited. Does not implicitly {@link exonum.proof.MapProof.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proof.MapProof
* @static
* @param {exonum.proof.IMapProof} message MapProof message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/MapProof.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a MapProof message from the specified reader or buffer.
* @function decode
* @memberof exonum.proof.MapProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proof.MapProof} MapProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/MapProof.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proof.MapProof();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:if(!(message.entries&&message.entries.length))message.entries=[];message.entries.push($root.exonum.proof.OptionalEntry.decode(reader,reader.uint32()));break;case 2:if(!(message.proof&&message.proof.length))message.proof=[];message.proof.push($root.exonum.proof.MapProofEntry.decode(reader,reader.uint32()));break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a MapProof message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proof.MapProof
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proof.MapProof} MapProof
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/MapProof.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a MapProof message.
* @function verify
* @memberof exonum.proof.MapProof
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/MapProof.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.entries!=null&&message.hasOwnProperty("entries")){if(!Array.isArray(message.entries))return"entries: array expected";for(var i=0;i<message.entries.length;++i){var error=$root.exonum.proof.OptionalEntry.verify(message.entries[i]);if(error)return"entries."+error;}}if(message.proof!=null&&message.hasOwnProperty("proof")){if(!Array.isArray(message.proof))return"proof: array expected";for(var i=0;i<message.proof.length;++i){var error=$root.exonum.proof.MapProofEntry.verify(message.proof[i]);if(error)return"proof."+error;}}return null;};/**
* Creates a MapProof message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proof.MapProof
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proof.MapProof} MapProof
*/MapProof.fromObject=function fromObject(object){if(object instanceof $root.exonum.proof.MapProof)return object;var message=new $root.exonum.proof.MapProof();if(object.entries){if(!Array.isArray(object.entries))throw TypeError(".exonum.proof.MapProof.entries: array expected");message.entries=[];for(var i=0;i<object.entries.length;++i){if((0,_typeof2["default"])(object.entries[i])!=="object")throw TypeError(".exonum.proof.MapProof.entries: object expected");message.entries[i]=$root.exonum.proof.OptionalEntry.fromObject(object.entries[i]);}}if(object.proof){if(!Array.isArray(object.proof))throw TypeError(".exonum.proof.MapProof.proof: array expected");message.proof=[];for(var i=0;i<object.proof.length;++i){if((0,_typeof2["default"])(object.proof[i])!=="object")throw TypeError(".exonum.proof.MapProof.proof: object expected");message.proof[i]=$root.exonum.proof.MapProofEntry.fromObject(object.proof[i]);}}return message;};/**
* Creates a plain object from a MapProof message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proof.MapProof
* @static
* @param {exonum.proof.MapProof} message MapProof
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/MapProof.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.arrays||options.defaults){object.entries=[];object.proof=[];}if(message.entries&&message.entries.length){object.entries=[];for(var j=0;j<message.entries.length;++j){object.entries[j]=$root.exonum.proof.OptionalEntry.toObject(message.entries[j],options);}}if(message.proof&&message.proof.length){object.proof=[];for(var j=0;j<message.proof.length;++j){object.proof[j]=$root.exonum.proof.MapProofEntry.toObject(message.proof[j],options);}}return object;};/**
* Converts this MapProof to JSON.
* @function toJSON
* @memberof exonum.proof.MapProof
* @instance
* @returns {Object.<string,*>} JSON object
*/MapProof.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return MapProof;}();proof.OptionalEntry=function(){/**
* Properties of an OptionalEntry.
* @memberof exonum.proof
* @interface IOptionalEntry
* @property {Uint8Array|null} [key] OptionalEntry key
* @property {Uint8Array|null} [value] OptionalEntry value
* @property {google.protobuf.IEmpty|null} [no_value] OptionalEntry no_value
*/ /**
* Constructs a new OptionalEntry.
* @memberof exonum.proof
* @classdesc Represents an OptionalEntry.
* @implements IOptionalEntry
* @constructor
* @param {exonum.proof.IOptionalEntry=} [properties] Properties to set
*/function OptionalEntry(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* OptionalEntry key.
* @member {Uint8Array} key
* @memberof exonum.proof.OptionalEntry
* @instance
*/OptionalEntry.prototype.key=$util.newBuffer([]);/**
* OptionalEntry value.
* @member {Uint8Array} value
* @memberof exonum.proof.OptionalEntry
* @instance
*/OptionalEntry.prototype.value=$util.newBuffer([]);/**
* OptionalEntry no_value.
* @member {google.protobuf.IEmpty|null|undefined} no_value
* @memberof exonum.proof.OptionalEntry
* @instance
*/OptionalEntry.prototype.no_value=null;// OneOf field names bound to virtual getters and setters
var $oneOfFields;/**
* OptionalEntry maybe_value.
* @member {"value"|"no_value"|undefined} maybe_value
* @memberof exonum.proof.OptionalEntry
* @instance
*/Object.defineProperty(OptionalEntry.prototype,"maybe_value",{get:$util.oneOfGetter($oneOfFields=["value","no_value"]),set:$util.oneOfSetter($oneOfFields)});/**
* Creates a new OptionalEntry instance using the specified properties.
* @function create
* @memberof exonum.proof.OptionalEntry
* @static
* @param {exonum.proof.IOptionalEntry=} [properties] Properties to set
* @returns {exonum.proof.OptionalEntry} OptionalEntry instance
*/OptionalEntry.create=function create(properties){return new OptionalEntry(properties);};/**
* Encodes the specified OptionalEntry message. Does not implicitly {@link exonum.proof.OptionalEntry.verify|verify} messages.
* @function encode
* @memberof exonum.proof.OptionalEntry
* @static
* @param {exonum.proof.IOptionalEntry} message OptionalEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/OptionalEntry.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.key!=null&&message.hasOwnProperty("key"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.key);if(message.value!=null&&message.hasOwnProperty("value"))writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.value);if(message.no_value!=null&&message.hasOwnProperty("no_value"))$root.google.protobuf.Empty.encode(message.no_value,writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim();return writer;};/**
* Encodes the specified OptionalEntry message, length delimited. Does not implicitly {@link exonum.proof.OptionalEntry.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proof.OptionalEntry
* @static
* @param {exonum.proof.IOptionalEntry} message OptionalEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/OptionalEntry.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an OptionalEntry message from the specified reader or buffer.
* @function decode
* @memberof exonum.proof.OptionalEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proof.OptionalEntry} OptionalEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/OptionalEntry.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proof.OptionalEntry();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.key=reader.bytes();break;case 2:message.value=reader.bytes();break;case 3:message.no_value=$root.google.protobuf.Empty.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an OptionalEntry message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proof.OptionalEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proof.OptionalEntry} OptionalEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/OptionalEntry.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an OptionalEntry message.
* @function verify
* @memberof exonum.proof.OptionalEntry
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/OptionalEntry.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";var properties={};if(message.key!=null&&message.hasOwnProperty("key"))if(!(message.key&&typeof message.key.length==="number"||$util.isString(message.key)))return"key: buffer expected";if(message.value!=null&&message.hasOwnProperty("value")){properties.maybe_value=1;if(!(message.value&&typeof message.value.length==="number"||$util.isString(message.value)))return"value: buffer expected";}if(message.no_value!=null&&message.hasOwnProperty("no_value")){if(properties.maybe_value===1)return"maybe_value: multiple values";properties.maybe_value=1;{var error=$root.google.protobuf.Empty.verify(message.no_value);if(error)return"no_value."+error;}}return null;};/**
* Creates an OptionalEntry message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proof.OptionalEntry
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proof.OptionalEntry} OptionalEntry
*/OptionalEntry.fromObject=function fromObject(object){if(object instanceof $root.exonum.proof.OptionalEntry)return object;var message=new $root.exonum.proof.OptionalEntry();if(object.key!=null)if(typeof object.key==="string")$util.base64.decode(object.key,message.key=$util.newBuffer($util.base64.length(object.key)),0);else if(object.key.length)message.key=object.key;if(object.value!=null)if(typeof object.value==="string")$util.base64.decode(object.value,message.value=$util.newBuffer($util.base64.length(object.value)),0);else if(object.value.length)message.value=object.value;if(object.no_value!=null){if((0,_typeof2["default"])(object.no_value)!=="object")throw TypeError(".exonum.proof.OptionalEntry.no_value: object expected");message.no_value=$root.google.protobuf.Empty.fromObject(object.no_value);}return message;};/**
* Creates a plain object from an OptionalEntry message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proof.OptionalEntry
* @static
* @param {exonum.proof.OptionalEntry} message OptionalEntry
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/OptionalEntry.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults)if(options.bytes===String)object.key="";else{object.key=[];if(options.bytes!==Array)object.key=$util.newBuffer(object.key);}if(message.key!=null&&message.hasOwnProperty("key"))object.key=options.bytes===String?$util.base64.encode(message.key,0,message.key.length):options.bytes===Array?Array.prototype.slice.call(message.key):message.key;if(message.value!=null&&message.hasOwnProperty("value")){object.value=options.bytes===String?$util.base64.encode(message.value,0,message.value.length):options.bytes===Array?Array.prototype.slice.call(message.value):message.value;if(options.oneofs)object.maybe_value="value";}if(message.no_value!=null&&message.hasOwnProperty("no_value")){object.no_value=$root.google.protobuf.Empty.toObject(message.no_value,options);if(options.oneofs)object.maybe_value="no_value";}return object;};/**
* Converts this OptionalEntry to JSON.
* @function toJSON
* @memberof exonum.proof.OptionalEntry
* @instance
* @returns {Object.<string,*>} JSON object
*/OptionalEntry.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return OptionalEntry;}();proof.MapProofEntry=function(){/**
* Properties of a MapProofEntry.
* @memberof exonum.proof
* @interface IMapProofEntry
* @property {Uint8Array|null} [proof_path] MapProofEntry proof_path
* @property {exonum.crypto.IHash|null} [hash] MapProofEntry hash
*/ /**
* Constructs a new MapProofEntry.
* @memberof exonum.proof
* @classdesc Represents a MapProofEntry.
* @implements IMapProofEntry
* @constructor
* @param {exonum.proof.IMapProofEntry=} [properties] Properties to set
*/function MapProofEntry(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* MapProofEntry proof_path.
* @member {Uint8Array} proof_path
* @memberof exonum.proof.MapProofEntry
* @instance
*/MapProofEntry.prototype.proof_path=$util.newBuffer([]);/**
* MapProofEntry hash.
* @member {exonum.crypto.IHash|null|undefined} hash
* @memberof exonum.proof.MapProofEntry
* @instance
*/MapProofEntry.prototype.hash=null;/**
* Creates a new MapProofEntry instance using the specified properties.
* @function create
* @memberof exonum.proof.MapProofEntry
* @static
* @param {exonum.proof.IMapProofEntry=} [properties] Properties to set
* @returns {exonum.proof.MapProofEntry} MapProofEntry instance
*/MapProofEntry.create=function create(properties){return new MapProofEntry(properties);};/**
* Encodes the specified MapProofEntry message. Does not implicitly {@link exonum.proof.MapProofEntry.verify|verify} messages.
* @function encode
* @memberof exonum.proof.MapProofEntry
* @static
* @param {exonum.proof.IMapProofEntry} message MapProofEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/MapProofEntry.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.proof_path!=null&&message.hasOwnProperty("proof_path"))writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.proof_path);if(message.hash!=null&&message.hasOwnProperty("hash"))$root.exonum.crypto.Hash.encode(message.hash,writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim();return writer;};/**
* Encodes the specified MapProofEntry message, length delimited. Does not implicitly {@link exonum.proof.MapProofEntry.verify|verify} messages.
* @function encodeDelimited
* @memberof exonum.proof.MapProofEntry
* @static
* @param {exonum.proof.IMapProofEntry} message MapProofEntry message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/MapProofEntry.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a MapProofEntry message from the specified reader or buffer.
* @function decode
* @memberof exonum.proof.MapProofEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {exonum.proof.MapProofEntry} MapProofEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/MapProofEntry.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.exonum.proof.MapProofEntry();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.proof_path=reader.bytes();break;case 2:message.hash=$root.exonum.crypto.Hash.decode(reader,reader.uint32());break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a MapProofEntry message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof exonum.proof.MapProofEntry
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {exonum.proof.MapProofEntry} MapProofEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/MapProofEntry.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a MapProofEntry message.
* @function verify
* @memberof exonum.proof.MapProofEntry
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/MapProofEntry.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.proof_path!=null&&message.hasOwnProperty("proof_path"))if(!(message.proof_path&&typeof message.proof_path.length==="number"||$util.isString(message.proof_path)))return"proof_path: buffer expected";if(message.hash!=null&&message.hasOwnProperty("hash")){var error=$root.exonum.crypto.Hash.verify(message.hash);if(error)return"hash."+error;}return null;};/**
* Creates a MapProofEntry message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof exonum.proof.MapProofEntry
* @static
* @param {Object.<string,*>} object Plain object
* @returns {exonum.proof.MapProofEntry} MapProofEntry
*/MapProofEntry.fromObject=function fromObject(object){if(object instanceof $root.exonum.proof.MapProofEntry)return object;var message=new $root.exonum.proof.MapProofEntry();if(object.proof_path!=null)if(typeof object.proof_path==="string")$util.base64.decode(object.proof_path,message.proof_path=$util.newBuffer($util.base64.length(object.proof_path)),0);else if(object.proof_path.length)message.proof_path=object.proof_path;if(object.hash!=null){if((0,_typeof2["default"])(object.hash)!=="object")throw TypeError(".exonum.proof.MapProofEntry.hash: object expected");message.hash=$root.exonum.crypto.Hash.fromObject(object.hash);}return message;};/**
* Creates a plain object from a MapProofEntry message. Also converts values to other types if specified.
* @function toObject
* @memberof exonum.proof.MapProofEntry
* @static
* @param {exonum.proof.MapProofEntry} message MapProofEntry
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/MapProofEntry.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if(options.bytes===String)object.proof_path="";else{object.proof_path=[];if(options.bytes!==Array)object.proof_path=$util.newBuffer(object.proof_path);}object.hash=null;}if(message.proof_path!=null&&message.hasOwnProperty("proof_path"))object.proof_path=options.bytes===String?$util.base64.encode(message.proof_path,0,message.proof_path.length):options.bytes===Array?Array.prototype.slice.call(message.proof_path):message.proof_path;if(message.hash!=null&&message.hasOwnProperty("hash"))object.hash=$root.exonum.crypto.Hash.toObject(message.hash,options);return object;};/**
* Converts this MapProofEntry to JSON.
* @function toJSON
* @memberof exonum.proof.MapProofEntry
* @instance
* @returns {Object.<string,*>} JSON object
*/MapProofEntry.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return MapProofEntry;}();return proof;}();return exonum;}();$root.google=function(){/**
* Namespace google.
* @exports google
* @namespace
*/var google={};google.protobuf=function(){/**
* Namespace protobuf.
* @memberof google
* @namespace
*/var protobuf={};protobuf.Timestamp=function(){/**
* Properties of a Timestamp.
* @memberof google.protobuf
* @interface ITimestamp
* @property {number|Long|null} [seconds] Timestamp seconds
* @property {number|null} [nanos] Timestamp nanos
*/ /**
* Constructs a new Timestamp.
* @memberof google.protobuf
* @classdesc Represents a Timestamp.
* @implements ITimestamp
* @constructor
* @param {google.protobuf.ITimestamp=} [properties] Properties to set
*/function Timestamp(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Timestamp seconds.
* @member {number|Long} seconds
* @memberof google.protobuf.Timestamp
* @instance
*/Timestamp.prototype.seconds=$util.Long?$util.Long.fromBits(0,0,false):0;/**
* Timestamp nanos.
* @member {number} nanos
* @memberof google.protobuf.Timestamp
* @instance
*/Timestamp.prototype.nanos=0;/**
* Creates a new Timestamp instance using the specified properties.
* @function create
* @memberof google.protobuf.Timestamp
* @static
* @param {google.protobuf.ITimestamp=} [properties] Properties to set
* @returns {google.protobuf.Timestamp} Timestamp instance
*/Timestamp.create=function create(properties){return new Timestamp(properties);};/**
* Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages.
* @function encode
* @memberof google.protobuf.Timestamp
* @static
* @param {google.protobuf.ITimestamp} message Timestamp message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Timestamp.encode=function encode(message,writer){if(!writer)writer=$Writer.create();if(message.seconds!=null&&message.hasOwnProperty("seconds"))writer.uint32(/* id 1, wireType 0 =*/8).int64(message.seconds);if(message.nanos!=null&&message.hasOwnProperty("nanos"))writer.uint32(/* id 2, wireType 0 =*/16).int32(message.nanos);return writer;};/**
* Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages.
* @function encodeDelimited
* @memberof google.protobuf.Timestamp
* @static
* @param {google.protobuf.ITimestamp} message Timestamp message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Timestamp.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes a Timestamp message from the specified reader or buffer.
* @function decode
* @memberof google.protobuf.Timestamp
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {google.protobuf.Timestamp} Timestamp
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Timestamp.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.google.protobuf.Timestamp();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){case 1:message.seconds=reader.int64();break;case 2:message.nanos=reader.int32();break;default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes a Timestamp message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof google.protobuf.Timestamp
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {google.protobuf.Timestamp} Timestamp
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Timestamp.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies a Timestamp message.
* @function verify
* @memberof google.protobuf.Timestamp
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Timestamp.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";if(message.seconds!=null&&message.hasOwnProperty("seconds"))if(!$util.isInteger(message.seconds)&&!(message.seconds&&$util.isInteger(message.seconds.low)&&$util.isInteger(message.seconds.high)))return"seconds: integer|Long expected";if(message.nanos!=null&&message.hasOwnProperty("nanos"))if(!$util.isInteger(message.nanos))return"nanos: integer expected";return null;};/**
* Creates a Timestamp message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof google.protobuf.Timestamp
* @static
* @param {Object.<string,*>} object Plain object
* @returns {google.protobuf.Timestamp} Timestamp
*/Timestamp.fromObject=function fromObject(object){if(object instanceof $root.google.protobuf.Timestamp)return object;var message=new $root.google.protobuf.Timestamp();if(object.seconds!=null)if($util.Long)(message.seconds=$util.Long.fromValue(object.seconds)).unsigned=false;else if(typeof object.seconds==="string")message.seconds=parseInt(object.seconds,10);else if(typeof object.seconds==="number")message.seconds=object.seconds;else if((0,_typeof2["default"])(object.seconds)==="object")message.seconds=new $util.LongBits(object.seconds.low>>>0,object.seconds.high>>>0).toNumber();if(object.nanos!=null)message.nanos=object.nanos|0;return message;};/**
* Creates a plain object from a Timestamp message. Also converts values to other types if specified.
* @function toObject
* @memberof google.protobuf.Timestamp
* @static
* @param {google.protobuf.Timestamp} message Timestamp
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Timestamp.toObject=function toObject(message,options){if(!options)options={};var object={};if(options.defaults){if($util.Long){var _long17=new $util.Long(0,0,false);object.seconds=options.longs===String?_long17.toString():options.longs===Number?_long17.toNumber():_long17;}else object.seconds=options.longs===String?"0":0;object.nanos=0;}if(message.seconds!=null&&message.hasOwnProperty("seconds"))if(typeof message.seconds==="number")object.seconds=options.longs===String?String(message.seconds):message.seconds;else object.seconds=options.longs===String?$util.Long.prototype.toString.call(message.seconds):options.longs===Number?new $util.LongBits(message.seconds.low>>>0,message.seconds.high>>>0).toNumber():message.seconds;if(message.nanos!=null&&message.hasOwnProperty("nanos"))object.nanos=message.nanos;return object;};/**
* Converts this Timestamp to JSON.
* @function toJSON
* @memberof google.protobuf.Timestamp
* @instance
* @returns {Object.<string,*>} JSON object
*/Timestamp.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Timestamp;}();protobuf.Empty=function(){/**
* Properties of an Empty.
* @memberof google.protobuf
* @interface IEmpty
*/ /**
* Constructs a new Empty.
* @memberof google.protobuf
* @classdesc Represents an Empty.
* @implements IEmpty
* @constructor
* @param {google.protobuf.IEmpty=} [properties] Properties to set
*/function Empty(properties){if(properties)for(var keys=Object.keys(properties),i=0;i<keys.length;++i){if(properties[keys[i]]!=null)this[keys[i]]=properties[keys[i]];}}/**
* Creates a new Empty instance using the specified properties.
* @function create
* @memberof google.protobuf.Empty
* @static
* @param {google.protobuf.IEmpty=} [properties] Properties to set
* @returns {google.protobuf.Empty} Empty instance
*/Empty.create=function create(properties){return new Empty(properties);};/**
* Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @function encode
* @memberof google.protobuf.Empty
* @static
* @param {google.protobuf.IEmpty} message Empty message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Empty.encode=function encode(message,writer){if(!writer)writer=$Writer.create();return writer;};/**
* Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages.
* @function encodeDelimited
* @memberof google.protobuf.Empty
* @static
* @param {google.protobuf.IEmpty} message Empty message or plain object to encode
* @param {$protobuf.Writer} [writer] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/Empty.encodeDelimited=function encodeDelimited(message,writer){return this.encode(message,writer).ldelim();};/**
* Decodes an Empty message from the specified reader or buffer.
* @function decode
* @memberof google.protobuf.Empty
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @param {number} [length] Message length if known beforehand
* @returns {google.protobuf.Empty} Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Empty.decode=function decode(reader,length){if(!(reader instanceof $Reader))reader=$Reader.create(reader);var end=length===undefined?reader.len:reader.pos+length,message=new $root.google.protobuf.Empty();while(reader.pos<end){var tag=reader.uint32();switch(tag>>>3){default:reader.skipType(tag&7);break;}}return message;};/**
* Decodes an Empty message from the specified reader or buffer, length delimited.
* @function decodeDelimited
* @memberof google.protobuf.Empty
* @static
* @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from
* @returns {google.protobuf.Empty} Empty
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/Empty.decodeDelimited=function decodeDelimited(reader){if(!(reader instanceof $Reader))reader=new $Reader(reader);return this.decode(reader,reader.uint32());};/**
* Verifies an Empty message.
* @function verify
* @memberof google.protobuf.Empty
* @static
* @param {Object.<string,*>} message Plain object to verify
* @returns {string|null} `null` if valid, otherwise the reason why it is not
*/Empty.verify=function verify(message){if((0,_typeof2["default"])(message)!=="object"||message===null)return"object expected";return null;};/**
* Creates an Empty message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof google.protobuf.Empty
* @static
* @param {Object.<string,*>} object Plain object
* @returns {google.protobuf.Empty} Empty
*/Empty.fromObject=function fromObject(object){if(object instanceof $root.google.protobuf.Empty)return object;return new $root.google.protobuf.Empty();};/**
* Creates a plain object from an Empty message. Also converts values to other types if specified.
* @function toObject
* @memberof google.protobuf.Empty
* @static
* @param {google.protobuf.Empty} message Empty
* @param {$protobuf.IConversionOptions} [options] Conversion options
* @returns {Object.<string,*>} Plain object
*/Empty.toObject=function toObject(){return{};};/**
* Converts this Empty to JSON.
* @function toJSON
* @memberof google.protobuf.Empty
* @instance
* @returns {Object.<string,*>} JSON object
*/Empty.prototype.toJSON=function toJSON(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions);};return Empty;}();return protobuf;}();return google;}();return $root;});
},{"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/typeof":22,"protobufjs/minimal":67}],90:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _convert = require("../types/convert");
/**
* Length of a path to a terminal node in bits.
*
* @type {number}
*/
var BIT_LENGTH = 256;
var ProofPath =
/*#__PURE__*/
function () {
/**
* Constructs a proof path from a binary string or a byte buffer.
*
* @param {string | Uint8Array} bits
* @param {number} bitLength?
*/
function ProofPath(bits) {
var bitLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : BIT_LENGTH;
(0, _classCallCheck2["default"])(this, ProofPath);
if (typeof bits === 'string') {
this.key = (0, _convert.binaryStringToUint8Array)(padWithZeros(bits, BIT_LENGTH));
bitLength = bits.length;
} else if (bits instanceof Uint8Array && bits.length === BIT_LENGTH / 8) {
this.key = bits.slice(0);
} else {
throw new TypeError('Invalid `bits` parameter');
}
this.bitLength = bitLength;
this.hexKey = (0, _convert.uint8ArrayToHexadecimal)(this.key);
}
/**
* Checks if this path corresponds to the terminal node / leaf in the Merkle Patricia tree.
*
* @returns {boolean}
*/
(0, _createClass2["default"])(ProofPath, [{
key: "isTerminal",
value: function isTerminal() {
return this.bitLength === BIT_LENGTH;
}
/**
* Retrieves a bit at a specific position of this key.
*
* @param {number} pos
* @returns {0 | 1 | void}
*/
}, {
key: "bit",
value: function bit(pos) {
pos = +pos;
if (pos >= this.bitLength || pos < 0) {
return undefined;
}
return getBit(this.key, pos);
}
}, {
key: "commonPrefixLength",
value: function commonPrefixLength(other) {
var intersectingBits = Math.min(this.bitLength, other.bitLength); // First, advance by a full byte while it is possible
var pos;
for (pos = 0; pos < intersectingBits >> 3 && this.key[pos >> 3] === other.key[pos >> 3]; pos += 8) {
;
} // Then, check individual bits
for (; pos < intersectingBits && this.bit(pos) === other.bit(pos); pos++) {
;
}
return pos;
}
/**
* Computes a common prefix of this and another byte sequence.
*
* @param {ProofPath} other
* @returns {ProofPath}
*/
}, {
key: "commonPrefix",
value: function commonPrefix(other) {
var pos = this.commonPrefixLength(other);
return this.truncate(pos);
}
/**
* Checks if the path starts with the other specified path.
*
* @param {ProofPath} other
* @returns {boolean}
*/
}, {
key: "startsWith",
value: function startsWith(other) {
return this.commonPrefixLength(other) === other.bitLength;
}
/**
* Compares this proof path to another.
*
* @param {ProofPath} other
* @returns {-1 | 0 | 1}
*/
}, {
key: "compare",
value: function compare(other) {
var _ref = [this.bitLength, other.bitLength],
thisLen = _ref[0],
otherLen = _ref[1];
var intersectingBits = Math.min(thisLen, otherLen);
var pos = this.commonPrefixLength(other);
if (pos === intersectingBits) {
return Math.sign(thisLen - otherLen);
}
return this.bit(pos) - other.bit(pos);
}
/**
* Truncates this bit sequence to a shorter one by removing some bits from the end.
*
* @param {number} bits
* new length of the sequence
* @returns {ProofPath}
* truncated bit sequence
*/
}, {
key: "truncate",
value: function truncate(bits) {
bits = +bits;
if (bits > this.bitLength) {
throw new TypeError('Cannot truncate bit slice to length more than current ' + "(current: ".concat(this.bitLength, ", requested: ").concat(bits, ")"));
}
var bytes = new Uint8Array(BIT_LENGTH / 8);
for (var i = 0; i < bits >> 3; i++) {
bytes[i] = this.key[i];
}
for (var bit = 8 * (bits >> 3); bit < bits; bit++) {
setBit(bytes, bit, this.bit(bit));
}
return new ProofPath(bytes, bits);
}
/**
* Serializes this path into a buffer. The serialization is performed according as follows:
*
* 1. Serialize number of bits in the path in LEB128 encoding.
* 2. Serialize bits with zero padding to the right.
*
* @param {Array<number>} buffer
*/
}, {
key: "serialize",
value: function serialize(buffer) {
if (this.bitLength < 128) {
buffer.push(this.bitLength);
} else {
// The length is encoded as two bytes.
// The first byte contains the lower 7 bits of the length, and has the highest bit set
// as per LEB128. The second byte contains the upper bit of the length
// (i.e., 1 or 2), thus, it always equals 1 or 2.
buffer.push(128 + this.bitLength % 128, this.bitLength >> 7);
} // Copy the bits.
for (var pos = 0; pos < this.bitLength + 7 >> 3; pos++) {
buffer.push(this.key[pos]);
}
}
/**
* Converts this path to its JSON presentation.
*
* @returns {string}
* binary string representing the path
*/
}, {
key: "toJSON",
value: function toJSON() {
var bits = (0, _convert.hexadecimalToBinaryString)(this.hexKey);
return trimZeros(bits, this.bitLength);
}
}, {
key: "toString",
value: function toString() {
var bits = (0, _convert.hexadecimalToBinaryString)(this.hexKey);
bits = this.bitLength > 8 ? trimZeros(bits, 8) + '...' : trimZeros(bits, this.bitLength);
return "path(".concat(bits, ")");
}
}]);
return ProofPath;
}();
/**
* Expected length of byte buffers used to create `ProofPath`s.
*/
exports["default"] = ProofPath;
ProofPath.BYTE_LENGTH = BIT_LENGTH / 8;
function getBit(buffer, pos) {
var _byte = Math.floor(pos / 8);
var bitPos = pos % 8;
return (buffer[_byte] & 1 << bitPos) >> bitPos;
}
/**
* Sets a specified bit in the byte buffer.
*
* @param {Uint8Array} buffer
* @param {number} pos 0-based position in the buffer to set
* @param {0 | 1} bit
*/
function setBit(buffer, pos, bit) {
var _byte2 = Math.floor(pos / 8);
var bitPos = pos % 8;
if (bit === 0) {
var mask = 255 - (1 << bitPos);
buffer[_byte2] &= mask;
} else {
var _mask = 1 << bitPos;
buffer[_byte2] |= _mask;
}
}
var ZEROS = function () {
var str = '0';
for (var i = 0; i < 8; i++) {
str = str + str;
}
return str;
}();
function padWithZeros(str, desiredLength) {
return str + ZEROS.substring(0, desiredLength - str.length);
}
function trimZeros(str, desiredLength) {
/* istanbul ignore next: should never be triggered */
if (str.length < desiredLength) {
throw new Error('Invariant broken: negative zero trimming requested');
}
return str.substring(0, desiredLength);
}
},{"../types/convert":118,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":7,"@babel/runtime/helpers/interopRequireDefault":11}],91:[function(require,module,exports){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.verifyBlock = verifyBlock;
exports.protocol = void 0;
var Long = _interopRequireWildcard(require("long"));
var protocol = _interopRequireWildcard(require("../../proto/protocol.js"));
exports.protocol = protocol;
var _convert = require("../types/convert");
var _crypto = require("../crypto");
/**
* Validate block and each precommit in block
* @param {Object} data
* @param {Array} validators
* @return {Promise}
*/
function verifyBlock(data, validators) {
return new Promise(function (resolve) {
var block = {
prev_hash: {
data: (0, _convert.hexadecimalToUint8Array)(data.block.prev_hash)
},
tx_hash: {
data: (0, _convert.hexadecimalToUint8Array)(data.block.tx_hash)
},
state_hash: {
data: (0, _convert.hexadecimalToUint8Array)(data.block.state_hash)
}
};
var blockHash;
if (data.block.proposer_id !== 0) {
block.proposer_id = data.block.proposer_id;
}
if (data.block.height !== 0) {
block.height = data.block.height;
}
if (data.block.tx_count !== 0) {
block.tx_count = data.block.tx_count;
}
var message = protocol.exonum.Block.create(block);
var buffer = new Uint8Array(protocol.exonum.Block.encode(message).finish());
blockHash = (0, _crypto.hash)(buffer);
for (var i = 0; i < data.precommits.length; i++) {
var precommit = data.precommits[i];
var _buffer = (0, _convert.hexadecimalToUint8Array)(precommit);
var singedMsg = protocol.exonum.consensus.SignedMessage.decode(new Uint8Array(_buffer));
var _message = protocol.exonum.consensus.ExonumMessage.decode(singedMsg.payload);
_message = _message.precommit;
var plain = protocol.exonum.consensus.Precommit.toObject(_message);
if (Long.fromValue(plain.height).compare(Long.fromValue(data.block.height)) !== 0) {
throw new Error('Precommit height is not match with block height');
}
if ((0, _convert.uint8ArrayToHexadecimal)(plain.block_hash.data) !== blockHash) {
throw new Error('Precommit block hash is not match with calculated block hash');
}
var publicKey = validators[plain.validator || 0];
if ((0, _convert.uint8ArrayToHexadecimal)(singedMsg.author.data) !== publicKey) {
throw new Error('Precommit public key is not match with buffer');
}
var signature = (0, _convert.uint8ArrayToHexadecimal)(singedMsg.signature.data);
if (!(0, _crypto.verifySignature)(signature, publicKey, singedMsg.payload)) {
throw new Error('Precommit signature is wrong');
}
}
resolve();
});
}
},{"../../proto/protocol.js":89,"../crypto":100,"../types/convert":118,"@babel/runtime/helpers/interopRequireWildcard":12,"long":65}],92:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MAP_BRANCH_PREFIX = exports.MAP_PREFIX = exports.LIST_BRANCH_PREFIX = exports.LIST_PREFIX = exports.BLOB_PREFIX = void 0;
/**
* Prefix marker for a blob node in a `ProofMapIndex`.
*
* @type {number}
*/
var BLOB_PREFIX = 0;
/**
* Prefix marker for a `ProofListIndex` object.
* It is defined in the `HashTag` enum in the `exonum_merkledb` crate.
*
* @type {number}
*/
exports.BLOB_PREFIX = BLOB_PREFIX;
var LIST_PREFIX = 2;
/**
* Prefix marker for an intermediate `ProofListIndex` node.
* It is defined in the `HashTag` enum in the `exonum_merkledb` crate.
*
* @type {number}
*/
exports.LIST_PREFIX = LIST_PREFIX;
var LIST_BRANCH_PREFIX = 1;
/**
* Prefix marker for a `ProofMapIndex` object.
* It is defined in the `HashTag` enum in the `exonum_merkledb` crate.
*
* @type {number}
*/
exports.LIST_BRANCH_PREFIX = LIST_BRANCH_PREFIX;
var MAP_PREFIX = 3;
/**
* Prefix marker for an intermediate `ProofMapIndex` nodes.
* It is defined in the `HashTag` enum in the `exonum_merkledb` crate.
*
* @type {number}
*/
exports.MAP_PREFIX = MAP_PREFIX;
var MAP_BRANCH_PREFIX = 4;
exports.MAP_BRANCH_PREFIX = MAP_BRANCH_PREFIX;
},{}],93:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _merkle = require("./merkle");
Object.keys(_merkle).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _merkle[key];
}
});
});
var _merklePatricia = require("./merkle-patricia");
Object.keys(_merklePatricia).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _merklePatricia[key];
}
});
});
var _block = require("./block");
Object.keys(_block).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _block[key];
}
});
});
var _transport = require("./transport");
Object.keys(_transport).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _transport[key];
}
});
});
var _table = require("./table");
Object.keys(_table).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _table[key];
}
});
});
},{"./block":91,"./merkle":95,"./merkle-patricia":94,"./table":96,"./transport":97}],94:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MapProofError = exports.MapProof = void 0;
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _binarySearch = _interopRequireDefault(require("binary-search"));
var _crypto = require("../crypto");
var _hexadecimal = require("../types/hexadecimal");
var _constants = require("./constants");
var _ProofPath = _interopRequireDefault(require("./ProofPath"));
var _types = require("../types");
/**
* Proof of existence and/or absence of certain elements from a Merkelized
* map index.
*/
var MapProof =
/**
* Creates a new instance of a proof.
*
* @param {Object} json
* JSON object containing (untrusted) proof
* @param {{serialize: (any) => Array<number>}} keyType
* Type of keys used in the underlying Merkelized map. Usually, `PublicKey`
* or `Hash`. The keys must be serializable.
* @param {{ serialize: (any) => Array<number>}} valueType
* Type of values used in the underlying Merkelized map. Usually, it should
* be a type created with the `newType` function. The type must be serializable.
* @throws {MapProofError}
* if the proof is malformed
*/
function MapProof(json, keyType, valueType) {
(0, _classCallCheck2["default"])(this, MapProof);
if (!valueType) {
throw new TypeError('Invalid value type');
}
if (typeof valueType.encode === 'function' && typeof valueType.serialize !== 'function') {
valueType.serialize = function (data, _buff, _offset) {
return this.encode(data).finish();
};
} else if (typeof valueType.serialize !== 'function') {
throw new TypeError('No `hash` or `serialize` method in the value type');
}
this.valueType = valueType;
this.proof = parseProof(json.proof);
this.entries = parseEntries(json.entries, keyType, valueType);
if (!keyType || typeof keyType.serialize !== 'function') {
throw new TypeError('No `serialize` method in the key type');
}
this.keyType = keyType;
precheckProof.call(this);
var completeProof = this.proof.concat(this.entries).sort(function (_ref, _ref2) {
var pathA = _ref.path;
var pathB = _ref2.path;
return pathA.compare(pathB);
}); // This check is required as duplicate paths can be introduced by entries
// (further, it's generally possible that two different entry keys lead
// to the same `ProofPath`).
for (var i = 1; i < completeProof.length; i++) {
var _ref3 = [completeProof[i - 1], completeProof[i]],
pathA = _ref3[0].path,
pathB = _ref3[1].path;
if (pathA.compare(pathB) === 0) {
throw new MapProofError('duplicatePath', pathA);
}
}
var rootHash = (0, _types.hexadecimalToUint8Array)(collect(completeProof.filter(function (_ref4) {
var hash = _ref4.hash;
return !!hash;
})));
this.merkleRoot = (0, _crypto.hash)([_constants.MAP_PREFIX].concat((0, _toConsumableArray2["default"])(rootHash)));
this.missingKeys = new Set(this.entries.filter(function (e) {
return e.missing !== undefined;
}).map(function (_ref5) {
var missing = _ref5.missing;
return missing;
}));
this.entries = new Map(this.entries.filter(function (e) {
return e.key !== undefined;
}).map(function (_ref6) {
var key = _ref6.key,
value = _ref6.value;
return [key, value];
}));
};
exports.MapProof = MapProof;
function parseProof(proof) {
if (!Array.isArray(proof)) {
throw new MapProofError('malformedProof');
}
var validEntries = proof.every(function (_ref7) {
var path = _ref7.path,
hash = _ref7.hash;
return /^[01]{1,256}$/.test(path) && /^[0-9a-f]{64}$/i.test(hash);
});
if (!validEntries) {
throw new MapProofError('malformedProof');
}
return proof.map(function (_ref8) {
var path = _ref8.path,
hash = _ref8.hash;
return {
path: new _ProofPath["default"](path),
hash: hash
};
});
}
function parseEntries(entries, keyType, valueType) {
function createPath(data) {
var keyBytes = typeof keyType.hash === 'function' ? keyType.hash(data) : (0, _crypto.hash)(keyType.serialize(data, [], 0));
var bytes = (0, _types.hexadecimalToUint8Array)(keyBytes);
return new _ProofPath["default"](new Uint8Array(bytes));
}
if (!Array.isArray(entries)) {
throw new MapProofError('malformedEntries');
}
return entries.map(function (_ref9) {
var missing = _ref9.missing,
key = _ref9.key,
value = _ref9.value;
if (missing === undefined && (key === undefined || value === undefined)) {
throw new MapProofError('unknownEntryType');
}
if (missing !== undefined && (key !== undefined || value !== undefined)) {
throw new MapProofError('ambiguousEntryType');
}
if (missing !== undefined) {
return {
missing: missing,
path: createPath(missing)
};
}
return {
key: key,
value: value,
path: createPath(key),
hash: (0, _crypto.hash)([_constants.BLOB_PREFIX].concat((0, _toConsumableArray2["default"])(valueType.serialize(value, [], 0))))
};
});
}
/**
* @this {MapProof}
*/
function precheckProof() {
var _this = this;
// Check that entries in proof are in increasing order
for (var i = 1; i < this.proof.length; i++) {
var _ref10 = [this.proof[i - 1], this.proof[i]],
prevPath = _ref10[0].path,
path = _ref10[1].path;
switch (prevPath.compare(path)) {
case -1:
if (path.startsWith(prevPath)) {
throw new MapProofError('embeddedPaths', prevPath, path);
}
break;
case 0:
throw new MapProofError('duplicatePath', path);
case 1:
throw new MapProofError('invalidOrdering', prevPath, path);
}
} // Check that no entry has a prefix among the paths in the proof entries.
// In order to do this, it suffices to locate the closest smaller path
// in the proof entries and check only it.
this.entries.forEach(function (_ref11) {
var keyPath = _ref11.path;
var index = (0, _binarySearch["default"])(_this.proof, keyPath, function (_ref12, needle) {
var path = _ref12.path;
return path.compare(needle);
});
if (index >= 0) {
throw new MapProofError('duplicatePath', keyPath);
}
var insertionIndex = -index - 1;
if (insertionIndex > 0) {
var _prevPath = _this.proof[insertionIndex - 1].path;
if (keyPath.startsWith(_prevPath)) {
throw new MapProofError('embeddedPaths', _prevPath, keyPath);
}
}
});
}
function serializeBranchNode(leftHash, rightHash, leftPath, rightPath) {
var buffer = [_constants.MAP_BRANCH_PREFIX];
_hexadecimal.Hash.serialize(leftHash, buffer, buffer.length);
_hexadecimal.Hash.serialize(rightHash, buffer, buffer.length);
leftPath.serialize(buffer);
rightPath.serialize(buffer);
return buffer;
}
function serializeIsolatedNode(path, hash) {
// `1, ...path.key, 0` is the old `ProofPath` serialization for terminal paths.
var buffer = [_constants.MAP_BRANCH_PREFIX, 1].concat((0, _toConsumableArray2["default"])(path.key), [0]);
_hexadecimal.Hash.serialize(hash, buffer, buffer.length);
return buffer;
}
function collect(entries) {
function hashIsolatedNode(_ref13) {
var path = _ref13.path,
valueHash = _ref13.hash;
var buffer = serializeIsolatedNode(path, valueHash);
return (0, _crypto.hash)(buffer);
}
function hashBranch(left, right) {
var buffer = serializeBranchNode(left.hash, right.hash, left.path, right.path);
return (0, _crypto.hash)(buffer);
}
function fold(contour, lastPrefix) {
var lastEntry = contour.pop();
var penultimateEntry = contour.pop();
contour.push({
path: lastPrefix,
hash: hashBranch(penultimateEntry, lastEntry)
});
return contour.length > 1 ? lastPrefix.commonPrefix(contour[contour.length - 2].path) : null;
}
switch (entries.length) {
case 0:
return '0000000000000000000000000000000000000000000000000000000000000000';
case 1:
if (!entries[0].path.isTerminal()) {
throw new MapProofError('nonTerminalNode', entries[0].path);
}
return hashIsolatedNode(entries[0]);
default:
var contour = []; // invariant: equal to the common prefix of the 2 last nodes in the contour
var lastPrefix = entries[0].path.commonPrefix(entries[1].path);
contour.push(entries[0], entries[1]);
for (var i = 2; i < entries.length; i++) {
var entry = entries[i];
var newPrefix = entry.path.commonPrefix(contour[contour.length - 1].path);
while (contour.length > 1 && newPrefix.bitLength < lastPrefix.bitLength) {
var foldedPrefix = fold(contour, lastPrefix);
if (foldedPrefix) {
lastPrefix = foldedPrefix;
}
}
contour.push(entry);
lastPrefix = newPrefix;
}
while (contour.length > 1) {
lastPrefix = fold(contour, lastPrefix);
}
return contour[0].hash;
}
}
/**
* Error indicating a malformed `MapProof`.
*/
var MapProofError =
/*#__PURE__*/
function (_Error) {
(0, _inherits2["default"])(MapProofError, _Error);
function MapProofError(type) {
var _this2;
(0, _classCallCheck2["default"])(this, MapProofError);
switch (type) {
case 'malformedProof':
_this2 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(MapProofError).call(this, 'malformed `proof` part of the proof'));
break;
case 'malformedEntries':
case 'unknownEntryType':
case 'ambiguousEntryType':
_this2 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(MapProofError).call(this, 'malformed `entries` part of the proof'));
break;
case 'embeddedPaths':
_this2 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(MapProofError).call(this, "embedded paths in proof: ".concat(arguments.length <= 1 ? undefined : arguments[1], " is a prefix of ").concat(arguments.length <= 2 ? undefined : arguments[2])));
break;
case 'duplicatePath':
_this2 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(MapProofError).call(this, "duplicate ".concat(arguments.length <= 1 ? undefined : arguments[1], " in proof")));
break;
case 'invalidOrdering':
_this2 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(MapProofError).call(this, 'invalid path ordering'));
break;
case 'nonTerminalNode':
_this2 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(MapProofError).call(this, 'non-terminal isolated node in proof'));
break;
default:
_this2 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(MapProofError).call(this, type));
}
return _this2;
}
return MapProofError;
}((0, _wrapNativeSuper2["default"])(Error));
exports.MapProofError = MapProofError;
},{"../crypto":100,"../types":121,"../types/hexadecimal":120,"./ProofPath":90,"./constants":92,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/getPrototypeOf":9,"@babel/runtime/helpers/inherits":10,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/possibleConstructorReturn":18,"@babel/runtime/helpers/toConsumableArray":21,"@babel/runtime/helpers/wrapNativeSuper":23,"binary-search":60}],95:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ListProofError = exports.ListProof = void 0;
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _bigInteger = _interopRequireDefault(require("big-integer"));
var _binarySearch = _interopRequireDefault(require("binary-search"));
var _hexadecimal = require("../types/hexadecimal");
var _convert = require("../types/convert");
var _crypto = require("../crypto");
var _constants = require("./constants");
/**
* @typedef IEntry
* @property {number} height Height of the entry
* @property {number} index Index of the entry on the level
* @property {string} hash SHA-256 digest of the entry
*/
// Maximum height of a valid Merkle tree
var MAX_TREE_HEIGHT = 58;
var ListProof = function ListProof(_ref, valueType) {
var proof = _ref.proof,
entries = _ref.entries,
length = _ref.length;
(0, _classCallCheck2["default"])(this, ListProof);
if (!valueType || typeof valueType.serialize !== 'function') {
throw new TypeError('No `serialize` method in the value type');
}
this.valueType = valueType;
this.proof = parseProof(proof);
this.entries = parseEntries(entries, valueType);
this.length = length;
var rootHash;
if (this.length === 0) {
if (this.proof.length === 0 && this.entries.length === 0) {
rootHash = '0000000000000000000000000000000000000000000000000000000000000000';
} else {
throw new ListProofError('malformedEmptyProof');
}
} else {
var completeProof = [].concat((0, _toConsumableArray2["default"])(this.entries), (0, _toConsumableArray2["default"])(this.proof));
rootHash = collect(completeProof, this.length);
}
this.merkleRoot = hashList(rootHash, this.length);
};
exports.ListProof = ListProof;
function parseProof(proof) {
if (!Array.isArray(proof)) {
throw new ListProofError('malformedProof');
}
var validEntries = proof.every(function (_ref2) {
var index = _ref2.index,
height = _ref2.height,
hash = _ref2.hash;
return /^[0-9a-f]{64}$/i.test(hash) && Number.isInteger(index) && Number.isInteger(height) && height > 0 && height <= MAX_TREE_HEIGHT;
});
if (!validEntries) {
throw new ListProofError('malformedProof');
} // Check ordering of proof entries.
for (var i = 0; i + 1 < proof.length; i++) {
var _ref3 = [proof[i], proof[i + 1]],
prev = _ref3[0],
next = _ref3[1];
if (prev.height > next.height || prev.height === next.height && prev.index >= next.index) {
throw new ListProofError('invalidProofOrdering');
}
}
return proof;
}
/**
* Performs some preliminary checks on list values and computes their hashes.
*
* @param entries
* @param valueType
* @returns {IEntry[]} parsed entries
*/
function parseEntries(entries, valueType) {
if (!Array.isArray(entries)) {
throw new ListProofError('malformedEntries');
} // Check ordering of values.
for (var i = 0; i + 1 < entries.length; i++) {
var _ref4 = [entries[i], entries[i + 1]],
prev = _ref4[0],
next = _ref4[1];
if (prev[0] >= next[0]) {
throw new ListProofError('invalidValuesOrdering');
}
}
return entries.map(function (_ref5) {
var _ref6 = (0, _slicedToArray2["default"])(_ref5, 2),
index = _ref6[0],
value = _ref6[1];
if (!Number.isInteger(index)) {
throw new ListProofError('malformedEntries');
}
return {
index: index,
height: 0,
value: value,
hash: (0, _crypto.hash)([_constants.BLOB_PREFIX].concat((0, _toConsumableArray2["default"])(valueType.serialize(value, [], 0))))
};
});
}
/**
* Collects entries into a single hash of the Merkle tree.
* @param {IEntry[]} entries
* @param {number} listLength
* @returns {string} hash of the Merkle tree
*/
function collect(entries, listLength) {
var treeHeight = calcHeight(listLength); // Check that height is appropriate. Since we've checked ordering of `entries`,
// we only check that the height of the last entry does not exceed the expected
// value.
if (entries[entries.length - 1].height >= treeHeight) {
throw new ListProofError('unexpectedHeight');
} // Check that indexes of `entries` are appropriate.
entries.forEach(function (_ref7) {
var height = _ref7.height,
index = _ref7.index;
var divisor = height === 0 ? 1 : Math.pow(2, height - 1);
var maxIndexOnLevel = Math.floor((listLength - 1) / divisor);
if (index > maxIndexOnLevel) {
throw new ListProofError('unexpectedIndex');
}
}); // Copy values to the first layer (we've calculated their hashes already).
var layer = spliceLayer(entries, 0).map(function (_ref8) {
var index = _ref8.index,
hash = _ref8.hash;
return {
height: 1,
index: index,
hash: hash
};
});
var lastIndex = listLength - 1;
for (var height = 1; height < treeHeight; height++) {
// Merge with the next layer.
var nextLayer = spliceLayer(entries, height);
layer = mergeLayers(layer, nextLayer); // Zip the entries on the layer.
hashLayer(layer, lastIndex);
lastIndex = Math.floor(lastIndex / 2);
}
return layer[0].hash;
}
/**
* Splices entries with the specified height from the beginning of the array.
* The entries are modified in place.
*
* @param {IEntry[]} entries
* @param {number} height
* @returns {IEntry[]} spliced entries
*/
function spliceLayer(entries, height) {
var index = (0, _binarySearch["default"])(entries, height + 1, function (_ref9, needleHeight) {
var height = _ref9.height,
index = _ref9.index;
// Assume that all entries with `height === needleHeight` are larger than our needle.
var x = needleHeight !== height ? height - needleHeight : 1;
return x;
});
/* istanbul ignore next: should never be triggered */
if (index >= 0) {
throw new Error('Internal error while verifying list proof');
}
var greaterIndex = -index - 1;
return entries.splice(0, greaterIndex);
}
/**
* Merges two sorted arrays together.
*
* @param {IEntry[]} xs
* @param {IEntry[]} ys
* @returns {IEntry[]}
*/
function mergeLayers(xs, ys) {
var xIndex = 0;
var yIndex = 0;
var output = [];
while (xIndex < xs.length || yIndex < ys.length) {
var _ref10 = [xs[xIndex], ys[yIndex]],
x = _ref10[0],
y = _ref10[1];
if (!x) {
output.push(y);
yIndex++;
} else if (!y) {
output.push(x);
xIndex++;
} else if (x.index < y.index) {
output.push(x);
xIndex++;
} else if (x.index > y.index) {
output.push(y);
yIndex++;
} else {
// x.index === y.index
throw new ListProofError('duplicateHash');
}
}
return output;
}
/**
* Elevates the layer to the next level by zipping pairs of entries together.
*
* @param {IEntry[]} layer
* @param {number} lastIndex
*/
function hashLayer(layer, lastIndex) {
for (var i = 0; i < layer.length; i += 2) {
var _ref11 = [layer[i], layer[i + 1]],
left = _ref11[0],
right = _ref11[1];
var _hash = void 0;
if (right) {
// To be able to zip two hashes on the layer, they need to be adjacent to each other,
// and the first of them needs to have an even index.
if (left.index % 2 !== 0 || right.index !== left.index + 1) {
throw new ListProofError('missingHash');
}
_hash = hashNode(left.hash, right.hash);
} else {
// If there is an odd number of hashes on the layer, the solitary hash must have
// the greatest possible index.
if (lastIndex % 2 === 1 || left.index !== lastIndex) {
throw new ListProofError('missingHash');
}
_hash = hashNode(left.hash);
}
layer[i / 2] = {
height: left.height + 1,
index: left.index / 2,
hash: _hash
};
}
layer.length = Math.ceil(layer.length / 2);
}
function hashNode(leftHash, maybeRightHash) {
var buffer = [_constants.LIST_BRANCH_PREFIX];
_hexadecimal.Hash.serialize(leftHash, buffer, buffer.length);
if (maybeRightHash) {
_hexadecimal.Hash.serialize(maybeRightHash, buffer, buffer.length);
}
return (0, _crypto.hash)(buffer);
}
/**
* Computes hash of the `ProofListIndex` given its length and root hash.
* @param {string} rootHash
* @param {number} length
* @returns {string}
*/
function hashList(rootHash, length) {
var buffer = new Uint8Array(9 + _crypto.HASH_LENGTH);
buffer[0] = _constants.LIST_PREFIX; // Set bytes 1..9 as little-endian list length
var quotient = (0, _bigInteger["default"])(length);
for (var _byte = 1; _byte < 9; _byte++) {
var remainder = void 0;
var _quotient$divmod = quotient.divmod(256);
quotient = _quotient$divmod.quotient;
remainder = _quotient$divmod.remainder;
buffer[_byte] = remainder;
}
buffer.set((0, _convert.hexadecimalToUint8Array)(rootHash), 9);
return (0, _crypto.hash)(buffer);
}
/**
* Calculates height of a Merkle tree given its length.
* @param {bigInt} count
* @return {number}
*/
function calcHeight(count) {
var i = 0;
while ((0, _bigInteger["default"])(2).pow(i).lt(count)) {
i++;
}
return i + 1;
}
var ListProofError =
/*#__PURE__*/
function (_Error) {
(0, _inherits2["default"])(ListProofError, _Error);
function ListProofError(type) {
var _this;
(0, _classCallCheck2["default"])(this, ListProofError);
switch (type) {
case 'malformedProof':
case 'invalidProofOrdering':
_this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ListProofError).call(this, 'malformed `proof` part of the proof'));
break;
case 'malformedEntries':
case 'invalidValuesOrdering':
_this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ListProofError).call(this, 'malformed `entries` in the proof'));
break;
case 'unexpectedHeight':
case 'unexpectedIndex':
_this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ListProofError).call(this, 'proof contains a branch where it is impossible according to list length'));
break;
case 'duplicateHash':
_this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ListProofError).call(this, 'proof contains redundant entries'));
break;
case 'missingHash':
_this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ListProofError).call(this, 'proof does not contain information to restore index hash'));
break;
default:
_this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ListProofError).call(this, type));
}
return _this;
}
return ListProofError;
}((0, _wrapNativeSuper2["default"])(Error));
exports.ListProofError = ListProofError;
},{"../crypto":100,"../types/convert":118,"../types/hexadecimal":120,"./constants":92,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/getPrototypeOf":9,"@babel/runtime/helpers/inherits":10,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/possibleConstructorReturn":18,"@babel/runtime/helpers/slicedToArray":20,"@babel/runtime/helpers/toConsumableArray":21,"@babel/runtime/helpers/wrapNativeSuper":23,"big-integer":59,"binary-search":60}],96:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.verifyTable = verifyTable;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _crypto = require("../crypto");
var _primitive = require("../types/primitive");
var _hexadecimal = require("../types/hexadecimal");
var _merklePatricia = require("./merkle-patricia");
var IndexCoordinates = {
/**
* Serialization index coordinates
* @param {Object} data
* @returns {Array}
*/
serialize: function serialize(data) {
var buffer = [];
_primitive.Uint16.serialize(data.origin_label, buffer, buffer.length, true);
_primitive.Uint32.serialize(data.local_schema_id, buffer, buffer.length, true);
_primitive.Uint16.serialize(data.index_id, buffer, buffer.length, true);
return buffer;
},
hash: function hash(data) {
return (0, _crypto.hash)(this.serialize(data));
}
};
Object.compare = function (obj1, obj2) {
// loop through properties in object 1
for (var p in obj1) {
// check property exists on both objects
if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false;
switch ((0, _typeof2["default"])(obj1[p])) {
// deep compare objects
case 'object':
if (!Object.compare(obj1[p], obj2[p])) return false;
break;
// compare function code
case 'function':
if (typeof obj2[p] === 'undefined' || p !== 'compare' && obj1[p].toString() !== obj2[p].toString()) return false;
break;
// compare values
default:
if (obj1[p] !== obj2[p]) return false;
}
} // check object 2 for any extra properties
for (var _p in obj2) {
if (typeof obj1[_p] === 'undefined') return false;
}
return true;
};
/**
* Validate path from tree root to some table
* @param {Object} proof
* @param {string} stateHash
* @param {Object} key
* @returns {string}
*/
function verifyTable(proof, stateHash, key) {
// validate proof of table existence in root tree
var tableProof = new _merklePatricia.MapProof(proof, IndexCoordinates, _hexadecimal.Hash);
if (tableProof.merkleRoot !== stateHash) {
throw new Error('Table proof is corrupted');
}
var rootHash; // get root hash of the table
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = tableProof.entries.keys()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var k = _step.value;
// use `Object.compare` for 'deep' key comparison, because keys may be objects
if (Object.compare(k, key)) {
rootHash = tableProof.entries.get(k);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (typeof rootHash === 'undefined') {
throw new Error('Table not found in the root tree');
}
return rootHash;
}
},{"../crypto":100,"../types/hexadecimal":120,"../types/primitive":123,"./merkle-patricia":94,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/typeof":22}],97:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.send = send;
exports.sendQueue = sendQueue;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _axios = _interopRequireDefault(require("axios"));
var _convert = require("../types/convert");
var ATTEMPTS = 10;
var ATTEMPT_TIMEOUT = 500;
/**
* Send transaction to the blockchain
* @param {string} explorerBasePath
* @param {Uint8Array | string} transaction
* @param {number} attempts
* @param {number} timeout
* @return {Promise}
*/
function send(_x, _x2) {
return _send.apply(this, arguments);
}
/**
* Sends several transactions to the blockchain.
*
* @param {string} explorerBasePath
* @param {Array} transactions
* @param {number} attempts
* @param {number} timeout
* @return {Promise}
*/
function _send() {
_send = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee(explorerBasePath, transaction) {
var attempts,
timeout,
sleep,
response,
txHash,
count,
errored,
_response,
_args = arguments;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
sleep = function _ref(timeout) {
return new Promise(function (resolve) {
setTimeout(resolve, timeout);
});
};
attempts = _args.length > 2 && _args[2] !== undefined ? _args[2] : ATTEMPTS;
timeout = _args.length > 3 && _args[3] !== undefined ? _args[3] : ATTEMPT_TIMEOUT;
if (!(typeof explorerBasePath !== 'string')) {
_context.next = 5;
break;
}
throw new TypeError('Explorer base path endpoint of wrong data type is passed. String is required.');
case 5:
attempts = +attempts;
timeout = +timeout;
if (typeof transaction !== 'string') {
transaction = (0, _convert.uint8ArrayToHexadecimal)(new Uint8Array(transaction));
}
_context.next = 10;
return _axios["default"].post("".concat(explorerBasePath), {
tx_body: transaction
});
case 10:
response = _context.sent;
txHash = response.data.tx_hash;
count = attempts;
errored = false;
case 14:
if (!(count >= 0)) {
_context.next = 32;
break;
}
_context.prev = 15;
_context.next = 18;
return _axios["default"].get("".concat(explorerBasePath, "?hash=").concat(txHash));
case 18:
_response = _context.sent;
if (!(_response.data.type === 'committed')) {
_context.next = 21;
break;
}
return _context.abrupt("return", txHash);
case 21:
errored = false;
_context.next = 27;
break;
case 24:
_context.prev = 24;
_context.t0 = _context["catch"](15);
errored = true;
case 27:
count--;
_context.next = 30;
return sleep(timeout);
case 30:
_context.next = 14;
break;
case 32:
if (!errored) {
_context.next = 36;
break;
}
throw new Error('The request failed or the blockchain node did not respond.');
case 36:
throw new Error('The transaction was not accepted to the block for the expected period.');
case 37:
case "end":
return _context.stop();
}
}
}, _callee, null, [[15, 24]]);
}));
return _send.apply(this, arguments);
}
function sendQueue(explorerBasePath, transactions) {
var attempts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ATTEMPTS;
var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ATTEMPT_TIMEOUT;
var index = 0;
var responses = [];
return function shift() {
var transaction = transactions[index++];
return send(explorerBasePath, transaction, attempts, timeout).then(function (response) {
responses.push(response);
if (index < transactions.length) {
return shift();
} else {
return responses;
}
});
}();
}
},{"../types/convert":118,"@babel/runtime/helpers/asyncToGenerator":4,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/regenerator":24,"axios":32}],98:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CONFIG = void 0;
var _crypto = require("./crypto");
/**
* Default global library configuration.
*
* Redefine, if needed.
*/
var CONFIG = {
// Library will use NIST cryptography by default.
crypto: _crypto.CRYPTO.NIST
};
exports.CONFIG = CONFIG;
},{"./crypto":100}],99:[function(require,module,exports){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hash = hash;
exports.sign = sign;
exports.verifySignature = verifySignature;
exports.keyPair = keyPair;
exports.fromSeed = fromSeed;
exports.randomUint64 = randomUint64;
exports.SIGNATURE_LENGTH = exports.HASH_LENGTH = exports.SECRET_KEY_LENGTH = exports.PUBLIC_KEY_LENGTH = void 0;
var _bigInteger = _interopRequireDefault(require("big-integer"));
var _tweetnacl = _interopRequireDefault(require("tweetnacl"));
var _exonumWebcryptoGost = _interopRequireWildcard(require("../third-party/exonum-webcrypto-gost"));
var _generic = require("../types/generic");
var _message = require("../types/message");
var validate = _interopRequireWildcard(require("../types/validate"));
var convert = _interopRequireWildcard(require("../types/convert"));
var PUBLIC_KEY_LENGTH = 64;
exports.PUBLIC_KEY_LENGTH = PUBLIC_KEY_LENGTH;
var SECRET_KEY_LENGTH = 32;
exports.SECRET_KEY_LENGTH = SECRET_KEY_LENGTH;
var HASH_LENGTH = 32;
exports.HASH_LENGTH = HASH_LENGTH;
var SIGNATURE_LENGTH = 64;
/**
* Get GOST R 34.11 hash
* @param {Object|Array|Uint8Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {string}
*/
exports.SIGNATURE_LENGTH = SIGNATURE_LENGTH;
function hash(data, type) {
var buffer;
var hasher = new _exonumWebcryptoGost.GostDigest({
name: 'GOST R 34.11',
version: 2012
});
var digest;
if ((0, _generic.isType)(type)) {
buffer = type.serialize(data);
} else if ((0, _message.isTransaction)(type)) {
var payloadBuffer = data.schema.encode(data.payload).finish();
var chainIdBytesBuffer = data.chainIdBytes;
var authorBuffer = convert.hexadecimalToUint8Array(data.author);
var merged = new Uint8Array(chainIdBytesBuffer.length + payloadBuffer.length + authorBuffer.length);
merged.set(chainIdBytesBuffer);
merged.set(payloadBuffer, chainIdBytesBuffer.length);
merged.set(authorBuffer, chainIdBytesBuffer.length + payloadBuffer.length);
buffer = merged;
} else {
if (type !== undefined) {
throw new TypeError('Wrong type of data.');
}
if (data instanceof Uint8Array) {
buffer = data;
} else {
if (!Array.isArray(data)) {
throw new TypeError('Invalid data parameter.');
}
buffer = new Uint8Array(data);
}
}
digest = hasher.digest(new Uint8Array(buffer));
return convert.uint8ArrayToHexadecimal(new Uint8Array(digest));
}
/**
* Get GOST R 34.10 signature
* @param {string} secretKey
* @param {Object|Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {Promise<string>}
*/
function sign(secretKey, data, type) {
var coding = new _exonumWebcryptoGost.GostCoding();
var buffer;
if (!validate.validateHexadecimal(secretKey, SECRET_KEY_LENGTH)) {
throw new TypeError('secretKey of wrong type is passed. Hexadecimal expected.');
}
if ((0, _generic.isType)(type)) {
buffer = new Uint8Array(type.serialize(data));
} else if ((0, _message.isTransaction)(type)) {
var ser = new Uint8Array(type.serialize(data));
var chainIdBytesBuffer = new Uint8Array(type.chain_id_bytes);
buffer = new Uint8Array(chainIdBytesBuffer.length + ser.length);
buffer.set(chainIdBytesBuffer);
buffer.set(ser, chainIdBytesBuffer.length);
} else {
if (type !== undefined) {
throw new TypeError('Wrong type of data.');
}
if (data instanceof Uint8Array) {
buffer = data;
} else {
if (!Array.isArray(data)) {
throw new TypeError('Invalid data parameter.');
}
buffer = new Uint8Array(data);
}
}
var secretKeyBuf = coding.Hex.decode(secretKey);
return _exonumWebcryptoGost["default"].subtle.importKey('raw', secretKeyBuf, {
id: 'id-tc26-gost3410-12-256',
keySize: 32,
length: 256,
mode: 'SIGN',
name: 'GOST R 34.10',
namedCurve: 'S-256-A',
procreator: 'CP',
version: 2012
}, false, ['sign']).then(function (key) {
return _exonumWebcryptoGost["default"].subtle.sign('GOST R 34.10/GOST R 34.11', key, buffer);
}).then(function (signature) {
return coding.Hex.encode(signature, 'big').split(/[^0-9a-f]+/).join('');
});
}
/**
* Verifies GOST R 34.10 signature
* @param {string} signature
* @param {string} publicKey
* @param {Object|Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {Promise<boolean>}
*/
function verifySignature(signature, publicKey, data, type) {
var buffer;
if (!validate.validateHexadecimal(signature, SIGNATURE_LENGTH)) {
throw new TypeError('Signature of wrong type is passed. Hexadecimal expected.');
}
if (!validate.validateHexadecimal(publicKey, PUBLIC_KEY_LENGTH)) {
throw new TypeError('publicKey of wrong type is passed. Hexadecimal expected.');
}
if ((0, _generic.isType)(type)) {
buffer = new Uint8Array(type.serialize(data));
} else if ((0, _message.isTransaction)(type)) {
var ser = new Uint8Array(type.serialize(data));
var chainIdBytesBuffer = new Uint8Array(type.chain_id_bytes);
buffer = new Uint8Array(chainIdBytesBuffer.length + ser.length);
buffer.set(chainIdBytesBuffer);
buffer.set(ser, chainIdBytesBuffer.length);
} else if (type === undefined) {
if (data instanceof Uint8Array) {
buffer = data;
} else if (Array.isArray(data)) {
buffer = new Uint8Array(data);
}
} else {
throw new TypeError('Wrong type of data.');
}
var signatureBuf = _exonumWebcryptoGost["default"].coding.Hex.decode(signature, 'big');
var publicKeyBuf = _exonumWebcryptoGost["default"].coding.Hex.decode(publicKey);
return _exonumWebcryptoGost["default"].subtle.importKey('raw', publicKeyBuf, {
name: 'GOST R 34.10-256/VN',
id: 'id-tc26-gost3410-12-256',
namedCurve: 'S-256-A'
}, true, ['verify']).then(function (key) {
return _exonumWebcryptoGost["default"].subtle.verify('GOST R 34.10/GOST R 34.11', key, signatureBuf, new Uint8Array(buffer));
});
}
/**
* Generate random pair of publicKey and secretKey
* @return {Promise<Object>}
* publicKey {string}
* secretKey {string}
*/
function keyPair() {
return _exonumWebcryptoGost["default"].subtle.generateKey({
name: 'GOST R 34.10-256/VN'
}, true, ['sign', 'verify']).then(function (pair) {
return {
publicKey: convert.uint8ArrayToHexadecimal(new Uint8Array(pair.publicKey.buffer)),
secretKey: convert.uint8ArrayToHexadecimal(new Uint8Array(pair.privateKey.buffer))
};
});
}
/**
* Returns a new signing key pair generated deterministically from a 32-byte seed
* @return {Object}
* publicKey {string}
* secretKey {Promise<string>}
*/
function fromSeed(seed) {
var pair = _exonumWebcryptoGost["default"].subtle.generateKey(seed);
var publicKey = convert.uint8ArrayToHexadecimal(pair.publicKey);
var secretKey = convert.uint8ArrayToHexadecimal(pair.secretKey);
return new Promise(function (resolve) {
return resolve({
publicKey: publicKey,
secretKey: secretKey
});
});
}
/**
* Get random number of cryptographic quality
* @returns {string}
*/
function randomUint64() {
var buffer = _tweetnacl["default"].randomBytes(8);
return _bigInteger["default"].fromArray(Array.from(buffer), 256).toString();
}
},{"../third-party/exonum-webcrypto-gost":104,"../types/convert":118,"../types/generic":119,"../types/message":122,"../types/validate":124,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/interopRequireWildcard":12,"big-integer":59,"tweetnacl":88}],100:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hash = hash;
exports.sign = sign;
exports.verifySignature = verifySignature;
exports.keyPair = keyPair;
exports.fromSeed = fromSeed;
exports.randomUint64 = randomUint64;
exports.IMPLS = exports.CRYPTO = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var NIST_CRYPTO = _interopRequireWildcard(require("./nist"));
var GOST_CRYPTO = _interopRequireWildcard(require("./gost"));
var _IMPLS;
/**
* Defines a different sets of available cryptographic primitives.
*
* This constant is used in global library configuration.
*/
var CRYPTO = {
NIST: 0,
GOST: 1
};
exports.CRYPTO = CRYPTO;
var IMPLS = (_IMPLS = {}, (0, _defineProperty2["default"])(_IMPLS, CRYPTO.GOST, GOST_CRYPTO), (0, _defineProperty2["default"])(_IMPLS, CRYPTO.NIST, NIST_CRYPTO), _IMPLS);
/** Helper function that returns set of cryptographic primitives that matches configuration. */
exports.IMPLS = IMPLS;
function currentCrypto() {
var CONFIG = require('../config.js').CONFIG;
return IMPLS[CONFIG.crypto];
} // Define getters for backend-specific constants.
// This is mandatory.
Object.defineProperties(module.exports, {
PUBLIC_KEY_LENGTH: {
enumerable: true,
get: function get() {
return currentCrypto().PUBLIC_KEY_LENGTH;
}
},
HASH_LENGTH: {
enumerable: true,
get: function get() {
return currentCrypto().HASH_LENGTH;
}
},
SECRET_KEY_LENGTH: {
enumerable: true,
get: function get() {
return currentCrypto().SECRET_KEY_LENGTH;
}
},
SIGNATURE_LENGTH: {
enumerable: true,
get: function get() {
return currentCrypto().SIGNATURE_LENGTH;
}
}
});
/**
* Get hash.
*
* Hash algorithm depends on the value of the global library configuration.
*
* @param {Object|Array|Uint8Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {string}
*/
function hash(data, type) {
return currentCrypto().hash(data, type);
}
/**
* Get signature.
*
* Signature algorithm depends on the value of the global library configuration.
*
* @param {string} secretKey
* @param {Object|Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {Promise<string>}
*/
function sign(secretKey, data, type) {
return currentCrypto().sign(secretKey, data, type);
}
/**
* Verifies signature.
*
* Signature algorithm depends on the value of the global library configuration.
*
* @param {string} signature
* @param {string} publicKey
* @param {Object|Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {Promise<boolean>}
*/
function verifySignature(signature, publicKey, data, type) {
return currentCrypto().verifySignature(signature, publicKey, data, type);
}
/**
* Generate random pair of publicKey and secretKey
* @return {Promise<Object>}
* publicKey {string}
* secretKey {string}
*/
function keyPair() {
return currentCrypto().keyPair();
}
/**
* Returns a new signing key pair generated deterministically from a seed
* @return {Object}
* publicKey {string}
* secretKey {Promise<String>}
*/
function fromSeed(seed) {
return currentCrypto().fromSeed(seed);
}
/**
* Get random number of cryptographic quality
* @returns {string}
*/
function randomUint64() {
return currentCrypto().randomUint64();
}
},{"../config.js":98,"./gost":99,"./nist":101,"@babel/runtime/helpers/defineProperty":8,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/interopRequireWildcard":12}],101:[function(require,module,exports){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hash = hash;
exports.sign = sign;
exports.verifySignature = verifySignature;
exports.keyPair = keyPair;
exports.fromSeed = fromSeed;
exports.randomUint64 = randomUint64;
exports.SECRET_KEY_LENGTH = exports.HASH_LENGTH = void 0;
var _bigInteger = _interopRequireDefault(require("big-integer"));
var _sha = _interopRequireDefault(require("sha.js"));
var _tweetnacl = _interopRequireDefault(require("tweetnacl"));
var _generic = require("../types/generic");
var _message = require("../types/message");
var validate = _interopRequireWildcard(require("../types/validate"));
var convert = _interopRequireWildcard(require("../types/convert"));
/**
* Byte size of a hash.
* @type {number}
*/
var HASH_LENGTH = 32;
exports.HASH_LENGTH = HASH_LENGTH;
var SECRET_KEY_LENGTH = 64;
/**
* Get SHA256 hash
* @param {Object|Array|Uint8Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {string}
*/
exports.SECRET_KEY_LENGTH = SECRET_KEY_LENGTH;
function hash(data, type) {
var buffer;
if ((0, _generic.isType)(type)) {
buffer = type.serialize(data);
} else if ((0, _message.isTransaction)(type)) {
var payloadBuffer = data.schema.encode(data.payload).finish();
var chainIdBytesBuffer = data.chainIdBytes;
var authorBuffer = convert.hexadecimalToUint8Array(data.author);
return (0, _sha["default"])('sha256').update(chainIdBytesBuffer).update(payloadBuffer).update(authorBuffer).digest('hex');
} else {
if (type !== undefined) {
throw new TypeError('Wrong type of data.');
}
if (data instanceof Uint8Array) {
buffer = data;
} else {
if (!Array.isArray(data)) {
throw new TypeError('Invalid data parameter.');
}
buffer = new Uint8Array(data);
}
}
return (0, _sha["default"])('sha256').update(buffer, 'utf8').digest('hex');
}
/**
* Get ED25519 signature
* @param {string} secretKey
* @param {Object|Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {Promise<string>}
*/
function sign(secretKey, data, type) {
var secretKeyUint8Array;
var buffer;
var signature;
if (!validate.validateHexadecimal(secretKey, 64)) {
throw new TypeError('secretKey of wrong type is passed. Hexadecimal expected.');
}
secretKeyUint8Array = convert.hexadecimalToUint8Array(secretKey);
if ((0, _generic.isType)(type)) {
buffer = new Uint8Array(type.serialize(data));
} else if ((0, _message.isTransaction)(type)) {
var chainIdBuffer = new Uint8Array(type.chain_id_bytes);
var dataBuffer = new Uint8Array(type.serialize(data));
buffer = new Uint8Array(chainIdBuffer.length + dataBuffer.length);
buffer.set(chainIdBuffer);
buffer.set(dataBuffer, chainIdBuffer.length);
} else {
if (type !== undefined) {
throw new TypeError('Wrong type of data.');
}
if (data instanceof Uint8Array) {
buffer = data;
} else {
if (!Array.isArray(data)) {
throw new TypeError('Invalid data parameter.');
}
buffer = new Uint8Array(data);
}
}
signature = _tweetnacl["default"].sign.detached(buffer, secretKeyUint8Array);
return new Promise(function (resolve) {
return resolve(convert.uint8ArrayToHexadecimal(signature));
});
}
/**
* Verifies ED25519 signature
* @param {string} signature
* @param {string} publicKey
* @param {Object|Array} data - object of NewType type or array of 8-bit integers
* @param {Type|Transaction} [type] - optional, used only if data of {Object} type is passed
* @return {Promise<boolean>}
*/
function verifySignature(signature, publicKey, data, type) {
var signatureUint8Array;
var publicKeyUint8Array;
var buffer;
if (!validate.validateHexadecimal(signature, 64)) {
throw new TypeError('Signature of wrong type is passed. Hexadecimal expected.');
}
signatureUint8Array = convert.hexadecimalToUint8Array(signature);
if (!validate.validateHexadecimal(publicKey)) {
throw new TypeError('publicKey of wrong type is passed. Hexadecimal expected.');
}
publicKeyUint8Array = convert.hexadecimalToUint8Array(publicKey);
if ((0, _generic.isType)(type)) {
buffer = new Uint8Array(type.serialize(data));
} else if ((0, _message.isTransaction)(type)) {
var chainIdBuffer = (0, _message.chainIdToBytes)(type.chainId);
var dataBuffer = new Uint8Array(type.serialize(data));
buffer = new Uint8Array(chainIdBuffer.length + dataBuffer.length);
buffer.set(chainIdBuffer);
buffer.set(dataBuffer, chainIdBuffer.length);
} else if (type === undefined) {
if (data instanceof Uint8Array) {
buffer = data;
} else if (Array.isArray(data)) {
buffer = new Uint8Array(data);
}
} else {
throw new TypeError('Wrong type of data.');
}
return new Promise(function (resolve) {
return resolve(_tweetnacl["default"].sign.detached.verify(buffer, signatureUint8Array, publicKeyUint8Array));
});
}
/**
* Generate random pair of publicKey and secretKey
* @return {Object}
* publicKey {string}
* secretKey {string}
*/
function keyPair() {
var pair = _tweetnacl["default"].sign.keyPair();
var publicKey = convert.uint8ArrayToHexadecimal(pair.publicKey);
var secretKey = convert.uint8ArrayToHexadecimal(pair.secretKey);
return new Promise(function (resolve) {
return resolve({
publicKey: publicKey,
secretKey: secretKey
});
});
}
/**
* Returns a new signing key pair generated deterministically from a 32-byte seed
* @return {Object}
* publicKey {string}
* secretKey {Promise<string>}
*/
function fromSeed(seed) {
var pair = _tweetnacl["default"].sign.keyPair.fromSeed(seed);
var publicKey = convert.uint8ArrayToHexadecimal(pair.publicKey);
var secretKey = convert.uint8ArrayToHexadecimal(pair.secretKey);
return new Promise(function (resolve) {
return resolve({
publicKey: publicKey,
secretKey: secretKey
});
});
}
/**
* Get random number of cryptographic quality
* @returns {string}
*/
function randomUint64() {
var buffer = _tweetnacl["default"].randomBytes(8);
return _bigInteger["default"].fromArray(Array.from(buffer), 256).toString();
}
},{"../types/convert":118,"../types/generic":119,"../types/message":122,"../types/validate":124,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/interopRequireWildcard":12,"big-integer":59,"sha.js":81,"tweetnacl":88}],102:[function(require,module,exports){
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isObject = isObject;
exports.verifyElement = verifyElement;
exports.cleanZeroValuedFields = cleanZeroValuedFields;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
function isStrictTypedArray(arr) {
return arr instanceof Int8Array || arr instanceof Int16Array || arr instanceof Int32Array || arr instanceof Uint8Array || arr instanceof Uint8ClampedArray || arr instanceof Uint16Array || arr instanceof Uint32Array || arr instanceof Float32Array || arr instanceof Float64Array;
}
/**
* Check if element is of type Object
* @param obj
* @returns {boolean}
*/
function isObject(obj) {
return (0, _typeof2["default"])(obj) === 'object' && !Array.isArray(obj) && obj !== null && !(obj instanceof Date);
}
/**
* @param {Object} element
* @returns {boolean}
*/
function verifyElement(element) {
switch ((0, _typeof2["default"])(element)) {
case 'string':
return element !== '0' && element.length !== 0;
case 'number':
return element !== 0;
}
return true;
}
/**
* @param {Object} data
* @param {Object} object
* @returns {Object}
*/
function cleanZeroValuedFields(data, object) {
var keys = Object.keys(data);
keys.forEach(function (key) {
if (isStrictTypedArray(data[key]) || data[key] instanceof Array) {
object[key] = data[key];
} else {
if ((0, _typeof2["default"])(data[key]) === 'object') {
object[key] = cleanZeroValuedFields(data[key], {});
} else {
if (verifyElement(data[key])) {
object[key] = data[key];
}
}
}
});
return object;
}
},{"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/typeof":22}],103:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
version: true,
CONFIG: true
};
exports.CONFIG = exports.version = void 0;
var _types = require("./types");
Object.keys(_types).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _types[key];
}
});
});
var _crypto = require("./crypto");
Object.keys(_crypto).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _crypto[key];
}
});
});
var _blockchain = require("./blockchain");
Object.keys(_blockchain).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _blockchain[key];
}
});
});
var version = '@@version';
exports.version = version;
var CONFIG = require('./config').CONFIG;
exports.CONFIG = CONFIG;
},{"./blockchain":93,"./config":98,"./crypto":100,"./types":121}],104:[function(require,module,exports){
"use strict";
module.exports = require('./lib/gostCrypto');
module.exports.GostASN1 = require('./lib/gostASN1');
module.exports.GostCert = require('./lib/gostCert');
module.exports.GostCipher = require('./lib/gostCipher');
module.exports.GostCMS = require('./lib/gostCMS');
module.exports.GostCoding = require('./lib/gostCoding');
module.exports.GostDigest = require('./lib/gostDigest');
module.exports.GostEngine = require('./lib/gostEngine');
module.exports.GostKeys = require('./lib/gostKeys');
module.exports.GostRandom = require('./lib/gostRandom');
module.exports.GostSecurity = require('./lib/gostSecurity');
module.exports.GostSign = require('./lib/gostSign');
module.exports.GostViewer = require('./lib/gostViewer');
},{"./lib/gostASN1":105,"./lib/gostCMS":106,"./lib/gostCert":107,"./lib/gostCipher":108,"./lib/gostCoding":109,"./lib/gostCrypto":110,"./lib/gostDigest":111,"./lib/gostEngine":112,"./lib/gostKeys":113,"./lib/gostRandom":114,"./lib/gostSecurity":115,"./lib/gostSign":116,"./lib/gostViewer":117}],105:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file PKCS ASN.1 message syntax and converters
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostCrypto', 'gostCoding', 'gostSecurity'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostCrypto'), require('./gostCoding'), require('./gostSecurity'));
} else {
root.GostASN1 = factory(root.gostCrypto, root.GostCoding, root.GostSecurity);
} // </editor-fold>
})(void 0, function (gostCrypto) {
/*
* Service functions
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var CryptoOperationData = root.ArrayBuffer;
var Date = root.Date; // Security parameters
var algorithms = gostCrypto.security.algorithms;
var names = gostCrypto.security.names;
var identifiers = gostCrypto.security.identifiers;
var attributes = gostCrypto.security.attributes;
var parameters = gostCrypto.security.parameters; // BER coding
var BER = gostCrypto.coding.BER; // PEM coding
var PEM = gostCrypto.coding.PEM; // Chars coding
var Chars = gostCrypto.coding.Chars; // Hex coding;
var Hex = gostCrypto.coding.Hex; // Hex coding;
var Int16 = gostCrypto.coding.Int16; // Expand javascript object
function expand() {
var r = {};
for (var i = 0, n = arguments.length; i < n; i++) {
var item = arguments[i];
if (_typeof(item) === 'object') for (var name in item) {
r[name] = item[name];
}
}
return r;
} // Swap bytes in buffer
function swapBytes(src) {
if (src instanceof CryptoOperationData) src = new Uint8Array(src);
var dst = new Uint8Array(src.length);
for (var i = 0, n = src.length; i < n; i++) {
dst[n - i - 1] = src[i];
}
return dst.buffer;
}
function isBinary(value) {
return value instanceof CryptoOperationData || value.buffer instanceof CryptoOperationData;
} // Left pad zero
function lpad(n, width) {
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
} // Nearest power 2
function npw2(n) {
return n <= 2 ? n : n <= 4 ? 4 : n <= 8 ? 8 : n <= 16 ? 16 : n <= 32 ? 32 : n <= 64 ? 64 : n <= 128 ? 128 : n <= 256 ? 256 : n < 512 ? 512 : n < 1024 ? 1024 : undefined;
} // String int encode/decode to buffer
var SInt = {
encode: function encode(value, endian) {
return '0x' + Hex.encode(value, endian);
},
decode: function decode(value, endian, len) {
if (typeof value === 'number') value = value.toString(16);
var s = value.replace('0x', '');
len = len || npw2(s.length);
return Hex.decode(lpad(s, len), endian);
}
}; // Assert invalid message
function assert(value) {
if (value) throw Error('Invalid format');
}
function defineProperty(object, name, descriptor, enumerable) {
if (_typeof(descriptor) !== 'object') descriptor = {
value: descriptor
};
if (enumerable !== undefined) descriptor.enumerable = enumerable;
Object.defineProperty(object, name, descriptor);
}
function defineProperties(object, properties, enumerable) {
for (var name in properties) {
defineProperty(object, name, properties[name], enumerable);
}
}
function getOwnPropertyDescriptor(object, name) {
return Object.getOwnPropertyDescriptor(object, name);
} // </editor-fold>
/*
* Base ASN.1 types and definitions
*
*/
// <editor-fold defaultstate="collapsed">
// Encode object primitive
function _encode(format, object, tagNumber, tagClass, tagConstructed, uniformTitle) {
assert(object === undefined);
var source = {
tagNumber: tagNumber,
tagClass: tagClass || 0x00,
tagConstructed: tagConstructed || false,
object: object
}; // Output format
format = format || 'DER';
if (format === 'DER' || format === 'CER') source = BER.encode(source, format);
if (format === 'PEM') source = PEM.encode(source, uniformTitle);
return source;
} // Decode object primitive
function _decode(source, tagNumber, tagClass, tagConstructed, uniformTitle) {
assert(source === undefined); // Decode PEM
if (typeof source === 'string') source = PEM.decode(source, uniformTitle, false); // Decode binary data
if (source instanceof CryptoOperationData) {
try {
source = PEM.decode(Chars.encode(source), uniformTitle, true);
} catch (e) {
source = BER.decode(source);
}
}
tagClass = tagClass || 0;
tagConstructed = tagConstructed || false; // Restore context implicit formats
if (source.tagNumber === undefined) {
source = _encode(true, source.object, tagNumber, tagClass, source.object instanceof Array);
source = BER.decode(source);
} // Check format
assert(source.tagClass !== tagClass || source.tagNumber !== tagNumber || source.tagConstructed !== tagConstructed); // Clone value define from redefine original
if (tagClass === 0 && tagNumber === 0x05) return null;else return source.object;
} // Create class based on super
function extend(Super, Class, propertiesObject, propertiesClass) {
// If constructor not defined
if (typeof Class !== 'function') {
propertiesClass = propertiesObject;
propertiesObject = Class;
Class = function Class() {
Super.apply(this, arguments);
};
} // Create prototype properties
Class.prototype = Object.create(Super.prototype, {
constructor: {
value: Class
},
superclass: {
value: Super.prototype
}
});
if (propertiesObject) defineProperties(Class.prototype, propertiesObject); // Inherites super class properties
if (Super !== Object) for (var name in Super) {
Class[name] = Super[name];
}
Class["super"] = Super;
if (propertiesClass) defineProperties(Class, propertiesClass, true);
return Class;
} // Base class
var ASN1Object = extend(Object, function (object) {
this.object = object;
}, {
// Call set method for a class property
_set: function _set(Class, propName, value) {
Class.property(propName).set.call(this, value);
},
// Call get method for a class property
_get: function _get(Class, propName) {
return Class.property(propName).get.call(this);
},
// Call method for a class
_call: function _call(Class, methodName, args) {
return Class.method(methodName).apply(this, args);
},
hasProperty: function hasProperty(propName) {
return this.hasOwnProperty(propName) || !!this.constructor.property(propName);
},
encode: function encode() {
return this.object;
}
}, {
decode: function decode(source) {
return new this(source);
},
// Find ingerited property
property: function property(propName) {
var proto = this.prototype;
while (proto) {
var descriptor = getOwnPropertyDescriptor(proto, propName);
if (descriptor) return descriptor;else proto = proto.superclass;
}
},
// Find method
method: function method(methodName) {
var proto = this.prototype;
while (proto) {
if (proto[methodName]) return proto[methodName];else proto = proto.superclass;
}
}
}); // Primitive metaclass
var PRIMITIVE = function PRIMITIVE(tagNumber) {
return extend(ASN1Object, {
encode: function encode(format) {
return _encode(format, this.object, tagNumber);
}
}, {
decode: function decode(source) {
return new this(_decode(source, tagNumber));
}
});
};
var ANY = ASN1Object;
var BOOLEAN = PRIMITIVE(0x01);
var IA5String = PRIMITIVE(0x16);
var NumericString = PRIMITIVE(0x12);
var PrintableString = PRIMITIVE(0x13);
var TeletexString = PRIMITIVE(0x14);
var UTF8String = PRIMITIVE(0x0c);
var UTCTime = PRIMITIVE(0x17);
var GeneralizedTime = PRIMITIVE(0x18);
var UniversalString = PRIMITIVE(0x1C);
var BMPString = PRIMITIVE(0x1e);
var NULL = extend(PRIMITIVE(0x05), {
object: {
get: function get() {
return null;
},
set: function set(object) {
assert(object !== null);
}
}
}); // Primitive class with value coding
var PRIMITIVE_CODE = function PRIMITIVE_CODE(tagNumber) {
// Base class primitive
var Class = extend(PRIMITIVE(tagNumber), function (object) {
if (this instanceof Class) Class["super"].apply(this, arguments);else return CODE(object);
}); // Create Class with encoded
function CODE(structure) {
// Structured class
return extend(PRIMITIVE(tagNumber), function (object) {
Class["super"].call(this, object);
}, {
// Transformation to code values
encode: function encode(format) {
return _encode(format, structure[this.object], tagNumber);
}
}, {
decode: function decode(source) {
var id = _decode(source, tagNumber);
for (var name in structure) {
if (id === structure[name]) return new this(name);
}
assert(true);
}
});
}
return Class;
};
var INTEGER = PRIMITIVE_CODE(0x02);
var ENUMERATED = PRIMITIVE_CODE(0x0a);
var OCTET_STRING = function () {
// Base class primitive
var Class = extend(PRIMITIVE(0x04), function (object) {
if (this instanceof Class) Class["super"].apply(this, arguments);else return WRAPPING(object);
}); // Wrapping class
function WRAPPING(WrappedClass) {
if (WrappedClass) {
return extend(WrappedClass, {
encode: function encode(format) {
return _encode(format, WrappedClass.method('encode').call(this, true), 0x04);
}
}, {
decode: function decode(source) {
return WrappedClass.decode.call(this, _decode(source, 0x04));
}
});
} else return Class;
}
return Class;
}();
var BIT_STRING = function () {
// Base class primitive
var Class = extend(PRIMITIVE(0x03), function (object) {
if (this instanceof Class) Class["super"].apply(this, arguments);else if (_typeof(object) === 'object') return MASK(object);else return WRAPPING(object);
}); // Wrapping class
function WRAPPING(WrappedClass) {
if (WrappedClass) {
return extend(WrappedClass, {
encode: function encode(format) {
return _encode(format, WrappedClass.method('encode').call(this, true), 0x03);
}
}, {
decode: function decode(source) {
return WrappedClass.decode.call(this, _decode(source, 0x03));
}
});
} else return Class;
} // Create new class for a mask
function MASK(structure) {
// Bit string masked class
return extend(ASN1Object, function (object, numbits) {
ASN1Object.call(this, object);
this.numbits = numbits || 0;
}, {
encode: function encode(format) {
var object = this.object,
data = [];
if (object instanceof Array) {
for (var i = 0, n = object.length; i < n; i++) {
var j = structure[object[i]];
if (j !== undefined) data[j] = '1';
}
for (var i = 0, n = Math.max(data.length, this.numbits); i < n; i++) {
if (!data[i]) data[i] = '0';
}
data = data.join('');
} else data = '0';
return _encode(format, data, 0x03);
}
}, {
// Transformation to array of values
decode: function decode(source) {
var data = _decode(source, 0x03),
object = [];
for (var name in structure) {
var i = structure[name];
if (data.charAt(i) === '1') object.push(name);
}
return new this(object, data.length);
}
});
}
return Class;
}(); // Combine sequence object properties with owner object
var COMBINE = function COMBINE(Class) {
Class.combine = function (owner, valueName) {
for (var name in Class.prototype) {
if (Class.prototype.hasOwnProperty(name) && !owner.hasProperty(name)) {
defineProperty(owner, name, function (name) {
return {
get: function get() {
// Get object property
return this[valueName] && this[valueName][name];
},
set: function set(object) {
// Set object property
if (!this[valueName]) this[valueName] = {};
this[valueName][name] = object;
},
configurable: false,
enumerable: true
};
}(name));
}
}
};
return Class;
};
var SEQUENCE = function SEQUENCE(structure, uniformTitle) {
/**
* Create SEQUENCE ASN.1 metaclass
*
* @class GostASN1.Sequence
* @param {(Object|FormatedData)} object Initialization object
* @param {boolean} check Check structure after initialization
*/
var Class = extend(ASN1Object, function (object, check) {
// Define hidden properties
defineProperty(this, 'items', {
writable: true,
value: {}
});
if (typeof object === 'string' || object instanceof CryptoOperationData) this.decode(object);else if (object !== undefined) {
this.object = object; // Check structure
if (check) this.check();
}
}, {
object: {
get: function get() {
return this;
},
set: function set(object) {
if (object instanceof Class) {
// Set the same sequence class
this.items = object.items;
for (var name in structure) {
var ItemClass = this.getItemClass(name, this.items);
if (ItemClass.combine) ItemClass.combine(this, name);
}
} else {
// Set other object structure
var data = {};
for (var name in structure) {
var item = object[name];
var ItemClass = this.getItemClass(name, data);
if (item !== undefined) {
data[name] = new ItemClass(item);
} else if (ItemClass.combine) {
// Create combined object
data[name] = new ItemClass(object);
}
if (ItemClass.combine) ItemClass.combine(this, name);
}
this.items = data;
}
}
},
getItemClass: function getItemClass(name, items) {
return structure[name];
},
/**
* Encode the object
*
* @memberOf GostASN1.Sequence
* @instance
* @param {string} format Encoding format 'DER', 'CER' or 'PEM'
* @returns {FormatedData}
*/
encode: function encode(format) {
var source = [],
items = this.items; // Encode objects in structure
for (var name in structure) {
// console.log(name, 'encoding...', items[name]);
if (items[name]) {
var encoded = items[name].encode(true); // Source from object
if (encoded !== undefined) // Can be optional
source.push(encoded);
}
}
return _encode(format, source, 0x10, 0, true, uniformTitle);
},
/**
* Decode the source to self object
*
* @memberOf GostASN1.Sequence
* @instance
* @param {FormatedData} source Encoded data
*/
decode: function decode(source) {
this.object = this.constructor.decode(source);
},
/**
* Check the object structure
*
* @memberOf GostASN1.Sequence
* @instance
*/
check: function check() {
this.constructor.decode(this.encode(true));
}
}, {
/**
* Encode data values with creating object
*
* @memberOf GostASN1.Sequence
* @static
* @param {Object} object Javascript object to encoding
* @param {string} format Encoding format 'DER', 'CER' or 'PEM'
* @returns {FormatedData}
*/
encode: function encode(object, format) {
return new this(object).encode(format);
},
/**
* Decode source and create object
*
* @memberOf GostASN1.Sequence
* @static
* @param {FormatedData} source Encoded data
* @returns {GostASN1.Sequence}
*
*/
decode: function decode(source) {
// Decode structure
source = _decode(source, 0x10, 0, true, uniformTitle);
var i = 0,
result = new this(),
data = result.items = {};
for (var name in structure) {
// console.log(name, 'decoding...');
// try to create and decode object
var ItemClass = result.getItemClass(name, data);
var item = ItemClass.decode(source[i]); // success? item can be optional
if (item !== undefined) {
data[name] = item;
if (ItemClass.combine) ItemClass.combine(result, name);
i++;
}
}
return result;
}
}); // Append structure items
for (var name in structure) {
defineProperty(Class.prototype, name, function (name) {
return {
get: function get() {
// Get object property
return this.items[name] && this.items[name].object;
},
set: function set(object) {
// Set object property
if (object !== undefined) {
var ItemClass = this.getItemClass(name, this.items);
this.items[name] = new ItemClass(object);
} else delete this.items[name];
},
configurable: false,
enumerable: !structure[name].combine
};
}(name));
if (structure[name].combine) structure[name].combine(Class.prototype, name);
}
return Class;
};
var ATTRIBUTE = function ATTRIBUTE(structure, typeName, valueName, ownerDafaultType, uniformName) {
var BaseClass = SEQUENCE(structure, uniformName); // Define attribute sequence
var DEFINE = function DEFINE(typeSet, defaultType) {
typeName = typeName || 'type';
valueName = valueName || 'value';
defaultType = defaultType || ownerDafaultType || ANY;
var Class = extend(BaseClass, function (object) {
// Constructor - "matrioshka"
if (this instanceof Class) {
// Call super
BaseClass.apply(this, arguments);
} else return DEFINE.apply(this, arguments);
}, {
getItemClass: function getItemClass(name, items) {
var ItemClass = structure[name];
if (valueName === name) {
// Define type of value attribute based on type attribute
var type,
typeId = items && items[typeName];
if (typeId) {
var id = typeId.object;
if (typeSet) {
if (typeof typeSet === 'function') type = typeSet(id);else type = typeSet[id];
}
}
type = type || defaultType || ANY;
ItemClass = ItemClass === ANY ? type : ItemClass(type);
}
return ItemClass;
}
}); // Redefine type property
defineProperty(Class.prototype, typeName, {
get: function get() {
// Get value property of object
return this.items[typeName] && this.items[typeName].object;
},
set: function set() {
// Can't set type definition property separatery
assert(true);
},
configurable: false,
enumerable: true
});
return Class;
};
return DEFINE();
};
var OBJECT_IDENTIFIER = extend(ASN1Object, {
encode: function encode(format) {
var object = this.object;
object = /^(\d+\.)+\d+$/.test(object) ? object : identifiers[object];
assert(!object);
return _encode(format, object, 0x06);
}
}, {
decode: function decode(source) {
var object = _decode(source, 0x06);
return new this(names[object] || object);
}
});
var IMPLICIT = function IMPLICIT(Class) {
Class = Class || ANY; // Add constracted tag
return extend(Class, {
encode: function encode(format) {
// Format encoding without CTX header
var source = Class.method('encode').call(this, format);
if (typeof source === 'string' || source instanceof CryptoOperationData) return source;
if (source.tagNumber !== 0x04 && source.tagClass === 0 && !(source.object instanceof Array)) // Encode primitive source
return {
object: BER.encode(source, 'DER', true)
};else return {
object: source.object
};
}
}, {
decode: function decode(source) {
if (typeof source === 'string' || source instanceof CryptoOperationData) {
return Class.decode.call(this, source);
} else {
source = {
object: source.object,
header: source.header,
content: source.content
};
return Class.decode.call(this, source);
}
}
});
};
var EXPLICIT = function EXPLICIT(Class) {
Class = Class || ANY; // Add constracted tag
return extend(Class, {
encode: function encode(format) {
// Format encoding without CTX header
var source = Class.method('encode').call(this, format);
if (typeof source === 'string' || source instanceof CryptoOperationData) return source;
return {
object: [source]
};
}
}, {
decode: function decode(source) {
if (typeof source === 'string' || source instanceof CryptoOperationData) {
return Class.decode.call(this, source);
} else return Class.decode.call(this, source.object[0]);
}
});
};
var CTX = function CTX(number, ContentClass) {
function CTX() {
ContentClass.apply(this, arguments);
} // Create CTX number class with wrapped content class
return extend(ContentClass, CTX, {
encode: function encode(format) {
var source = ContentClass.method('encode').call(this, format);
if (typeof source === 'string' || source instanceof CryptoOperationData) return source;
source.tagNumber = number;
source.tagClass = 0x02;
source.tagConstructed = source.object instanceof Array;
return source;
}
}, {
decode: function decode(source) {
// Format decoding without CTX
assert(source.tagNumber !== undefined && (source.tagClass !== 0x02 || source.tagNumber !== number));
return ContentClass.decode.call(this, source);
}
});
};
var ARRAY_OF = function ARRAY_OF(tagNumber) {
return function (ItemClassDef, typeAndValue) {
// Difininition of item class
ItemClassDef = ItemClassDef || ANY; // Metaclass definition
var DEFINE = function DEFINE(typeSet, defaultType) {
// Define item class
var ItemClass = typeof ItemClassDef === 'function' && typeSet !== undefined ? ItemClassDef(typeSet, defaultType) : ItemClassDef;
if (typeAndValue) {
/**
* Create class with type and value structure<br><br>
*
* SET OF attribute and SEQUENCE OF attribute metaclass
*
* @class GostASN1.Set
* @param {Object} object object value
*/
var Class = extend(ASN1Object, function (object) {
// Constructor - "matrioshka"
if (this instanceof Class) {
// Define hidden items property
defineProperty(this, 'items', {
writable: true,
value: {}
}); // Call super
ASN1Object.call(this, object || {});
} else return DEFINE.apply(this, arguments);
}, {
object: {
get: function get() {
// refresh items from object properties
this.read();
return this;
},
set: function set(object) {
if (object instanceof Class) {
object.read();
this.items = object.items;
} else {
// Set other object structure
var data = {};
for (var id in object) {
var item = object[id];
data[id] = this.createItem(item, id);
}
this.items = data;
} // refresh object properties to items
this.reset();
}
},
createItem: function createItem(value, type) {
if (typeAndValue) {
var object = {};
object[typeAndValue.typeName] = type;
object[typeAndValue.valueName] = value;
} else object = value;
return new ItemClass(object);
},
getItemValue: function getItemValue(id) {
var item = this.items[id];
return typeAndValue ? item.object[typeAndValue.valueName] : item.object;
},
setItemValue: function setItemValue(id, value) {
var item = this.items[id];
if (typeAndValue) item.object[typeAndValue.valueName] = value;else item.object = value;
},
isItemType: function isItemType(id) {
return typeAndValue ? identifiers[id] : !isNaN(parseInt(id));
},
reset: function reset() {
// remove unused properties
var items = this.items;
for (var id in this) {
if (this.hasOwnProperty(id) && !this.items[id] && this.isItemType(id)) delete this[id];
} // add new properties
for (var id in items) {
this[id] = this.getItemValue(id);
}
},
read: function read() {
var items = this.items;
for (var id in this) {
if (this.isItemType(id)) {
if (!this.items[id]) {
items[id] = this.createItem(this[id], id);
this[id] = this.getItemValue(id);
} else if (this.getItemValue(id) !== this[id]) {
this.setItemValue(id, this[id]);
}
}
}
},
/**
* Encode the object
*
* @memberOf GostASN1.Set
* @instance
* @param {string} format Encoding format 'DER', 'CER' or 'PEM'
* @returns {FormatedData}
*/
encode: function encode(format) {
// refresh items from object properties
this.read(); // repare source
var object = this.items,
source = [];
for (var id in object) {
// console.log(id, object[id], 'encoding...');
var encoded = object[id].encode(true);
if (encoded !== undefined) source.push(encoded);
}
return _encode(format, source, tagNumber, 0, true);
},
/**
* Decode the source to self object
*
* @memberOf GostASN1.Set
* @instance
* @param {FormatedData} source Encoded data
*/
decode: function decode(source) {
this.object = this.constructor.decode(source);
},
/**
* Check the object structure
*
* @memberOf GostASN1.Set
* @instance
*/
check: function check() {
this.constructor.decode(this.encode(true));
}
}, {
/**
* Encode data values with creating object
*
* @memberOf GostASN1.Set
* @static
* @param {Object} object Javascript object to encoding
* @param {string} format Encoding format 'DER', 'CER' or 'PEM'
* @returns {FormatedData}
*/
encode: function encode(object, format) {
return new this(object).encode(format);
},
/**
* Decode source and create object
*
* @memberOf GostASN1.Set
* @static
* @param {FormatedData} source Encoded data
* @returns {GostASN1.Sequence}
*
*/
decode: function decode(source) {
// Decode structure
source = _decode(source, tagNumber, 0, true);
var result = new this(),
data = result.items = {};
for (var i = 0, n = source.length; i < n; i++) {
var item = ItemClass.decode(source[i]);
var id = typeAndValue ? item.object[typeAndValue.typeName] : i;
data[id] = item;
}
result.reset();
return result;
}
});
return Class;
} else {
// Create array class
var ArrayClass = extend(ASN1Object, function (object) {
// Constructor - "matrioshka"
if (this instanceof ArrayClass) {
// Define hidden items property
defineProperties(this, {
items: {
writable: true,
value: []
},
values: {
writable: true,
value: []
}
}); // Call super
ASN1Object.call(this, object || []);
} else return DEFINE.apply(this, arguments);
}, {
object: {
get: function get() {
// refresh items from object properties
this.read();
return this.values;
},
set: function set(object) {
if (object instanceof ArrayClass) {
object.read();
this.items = object.items;
} else {
// Set other object structure
var data = [];
for (var i = 0, n = object.length; i < n; i++) {
data[i] = new ItemClass(object[i]);
}
this.items = data;
} // refresh object properties to items
this.reset();
}
},
encode: function encode(format) {
// refresh items from object properties
this.read(); // repare source
var data = this.items,
source = [];
for (var i = 0, n = data.length; i < n; i++) {
var encoded = data[i].encode(true);
if (encoded !== undefined) source.push(encoded);
}
return _encode(format, source, tagNumber, 0, true);
},
decode: function decode(source) {
this.object = this.constructor.decode(source);
},
check: function check() {
this.constructor.decode(this.encode(true));
},
reset: function reset() {
// remove unused properties
for (var i = 0, n = this.items.length; i < n; i++) {
this.values.push(this.items[i].object);
}
},
read: function read() {
var items = this.items,
values = this.values;
for (var i = 0, n = values.length; i < n; i++) {
if (!this.items[i]) {
items[i] = new ItemClass(values[i]);
values[i] = items[i].object;
} else if (items[i].object !== values[i]) items[i].object = values[i];
}
}
}, {
encode: function encode(object, format) {
return new this(object).encode(format);
},
decode: function decode(source) {
source = _decode(source, tagNumber, 0, true);
var result = new this();
result.items = [];
for (var i = 0, n = source.length; i < n; i++) {
result.items.push(ItemClass.decode(source[i]));
}
result.reset();
return result;
}
});
return ArrayClass;
}
};
return DEFINE(); // Create simple class w/o any parameters
};
};
var SEQUENCE_OF = ARRAY_OF(0x10);
var SET_OF = ARRAY_OF(0x11);
var ENCLOSURE = function ENCLOSURE(BaseClass, modifier) {
if (modifier) {
var Class = extend(ASN1Object, {
object: {
get: function get() {
if (this.item) return modifier.decode(this.item.object);else return undefined;
},
set: function set(object) {
if (object !== undefined) this.item = new BaseClass(modifier.encode(object));else delete this.item;
}
},
encode: function encode(format) {
return this.item.encode(format);
}
}, {
decode: function decode(source) {
var result = new this();
result.item = BaseClass.decode(source);
return result;
}
});
for (var name in BaseClass) {
if (!Class[name]) Class[name] = BaseClass[name];
}
return Class;
} else return BaseClass;
};
var SET_OF_SINGLE = function SET_OF_SINGLE(ItemClass) {
var Class = ENCLOSURE(SET_OF(ItemClass), {
encode: function encode(item) {
return [item];
},
decode: function decode(item) {
return item[0];
}
});
return Class;
};
var CHOICE = function CHOICE(structure, define) {
return extend(ASN1Object, {
object: {
get: function get() {
return this.item && this.item.object;
},
set: function set(object) {
// Try to find appropriate type in structure
if (object instanceof ASN1Object) {
for (var name in structure) {
if (object instanceof structure[name]) {
this.item = object;
return;
}
}
} // Define class
var name = typeof define === 'function' ? define(object) : define;
assert(!name || !structure[name]);
object = new structure[name](object);
this.item = object;
}
},
encode: function encode(format) {
// Already in class
return this.item.encode(format);
}
}, {
decode: function decode(source) {
// Try to find class structure
for (var name in structure) {
try {
var item = structure[name].decode(source);
if (item !== undefined) return new this(item);
} catch (e) {}
}
assert(true);
}
});
};
var ENCAPSULATES = function ENCAPSULATES(WrappedClass) {
WrappedClass = WrappedClass || ANY; // BER Encode/Decode values
return extend(WrappedClass, {
encode: function encode() {
return BER.encode(WrappedClass.method('encode').call(this, true));
}
}, {
encode: function encode(object, format) {
return new this(object).encode(format);
},
decode: function decode(source) {
return WrappedClass.decode.call(this, BER.decode(source));
}
});
};
var DEFAULT = function DEFAULT(Class, optional) {
Class = Class || ANY;
return extend(Class, {
encode: function encode(format) {
if (this.object === optional) return undefined;
return Class.method('encode').call(this, format);
}
}, {
decode: function decode(source) {
if (source === undefined) return new this(optional);else try {
return Class.decode.call(this, source);
} catch (e) {
return undefined;
}
}
});
};
var OPTIONAL = function OPTIONAL(Class) {
Class = Class || ANY;
return extend(Class, {}, {
decode: function decode(source) {
if (source === undefined) return undefined;else try {
return Class.decode.call(this, source);
} catch (e) {
return undefined;
}
}
});
};
var DEFAULT_NULL = function DEFAULT_NULL(Class, optional) {
Class = Class || ANY;
return extend(Class, {
encode: function encode(format) {
if (this.object === optional) return new NULL(null).encode(format);
return Class.method('encode').call(this, format);
}
}, {
decode: function decode(source) {
if (source === undefined) return undefined;else if (source === null || source.tagNumber === 0x05 && source.tagClass === 0) return new this(optional);else try {
return Class.decode.call(this, source);
} catch (e) {
return undefined;
}
}
});
}; // </editor-fold>
/*
* Certificate Version, Name, Attributes, Validity
*
* http://tools.ietf.org/html/rfc5280
*
*/
// <editor-fold defaultstate="collapsed">
var DirectoryString = CHOICE({
teletexString: TeletexString,
printableString: PrintableString,
universalString: UniversalString,
utf8String: UTF8String,
bmpString: BMPString,
numericString: NumericString
}, function (value) {
// PrintableString - for characters and symbols with no spaces, overrise UTF8String
return /^[A-Za-z0-9\.@\+\-\:\=\\\/\?\!\#\$\%\^\&\*\(\)\[\]\{\}\>\<\|\~]*$/.test(value) ? 'printableString' : 'utf8String';
});
var Time = CHOICE({
utcTime: UTCTime,
generalTime: GeneralizedTime
}, function (value) {
return value.getYear() >= 2050 ? 'generalTime' : 'utcTime';
}); // Attribute
var AttributeType = OBJECT_IDENTIFIER;
var AttributeValue = ANY;
var AttributeTypeAndValue = ATTRIBUTE({
type: AttributeType,
value: AttributeValue
});
var typeAndValue = {
typeName: 'type',
valueName: 'value'
};
/**
* X.501 type Name
* The Name describes a hierarchical name composed of attributes, such
* as country name, and corresponding values, such as US. The type of
* the component AttributeValue is determined by the AttributeType; in
* general it will be a DirectoryString.
* The DirectoryString type is defined as a choice of PrintableString,
* TeletexString, BMPString, UTF8String, and UniversalString. The
* UTF8String encoding [RFC 2279] is the preferred encoding, and all
* certificates issued after December 31, 2003 MUST use the UTF8String
* encoding of DirectoryString.
*
* Standard sets of attributes have been defined in the X.500 series of
* specifications [X.520]. Implementations of this specification MUST
* be prepared to receive the following standard attribute types in
* issuer and subject (section 4.1.2.6) names:
* <ul>
* <li>country,</li>
* <li>organization,</li>
* <li>organizational-unit,</li>
* <li>distinguished name qualifier,</li>
* <li>state or province name,</li>
* <li>common name (e.g., "Susan Housley"), and</li>
* <li>serial number.</li>
* </ul>
* In addition, implementations of this specification SHOULD be prepared
* to receive the following standard attribute types in issuer and
* subject names:
* <ul>
* <li>locality,</li>
* <li>title,</li>
* <li>surname,</li>
* <li>given name,</li>
* <li>initials,</li>
* <li>pseudonym, and</li>
* <li>generation qualifier (e.g., "Jr.", "3rd", or "IV").</li>
* </ul>
The syntax for type Name:
* <pre>
* Name ::= CHOICE {
* rdnSequence RDNSequence }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::=
* SET OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY DEFINED BY AttributeType
*
* DirectoryString ::= CHOICE {
* teletexString TeletexString (SIZE (1..MAX)),
* printableString PrintableString (SIZE (1..MAX)),
* universalString UniversalString (SIZE (1..MAX)),
* utf8String UTF8String (SIZE (1..MAX)),
* bmpString BMPString (SIZE (1..MAX)) }
* </pre>
* @class GostASN1.Name
*/
var RelativeDistinguishedName = SET_OF_SINGLE(AttributeTypeAndValue({
serialName: PrintableString,
countryName: PrintableString,
dnQualifier: PrintableString,
emailAddress: IA5String,
domainComponent: IA5String,
SNILS: NumericString,
OGRN: NumericString,
INN: NumericString
}, DirectoryString));
var RDNSequence = SEQUENCE_OF(RelativeDistinguishedName, typeAndValue)();
var Name = CHOICE({
// only one possibility for now
rdnSequence: RDNSequence
}, 'rdnSequence');
/**
* Validity
* @class GostASN1.Validity
* @extends GostASN1.Sequence
*/
var Validity = COMBINE(SEQUENCE({
notBefore: Time,
notAfter: Time
}));
var Version = INTEGER;
var Attribute = ATTRIBUTE({
type: OBJECT_IDENTIFIER,
value: ANY
});
/**
* Type and Value Attributes <br>
*
* Suggested naming attributes: Definition of the following
* information object set may be augmented to meet local
* requirements. Note that deleting members of the set may
* prevent interoperability with conforming implementations.
* presented in pairs: the AttributeType followed by the type
* definition for the corresponding AttributeValue
*
* @class GostASN1.Attributes
* @extends GostASN1.Set
*/
var Attributes = SET_OF(Attribute, typeAndValue);
var AttributeSequence = SEQUENCE_OF(Attribute, typeAndValue); // </editor-fold>
/*
* Algorithm identifiers
*
* http://tools.ietf.org/html/rfc3279
* http://tools.ietf.org/html/rfc4357
* http://tools.ietf.org/html/rfc2898
*
*/
// <editor-fold defaultstate="collapsed">
var FieldElement = INTEGER;
var Curve = SEQUENCE({
a: FieldElement,
b: FieldElement,
seed: OPTIONAL(BIT_STRING)
});
var ECPoint = OCTET_STRING(extend(ASN1Object, {
encode: function encode() {
var value = this.object;
var len = Math.max(npw2(value.x.length - 2), npw2(value.y.length - 2)) / 2,
r = new Uint8Array(2 * len + 1);
r[0] = 0x04;
r.set(new Uint8Array(SInt.decode(value.x, false, len)), 1); // x
r.set(new Uint8Array(SInt.decode(value.y, false, len)), len + 1); // y
return r.buffer;
}
}, {
decode: function decode(value) {
var len = (value.byteLength - 1) / 2;
return new this({
x: SInt.encode(new Uint8Array(value, 1, len)),
y: SInt.encode(new Uint8Array(value, len + 1, len))
});
}
}));
var FieldID = SEQUENCE({
fieldType: OBJECT_IDENTIFIER,
parameters: INTEGER
});
var ECParameters = SEQUENCE({
version: Version,
// version is always 1
fieldID: FieldID,
// identifies the finite field over which the curve is defined
curve: Curve,
// coefficients a and b of the elliptic curve
base: ECPoint,
// specifies the base point P on the elliptic curve
order: INTEGER,
// the order n of the base point
cofactor: OPTIONAL(INTEGER)
}); // The integer h = #E(Fq)/n
var GostR3410Parameters = SEQUENCE({
publicKeyParamSet: OBJECT_IDENTIFIER,
digestParamSet: OBJECT_IDENTIFIER,
encryptionParamSet: OPTIONAL(OBJECT_IDENTIFIER)
});
var GostR3411Parameters = DEFAULT_NULL(OBJECT_IDENTIFIER, 'id-GostR3411-94-CryptoProParamSet');
var ECDHParameters = CHOICE({
namedParameters: OBJECT_IDENTIFIER,
ecParameters: ECParameters,
implicitly: OPTIONAL(NULL)
}, function (value) {
return typeof value === 'string' || value instanceof String ? 'namedParameters' : 'ecParameters';
});
var Algorithm = function Algorithm(paramType, modifier) {
return ENCLOSURE(SEQUENCE({
algorithm: OBJECT_IDENTIFIER,
parameters: OPTIONAL(paramType)
}), modifier);
};
var AlgorithmIdentifier = function () {
var DefaultAlgorithm = Algorithm(ANY),
Class = extend(ASN1Object, function (object) {
if (this instanceof Class) Class["super"].apply(this, arguments);else return DEFINE(object);
}, {
encode: function encode(format) {
return new DefaultAlgorithm(this.object).encode(format);
}
}, {
decode: function decode(source) {
return new this(DefaultAlgorithm.decode(source).object);
}
});
var DEFINE = function DEFINE(algorithmSet) {
return extend(ASN1Object, {
object: {
get: function get() {
if (this.item) return this.item.object;else return undefined;
},
set: function set(object) {
if (object) {
var ItemClass = algorithmSet[object.id];
if (!ItemClass) throw new Error('Algorithm not supported');
this.item = new ItemClass(object);
} else delete this.item;
}
},
encode: function encode(format) {
return this.item.encode(format);
}
}, {
decode: function decode(source) {
// Decode PEM
if (typeof source === 'string') source = PEM.decode(source, undefined, false); // Decode binary data
if (source instanceof CryptoOperationData) source = BER.decode(source);
var ItemClass = algorithmSet[names[source.object[0].object]];
if (ItemClass) {
var result = new this();
result.item = ItemClass.decode(source);
return result;
} else throw new Error('Algorithm not supported');
}
});
};
return Class;
}();
var ECDHKeyAlgorithm = Algorithm(ECDHParameters, {
encode: function encode(value) {
var params;
if (typeof value.namedCurve === 'string') params = attributes['namedCurve'][value.namedCurve];else params = {
version: 1,
fieldID: {
fieldType: 'id-prime-Field',
parameters: value.curve.p
},
curve: {
a: value.curve.a,
b: value.curve.b
},
base: {
x: value.curve.x,
y: value.curve.y
},
order: value.curve.q,
cofactor: 1
};
return {
algorithm: value.id,
parameters: params
};
},
decode: function decode(value) {
var params = value.parameters,
result = algorithms[value.algorithm];
if (typeof params === 'string' || params instanceof String) {
result = expand(result, parameters[params]);
} else if (_typeof(params) === 'object') {
result = expand(result, {
curve: {
p: params.fieldID.parameters,
a: params.curve.a,
b: params.curve.b,
x: params.base.x,
y: params.base.y,
q: params.order
}
});
} else throw new DataError('Invalid key paramters');
return result;
}
});
var GostKeyAlgorithm = Algorithm(GostR3410Parameters, {
encode: function encode(value) {
var paramName = value.namedCurve ? 'namedCurve' : 'namedParam',
sBox = value.name.indexOf('-94') >= 0 || value.name.indexOf('-2001') >= 0 || value.version === 1994 || value.version === 2001 ? value.sBox || 'D-A' : value.name.indexOf('-512') >= 0 || value.length === 512 ? 'D-512' : 'D-256';
return {
algorithm: value.id,
parameters: {
publicKeyParamSet: attributes[paramName][value[paramName]],
digestParamSet: attributes['sBox'][sBox],
encryptionParamSet: value.encParams && value.encParams.sBox ? attributes['sBox'][value.encParams.sBox] : undefined
}
};
},
decode: function decode(value) {
var params = value.parameters,
algorithm = expand(algorithms[value.algorithm], parameters[params.publicKeyParamSet], parameters[params.digestParamSet]);
if (params.encryptionParamSet) algorithm.encParams = parameters[params.encryptionParamSet];
return algorithm;
}
});
var AlgorithmWithNoParam = Algorithm(ANY, {
encode: function encode(value) {
return {
algorithm: value.id
};
},
decode: function decode(value) {
return algorithms[value.algorithm];
}
});
var AlgorithmWithNullParam = Algorithm(NULL, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: null
};
},
decode: function decode(value) {
return algorithms[value.algorithm];
}
});
var Gost341194DigestAlgorithm = Algorithm(GostR3411Parameters, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: attributes['sBox'][value.sBox || value.hash && value.hash.sBox || 'D-A']
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm]),
parameter = parameters[value.parameters];
if (algorithm.hash) algorithm.hash = expand(algorithm.hash, parameter);else algorithm = expand(algorithm, parameter);
return algorithm;
}
});
var KeyAlgorithmIdentifier = AlgorithmIdentifier({
ecdsa: ECDHKeyAlgorithm,
noSignature: AlgorithmWithNullParam,
rsaEncryption: AlgorithmWithNullParam,
'id-sc-gostR3410-2001': ECDHKeyAlgorithm,
'id-GostR3410-2001': GostKeyAlgorithm,
'id-GostR3410-94': GostKeyAlgorithm,
'id-GostR3410-2001DH': GostKeyAlgorithm,
'id-GostR3410-94DH': GostKeyAlgorithm,
'id-tc26-gost3410-12-256': GostKeyAlgorithm,
'id-tc26-gost3410-12-512': GostKeyAlgorithm,
'id-tc26-agreement-gost-3410-12-256': GostKeyAlgorithm,
'id-tc26-agreement-gost-3410-12-512': GostKeyAlgorithm,
'id-sc-gost28147-gfb': AlgorithmWithNoParam,
'id-Gost28147-89': AlgorithmWithNoParam
});
var SignatureAlgorithmIdentifier = AlgorithmIdentifier({
noSignature: AlgorithmWithNullParam,
rsaEncryption: AlgorithmWithNullParam,
sha1withRSAEncryption: AlgorithmWithNullParam,
sha256withRSAEncryption: AlgorithmWithNullParam,
sha384withRSAEncryption: AlgorithmWithNullParam,
sha512withRSAEncryption: AlgorithmWithNullParam,
'ecdsa': AlgorithmWithNoParam,
'ecdsa-with-SHA1': AlgorithmWithNoParam,
'ecdsa-with-SHA256': AlgorithmWithNoParam,
'ecdsa-with-SHA384': AlgorithmWithNoParam,
'ecdsa-with-SHA512': AlgorithmWithNoParam,
'id-GostR3410-94': AlgorithmWithNullParam,
'id-GostR3410-2001': AlgorithmWithNullParam,
'id-GostR3411-94-with-GostR3410-2001': AlgorithmWithNoParam,
'id-GostR3411-94-with-GostR3410-94': AlgorithmWithNoParam,
'id-tc26-gost3410-12-256': AlgorithmWithNullParam,
'id-tc26-gost3410-12-512': AlgorithmWithNullParam,
'id-tc26-signwithdigest-gost3410-12-94': AlgorithmWithNoParam,
'id-tc26-signwithdigest-gost3410-12-256': AlgorithmWithNoParam,
'id-tc26-signwithdigest-gost3410-12-512': AlgorithmWithNoParam,
'id-sc-gostR3410-94': AlgorithmWithNullParam,
'id-sc-gostR3410-2001': AlgorithmWithNullParam,
'id-sc-gostR3411-94-with-gostR3410-94': AlgorithmWithNullParam,
'id-sc-gostR3411-94-with-gostR3410-2001': AlgorithmWithNullParam
});
var DigestAlgorithmIdentifier = AlgorithmIdentifier({
sha1: AlgorithmWithNoParam,
sha256: AlgorithmWithNullParam,
sha384: AlgorithmWithNullParam,
sha512: AlgorithmWithNullParam,
'id-GostR3411-94': Gost341194DigestAlgorithm,
'id-tc26-gost3411-94': Gost341194DigestAlgorithm,
'id-tc26-gost3411-12-256': AlgorithmWithNullParam,
'id-tc26-gost3411-12-512': AlgorithmWithNullParam,
'id-sc-gostR3411-94': AlgorithmWithNoParam
});
var Gost2814789Key = OCTET_STRING; //(SIZE (32))
var Gost2814789MAC = OCTET_STRING; // (SIZE (1..4))
var Gost2814789ParamSet = OBJECT_IDENTIFIER;
var Gost2814789IV = OCTET_STRING; // (SIZE (8))
var Gost2814789Parameters = SEQUENCE({
iv: Gost2814789IV,
encryptionParamSet: Gost2814789ParamSet
});
var Gost2814789KeyWrapParameters = SEQUENCE({
encryptionParamSet: Gost2814789ParamSet,
ukm: OPTIONAL(OCTET_STRING)
}); // (SIZE (8)) must be absent in key agreement
var Gost2814789Algorithm = Algorithm(Gost2814789Parameters, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: {
iv: value.iv,
encryptionParamSet: attributes['sBox'][value.sBox || 'E-A']
}
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm], parameters[value.parameters.encryptionParamSet]);
algorithm.iv = value.parameters.iv;
return algorithm;
}
});
var SCGostAlgorithm = Algorithm(Gost2814789IV, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: value.iv
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm]);
algorithm.iv = value.parameters || new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]);
return algorithm;
}
});
var GostKeyWrapAlgorithm = Algorithm(Gost2814789KeyWrapParameters, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: {
encryptionParamSet: attributes['sBox'][value.sBox || 'E-A'],
ukm: value.ukm
}
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm], parameters[value.parameters.encryptionParamSet]);
if (value.parameters.ukm) algorithm.ukm = value.parameters.ukm;
return algorithm;
}
});
var KeyWrapAlgorithmIdentifier = AlgorithmIdentifier({
'id-Gost28147-89-None-KeyWrap': GostKeyWrapAlgorithm,
'id-Gost28147-89-CryptoPro-KeyWrap': GostKeyWrapAlgorithm
});
var GostKeyAgreementAlgorithm = Algorithm(KeyWrapAlgorithmIdentifier, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: value.wrapping
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm]);
algorithm.wrapping = value.parameters;
return algorithm;
}
});
var BaseEncryptionAlgorithmIdentifier = AlgorithmIdentifier({
'id-sc-gost28147-gfb': SCGostAlgorithm,
'id-Gost28147-89': Gost2814789Algorithm
});
var MessageAuthenticationCodeAlgorithm = AlgorithmIdentifier({
'id-Gost28147-89-MAC': Gost2814789Parameters,
'id-HMACGostR3411-94': Gost341194DigestAlgorithm,
'id-tc26-hmac-gost-3411-12-256': Gost341194DigestAlgorithm,
'id-tc26-hmac-gost-3411-12-512': Gost341194DigestAlgorithm,
'hmacWithSHA1': AlgorithmWithNoParam,
'hmacWithSHA224': AlgorithmWithNoParam,
'hmacWithSHA256': AlgorithmWithNoParam,
'hmacWithSHA384': AlgorithmWithNoParam,
'hmacWithSHA512': AlgorithmWithNoParam,
'id-sc-gost28147-mac': AlgorithmWithNoParam,
'id-sc-hmacWithGostR3411': AlgorithmWithNoParam
}); // rfc2898 PKCS #5: Password-Based Cryptography Specification
// PBKDF2
var PBKDF2params = SEQUENCE({
salt: CHOICE({
specified: OCTET_STRING,
otherSource: AlgorithmIdentifier
}, function (value) {
return isBinary(value) ? 'specified' : 'otherSource';
}),
iterationCount: INTEGER,
keyLength: OPTIONAL(INTEGER),
prf: MessageAuthenticationCodeAlgorithm
});
var PBKDF2Algorithm = Algorithm(PBKDF2params, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: {
salt: value.salt,
iterationCount: value.iterations,
prf: value.hmac
}
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm]);
algorithm.salt = value.parameters.salt;
algorithm.iterations = value.parameters.iterationCount;
algorithm.hmac = value.parameters.prf;
algorithm.hash = algorithm.hmac.hash;
return algorithm;
}
});
var KeyDerivationAlgorithmIdentifier = AlgorithmIdentifier({
'PBKDF2': PBKDF2Algorithm
});
var PBEParameter = SEQUENCE({
salt: OCTET_STRING,
iterationCount: INTEGER
});
var PBES1Algorithm = Algorithm(PBEParameter, {
paramType: PBEParameter,
encode: function encode(value) {
return {
algorithm: value.id,
parameters: {
salt: value.derivation.salt,
iterationCount: value.derivation.iterations
}
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm]);
algorithm.derivation = expand(algorithm.derivation, {
salt: value.parameters.salt,
iterations: value.parameters.iterationCount
});
return algorithm;
}
}); // PBES2
var PBES2params = SEQUENCE({
keyDerivationFunc: KeyDerivationAlgorithmIdentifier,
// {{PBES2-KDFs}},
encryptionScheme: BaseEncryptionAlgorithmIdentifier
}); // {{PBES2-Encs}}
var PBES2Algorithm = Algorithm(PBES2params, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: {
keyDerivationFunc: value.derivation,
encryptionScheme: value.encryption
}
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm]);
algorithm.derivation = value.parameters.keyDerivationFunc;
algorithm.encryption = value.parameters.encryptionScheme;
return algorithm;
}
});
var PasswordEncryptionAlgorithmIndentifier = AlgorithmIdentifier({
// PBES1
'pbeWithSHAAndAES128-CBC': PBES1Algorithm,
'pbeWithSHAAndAES192-CBC': PBES1Algorithm,
'pbeWithSHAAndAES256-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES128-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES192-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES256-CBC': PBES1Algorithm,
'id-sc-pbeWithGost3411AndGost28147': PBES1Algorithm,
'id-sc-pbeWithGost3411AndGost28147CFB': PBES1Algorithm,
// PKCS12 PBES1
'pbeWithSHAAnd3-KeyTripleDES-CBC': PBES1Algorithm,
'pbeWithSHAAnd2-KeyTripleDES-CBC': PBES1Algorithm,
'pbeWithSHAAnd128BitRC2-CBC': PBES1Algorithm,
'pbeWithSHAAnd40BitRC2-CBC': PBES1Algorithm,
'pbeUnknownGost': PBES1Algorithm,
// PBES2
'PBES2': PBES2Algorithm
});
var KeyEncryptionAlgorithmIdentifier = AlgorithmIdentifier({
ecdsa: ECDHKeyAlgorithm,
rsaEncryption: AlgorithmWithNullParam,
// Base encryption
'id-sc-gost28147-gfb': SCGostAlgorithm,
'id-Gost28147-89': Gost2814789Algorithm,
// Key transport algorithms
'id-sc-gostR3410-2001': ECDHKeyAlgorithm,
'id-GostR3410-2001': GostKeyAlgorithm,
'id-GostR3410-94': GostKeyAlgorithm,
'id-tc26-gost3410-12-256': GostKeyAlgorithm,
'id-tc26-gost3410-12-512': GostKeyAlgorithm,
// Key agreement algorithms
'id-GostR3410-94-CryptoPro-ESDH': GostKeyAgreementAlgorithm,
'id-GostR3410-2001-CryptoPro-ESDH': GostKeyAgreementAlgorithm,
'id-tc26-agreement-gost-3410-12-256': GostKeyAgreementAlgorithm,
'id-tc26-agreement-gost-3410-12-512': GostKeyAgreementAlgorithm,
'id-sc-r3410-ESDH-r3411kdf': AlgorithmWithNullParam,
// Key encryption key algorithms
'id-Gost28147-89-None-KeyWrap': GostKeyWrapAlgorithm,
// Add ukm to algorithm
'id-Gost28147-89-CryptoPro-KeyWrap': GostKeyWrapAlgorithm,
'id-sc-cmsGostWrap': AlgorithmWithNoParam,
// SC don't use ukm
'id-sc-cmsGost28147Wrap': AlgorithmWithNoParam,
// Password based encryption
'pbeWithSHAAndAES128-CBC': PBES1Algorithm,
'pbeWithSHAAndAES192-CBC': PBES1Algorithm,
'pbeWithSHAAndAES256-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES128-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES192-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES256-CBC': PBES1Algorithm,
'id-sc-pbeWithGost3411AndGost28147': PBES1Algorithm,
'id-sc-pbeWithGost3411AndGost28147CFB': PBES1Algorithm,
// PKCS12 PBES1
'pbeWithSHAAnd3-KeyTripleDES-CBC': PBES1Algorithm,
'pbeWithSHAAnd2-KeyTripleDES-CBC': PBES1Algorithm,
'pbeWithSHAAnd128BitRC2-CBC': PBES1Algorithm,
'pbeWithSHAAnd40BitRC2-CBC': PBES1Algorithm,
'pbeUnknownGost': PBES1Algorithm,
// PBES2
'PBES2': PBES2Algorithm
});
var PBMAC1params = SEQUENCE({
keyDerivationFunc: KeyDerivationAlgorithmIdentifier,
// {{PBMAC1-KDFs}},
messageAuthScheme: MessageAuthenticationCodeAlgorithm
}); // {{PBMAC1-MACs}}
var PasswordMACAlgorithm = Algorithm(PBMAC1params, {
encode: function encode(value) {
return {
algorithm: value.id,
parameters: {
keyDerivationFunc: value.derivation,
messageAuthScheme: value.hmac
}
};
},
decode: function decode(value) {
var algorithm = expand(algorithms[value.algorithm]);
algorithm.derivation = value.parameters.keyDerivationFunc;
algorithm.hmac = value.parameters.messageAuthScheme;
return algorithm;
}
});
var PasswordMACAlgorithmIdentifier = AlgorithmIdentifier({
'PBMAC1': PasswordMACAlgorithm
});
var ContentEncryptionAlgorithmIdentifier = AlgorithmIdentifier({
// Base encryption
'id-sc-gost28147-gfb': SCGostAlgorithm,
'id-Gost28147-89': Gost2814789Algorithm,
// Password based encryption
'pbeWithSHAAndAES128-CBC': PBES1Algorithm,
'pbeWithSHAAndAES192-CBC': PBES1Algorithm,
'pbeWithSHAAndAES256-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES128-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES192-CBC': PBES1Algorithm,
'pbeWithSHA256AndAES256-CBC': PBES1Algorithm,
'id-sc-pbeWithGost3411AndGost28147': PBES1Algorithm,
'id-sc-pbeWithGost3411AndGost28147CFB': PBES1Algorithm,
// PKCS12 PBES1
'pbeWithSHAAnd3-KeyTripleDES-CBC': PBES1Algorithm,
'pbeWithSHAAnd2-KeyTripleDES-CBC': PBES1Algorithm,
'pbeWithSHAAnd128BitRC2-CBC': PBES1Algorithm,
'pbeWithSHAAnd40BitRC2-CBC': PBES1Algorithm,
'pbeUnknownGost': PBES1Algorithm,
// PBES2
'PBES2': PBES2Algorithm
}); // </editor-fold>
/*
* Public Key Info
*
* http://tools.ietf.org/html/rfc5280
*
*/
// <editor-fold defaultstate="collapsed">
var KeyData = ENCLOSURE;
var DHPublicKey = KeyData(BIT_STRING(ENCAPSULATES(INTEGER)), {
encode: function encode(value) {
return Int16.encode(swapBytes(value));
},
decode: function decode(value) {
return swapBytes(Int16.decode(value));
}
});
var ECDHPublicKey = KeyData(BIT_STRING(ENCAPSULATES(OCTET_STRING)), {
encode: function encode(value) {
var r = new Uint8Array(value.byteLength + 1),
d = swapBytes(value),
len = value.byteLength / 2;
r[0] = 0x04; // type hex;
r.set(new Uint8Array(d, len, len), 1); // x
r.set(new Uint8Array(d, 0, len), len + 1); // y
return r.buffer;
},
decode: function decode(value) {
assert((value.byteLength & 1) === 0);
var d = new Uint8Array(value.byteLength - 1),
len = d.byteLength / 2;
d.set(new Uint8Array(value, len + 1, len), 0); // y
d.set(new Uint8Array(value, 1, len), len); // x
return swapBytes(d);
}
});
var GostR3410PublicKey = BIT_STRING(ENCAPSULATES(OCTET_STRING));
/**
* Subject Public Key Info Syntax X.509
* <pre>
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
-- contains a value of the type
-- registered for use with the
-- algorithm object identifier value
* </pre>
* RFC 5280 references {@link http://tools.ietf.org/html/rfc5280}
* @class GostASN1.SubjectPublicKeyInfo
* @extends GostASN1.Sequence
* @property {AlgorithmIdentifier} algorithm Identifies the public-key algorithm.
* @property {CryptoOperationData} subjectPublicKey An binary data whose contents are the value of the public key
*/
var SubjectPublicKeyInfo = SEQUENCE({
algorithm: KeyAlgorithmIdentifier,
subjectPublicKey: BIT_STRING
}, 'PUBLIC KEY');
var GostSubjectPublicKeyInfo = function (PKTypes) {
/**
* Coding methods for {@link Algorithm} and {@link GostASN1.SubjectPublicKeyInfo}
* Supported types for GOST algorithms:
* <pre>
* {
* 'id-sc-gostR3410-2001': ECDHPublicKey,
* 'id-sc-gostR3410-94': DHPublicKey,
* 'id-GostR3410-2001': GostR3410PublicKey,
* 'id-GostR3410-94': GostR3410PublicKey,
* 'id-tc26-gost3410-12-256': GostR3410PublicKey,
* 'id-tc26-gost3410-12-512': GostR3410PublicKey
* }
* </pre>
*
* @class GostASN1.GostSubjectPublicKeyInfo
* @extends GostASN1.SubjectPublicKeyInfo
* @extends Key
*/
return ENCLOSURE(ATTRIBUTE({
algorithm: KeyAlgorithmIdentifier,
subjectPublicKey: ANY
}, 'algorithm', 'subjectPublicKey')(function (algorithm) {
return PKTypes[algorithm.id];
}), {
encode: function encode(value) {
return {
algorithm: value.algorithm,
subjectPublicKey: value.buffer
};
},
decode: function decode(value) {
return {
algorithm: value.algorithm,
type: 'public',
extractable: true,
usages: ['verify', 'deriveKey', 'deriveBits'],
buffer: value.subjectPublicKey
};
}
});
}({
'id-sc-gostR3410-2001': ECDHPublicKey,
'id-sc-gostR3410-94': DHPublicKey,
'id-GostR3410-2001': GostR3410PublicKey,
'id-GostR3410-94': GostR3410PublicKey,
'id-tc26-gost3410-12-256': GostR3410PublicKey,
'id-tc26-gost3410-12-512': GostR3410PublicKey
}); // </editor-fold>
/*
* Private Key Info PKCS#8
*
* http://tools.ietf.org/html/rfc5208
*
*/
// <editor-fold defaultstate="collapsed">
var PrivateKey = OCTET_STRING;
var DHPrivateKey = KeyData(PrivateKey(ENCAPSULATES(INTEGER)), {
encode: function encode(value) {
// for SignalCom INTEGER d
return SInt.encode(value, true);
},
decode: function decode(value) {
return SInt.decode(value, true);
}
});
var GostR3410KeyValueMask = OCTET_STRING;
var GostR3410KeyValueInfo = SEQUENCE({
keyValueMask: GostR3410KeyValueMask,
keyValyePublicKey: OCTET_STRING
});
var GostR3410PrivateKey = CHOICE({
privateKey: PrivateKey(ENCAPSULATES(CHOICE({
keyValueMask: GostR3410KeyValueMask,
keyValueInfo: GostR3410KeyValueInfo
}, function (value) {
if (isBinary(value)) return 'keyValueMask';else return 'keyValueInfo';
}))),
keyValueMask: GostR3410KeyValueMask
}, function (value) {
return value.enclosed ? 'keyValueMask' : 'privateKey';
});
var GostWrappedPrivateKey = function (PKTypes) {
/**
* Gost Wrapped Private Key for SignalCom key container
*
* @class GostASN1.GostWrappedPrivateKey
* @extends GostASN1.PrivateKeyInfo
*/
return ATTRIBUTE({
version: Version,
privateKeyAlgorithm: KeyAlgorithmIdentifier,
privateKeyWrapped: KeyData(PrivateKey(ENCAPSULATES(SEQUENCE({
keyData: INTEGER,
keyMac: INTEGER
}))), {
encode: function encode(value) {
var size = value.byteLength - 4;
return {
keyData: SInt.encode(new Uint8Array(value, 0, size)),
keyMac: SInt.encode(new Uint8Array(value, size, 4))
};
},
decode: function decode(value) {
var data = SInt.decode(value.keyData),
mac = SInt.decode(value.keyMac),
result = new Uint8Array(data.byteLength + mac.byteLength);
result.set(new Uint8Array(data));
result.set(new Uint8Array(mac), data.byteLength);
return result;
}
}),
attributes: ANY
}, 'privateKeyAlgorithm', 'attributes')(function (algorithm) {
return OPTIONAL(CTX(0, IMPLICIT(Attributes({
'id-sc-gostR3410-2001-publicKey': SET_OF_SINGLE(PKTypes[algorithm.id])
}))));
});
}({
// Signature keys
'id-sc-gostR3410-2001': ECDHPublicKey,
'id-sc-gostR3410-94': DHPublicKey,
'id-GostR3410-2001': GostR3410PublicKey,
'id-GostR3410-94': GostR3410PublicKey,
'id-GostR3410-2001DH': GostR3410PublicKey,
'id-GostR3410-94DH': GostR3410PublicKey,
'id-tc26-gost3410-12-256': GostR3410PublicKey,
'id-tc26-gost3410-12-512': GostR3410PublicKey,
'id-tc26-agreement-gost-3410-12-256': GostR3410PublicKey,
'id-tc26-agreement-gost-3410-12-512': GostR3410PublicKey
});
/**
* Private-Key Information Syntax PKSC#8
* <pre>
* -- Private-key information syntax
*
* PrivateKeyInfo ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
* privateKey PrivateKey,
* attributes [0] Attributes OPTIONAL }
*
* Version ::= INTEGER {v1(0)} (v1,...)
*
* PrivateKey ::= OCTET STRING
*
* Attributes ::= SET OF Attribute
* </pre>
* RFC 5208 references {@link http://tools.ietf.org/html/rfc5208}
* @class GostASN1.PrivateKeyInfo
* @extends GostASN1.Sequence
* @property {number} version The syntax version number. Should be 0
* @property {AlgorithmIndentifier} privateKeyAlgorithm Identifies the private-key algorithm
* @property {CryptoOperationData} privateKey Is an binary data whose contents are the value of the private key.
* @property {GostASN1.Attributes} attributes A set of attributes
*/
var PrivateKeyInfo = SEQUENCE({
version: Version,
privateKeyAlgorithm: KeyAlgorithmIdentifier,
privateKey: PrivateKey,
attributes: OPTIONAL(CTX(0, IMPLICIT(Attributes)))
}, 'PRIVATE KEY');
var PrivateKeyAlgorithmIdentifier = KeyAlgorithmIdentifier;
var PublicKey = BIT_STRING;
var OneAsymmetricKey = SEQUENCE({
version: Version,
privateKeyAlgorithm: PrivateKeyAlgorithmIdentifier,
privateKey: PrivateKey,
attributes: OPTIONAL(CTX(0, IMPLICIT(Attributes))),
publicKey: OPTIONAL(CTX(1, IMPLICIT(PublicKey)))
});
var AsymmetricKeyPackage = SEQUENCE_OF(OneAsymmetricKey);
var GostPrivateKeyInfo = function (PKTypes) {
/**
* Coding methods for {@link Algorithm} and {@link GostASN1.PrivateKeyInfo}
* Supported types for GOST algorithms:
* <pre>
* {
* 'id-sc-gostR3410-2001': DHPrivateKey,
* 'id-sc-gostR3410-94': DHPrivateKey,
* 'id-GostR3410-2001': GostR3410PrivateKey,
* 'id-GostR3410-94': GostR3410PrivateKey,
* 'id-tc26-gost3410-12-256': GostR3410PrivateKey,
* 'id-tc26-gost3410-12-512': GostR3410PrivateKey
* }
* </pre>
*
* @class GostASN1.GostPrivateKeyInfo
* @extends GostASN1.PrivateKeyInfo
* @extends Key
*/
return ENCLOSURE(ATTRIBUTE({
version: Version,
privateKeyAlgorithm: KeyAlgorithmIdentifier,
privateKey: ANY,
attributes: OPTIONAL(CTX(0, IMPLICIT(Attributes)))
}, 'privateKeyAlgorithm', 'privateKey')(function (algorithm) {
return PKTypes[algorithm.id];
}), {
encode: function encode(value) {
return {
version: 0,
privateKeyAlgorithm: value.algorithm,
privateKey: value.buffer
};
},
decode: function decode(value) {
return {
algorithm: value.privateKeyAlgorithm,
type: 'private',
extractable: true,
usages: ['sign', 'deriveKey', 'deriveBits'],
buffer: isBinary(value.privateKey) ? value.privateKey : value.privateKey.keyValueMask
};
}
});
}({
// Signature keys
'id-sc-gostR3410-2001': DHPrivateKey,
'id-sc-gostR3410-94': DHPrivateKey,
'id-GostR3410-2001': GostR3410PrivateKey,
'id-GostR3410-94': GostR3410PrivateKey,
'id-GostR3410-2001DH': GostR3410PrivateKey,
'id-GostR3410-94DH': GostR3410PrivateKey,
'id-tc26-gost3410-12-256': GostR3410PrivateKey,
'id-tc26-gost3410-12-512': GostR3410PrivateKey,
'id-tc26-agreement-gost-3410-12-256': GostR3410PrivateKey,
'id-tc26-agreement-gost-3410-12-512': GostR3410PrivateKey
});
var KeyEncryptedData = OCTET_STRING;
/**
* Encrypted Private-Key Information Syntax
* <pre>
* -- Encrypted private-key information syntax
*
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm AlgorithmIdentifier {{KeyEncryptionAlgorithms}},
* encryptedData KeyEncryptedData
* }
*
* KeyEncryptedData ::= OCTET STRING
*
* PrivateKeyAlgorithms ALGORITHM-IDENTIFIER ::= {
* ... -- For local profiles
* }
*
* KeyEncryptionAlgorithms ALGORITHM-IDENTIFIER ::= {
* ... -- For local profiles
* }
* </pre>
* RFC 5208 references {@link http://tools.ietf.org/html/rfc5208}
* @class GostASN1.EncryptedPrivateKeyInfo
* @extends GostASN1.Sequence
* @property {AlgorithmIdentifier} encryptionAlgorithm Identifies key encryption algorithm
* @property {CryptoOperationData} encryptedData Encrypted {@link GostASN1.PrivateKeyInfo}
*/
var EncryptedPrivateKeyInfo = SEQUENCE({
encryptionAlgorithm: KeyEncryptionAlgorithmIdentifier,
encryptedData: KeyEncryptedData
}, 'ENCRYPTED PRIVATE KEY'); // </editor-fold>
/*
* Certificate Extensions
*
* http://tools.ietf.org/html/rfc5280
*
*/
// <editor-fold defaultstate="collapsed">
var UniqueIdentifier = BIT_STRING;
var CertificateSerialNumber = INTEGER;
var BasicConstraints = SEQUENCE({
cA: DEFAULT(BOOLEAN, false),
pathLenConstraint: OPTIONAL(INTEGER)
});
var KeyUsage = BIT_STRING({
digitalSignature: 0,
nonRepudiation: 1,
keyEncipherment: 2,
dataEncipherment: 3,
keyAgreement: 4,
keyCertSign: 5,
cRLSign: 6,
encipherOnly: 7,
decipherOnly: 8
});
var KeyPurposeId = OBJECT_IDENTIFIER,
ExtKeyUsageSyntax = SEQUENCE_OF(KeyPurposeId);
var KeyIdentifier = OCTET_STRING;
var OtherName = SEQUENCE({
type: OBJECT_IDENTIFIER,
value: CTX(0, EXPLICIT(ANY))
});
var EDIPartyName = SEQUENCE({
nameAssigner: OPTIONAL(CTX(0, IMPLICIT(DirectoryString))),
partyName: OPTIONAL(CTX(1, IMPLICIT(DirectoryString)))
});
var ORAddress = SEQUENCE({});
var GeneralName = CHOICE({
otherName: CTX(0, IMPLICIT(OtherName)),
rfc822Name: CTX(1, IMPLICIT(DirectoryString)),
dNSName: CTX(2, IMPLICIT(DirectoryString)),
x400Address: CTX(3, IMPLICIT(ORAddress)),
directoryName: CTX(4, EXPLICIT(Name)),
// Name is CHOICE(RDNSequence)
ediPartyName: CTX(5, IMPLICIT(EDIPartyName)),
uniformResourceIdentifier: CTX(6, IMPLICIT(DirectoryString)),
iPAddress: CTX(7, IMPLICIT(OCTET_STRING)),
registeredID: CTX(8, IMPLICIT(OBJECT_IDENTIFIER))
}, function (value) {
return typeof value === 'string' || value instanceof String ? value.indexOf('@') >= 0 ? 'rfc822Name' : 'dNSName' : isBinary(value) ? 'iPAddress' : 'directoryName';
});
var GeneralNames = SEQUENCE_OF(GeneralName);
var AuthorityKeyIdentifier = SEQUENCE({
keyIdentifier: OPTIONAL(CTX(0, IMPLICIT(KeyIdentifier))),
authorityCertIssuer: OPTIONAL(CTX(1, IMPLICIT(GeneralNames))),
authorityCertSerialNumber: OPTIONAL(CTX(2, IMPLICIT(CertificateSerialNumber)))
});
var PrivateKeyUsagePeriod = SEQUENCE({
notBefore: OPTIONAL(CTX(0, IMPLICIT(GeneralizedTime))),
notAfter: OPTIONAL(CTX(1, IMPLICIT(GeneralizedTime)))
});
var CertPolicyId = OBJECT_IDENTIFIER,
PolicyQualifierId = OBJECT_IDENTIFIER;
var PolicyQualifierInfo = SEQUENCE({
policyQualifierId: PolicyQualifierId,
qualifier: ANY
});
var PolicyInformation = SEQUENCE({
policyIdentifier: CertPolicyId,
policyQualifiers: OPTIONAL(SEQUENCE_OF(PolicyQualifierInfo))
});
var PolicyMapping = SEQUENCE({
issuerDomainPolicy: CertPolicyId,
subjectDomainPolicy: CertPolicyId
});
var BaseDistance = INTEGER;
var GeneralSubtree = SEQUENCE({
base: GeneralName,
minimum: DEFAULT(CTX(0, IMPLICIT(BaseDistance)), 0),
maximum: OPTIONAL(CTX(1, IMPLICIT(BaseDistance)))
});
var GeneralSubtrees = SEQUENCE_OF(GeneralSubtree);
var NameConstraints = SEQUENCE({
permittedSubtrees: OPTIONAL(CTX(0, IMPLICIT(GeneralSubtrees))),
excludedSubtrees: OPTIONAL(CTX(1, IMPLICIT(GeneralSubtrees)))
});
var SkipCerts = INTEGER;
var PolicyConstraints = SEQUENCE({
requireExplicitPolicy: OPTIONAL(CTX(0, IMPLICIT(SkipCerts))),
inhibitPolicyMapping: OPTIONAL(CTX(1, IMPLICIT(SkipCerts)))
});
var ReasonFlags = BIT_STRING({
unused: 0,
keyCompromise: 1,
cACompromise: 2,
affiliationChanged: 3,
superseded: 4,
cessationOfOperation: 5,
certificateHold: 6,
privilegeWithdrawn: 7,
aACompromise: 8
});
var DistributionPointName = CHOICE({
fullName: CTX(0, IMPLICIT(GeneralNames)),
nameRelativeToCRLIssuer: CTX(1, IMPLICIT(RelativeDistinguishedName))
}, function (value) {
return value instanceof Array ? 'fullName' : 'nameRelativeToCRLIssuer';
});
var DistributionPoint = SEQUENCE({
distributionPoint: OPTIONAL(CTX(0, EXPLICIT(DistributionPointName))),
// DistributionPointName CHOICE
reasons: OPTIONAL(CTX(1, IMPLICIT(ReasonFlags))),
cRLIssuer: OPTIONAL(CTX(2, IMPLICIT(GeneralNames)))
});
var CRLDistributionPoints = SEQUENCE_OF(DistributionPoint);
var FreshestCRL = CRLDistributionPoints;
var AccessDescription = SEQUENCE({
accessMethod: OBJECT_IDENTIFIER,
accessLocation: GeneralName
});
var Extension = function Extension(typeSet, defaultCritical) {
var Attribute = ATTRIBUTE({
extnID: OBJECT_IDENTIFIER,
critical: DEFAULT(BOOLEAN, false),
extnValue: function extnValue(type) {
return OCTET_STRING(ENCAPSULATES(type));
}
}, 'extnID', 'extnValue');
var Class = extend(Attribute(typeSet), {
object: {
get: function get() {
var value = this._get(Class["super"], 'object');
if (value && _typeof(value.extnValue) === 'object') this.defineValue(value.extnValue);
return value;
},
set: function set(object) {
this._set(Class["super"], 'object', object); // Define critical
if (object && object.extnValue) if (object.extnValue.critical !== undefined) this.critical = object.extnValue.critical;else if (this.critical === undefined && defaultCritical) this.critical = defaultCritical(this.extnID, object.extnValue);
}
},
extnValue: {
get: function get() {
// Get value property of object
var value = this._get(Class["super"], 'extnValue');
if (_typeof(value) === 'object') this.defineValue(value);
return value;
},
set: function set(object) {
// Set value property of object
this._set(Class["super"], 'extnValue', object); // Define critical
if (object) {
if (object.critical !== undefined) this.critical = object.critical;else if (this.critical === undefined && defaultCritical) this.critical = defaultCritical(this.extnID, object);
}
}
},
defineValue: function defineValue(value) {
if (_typeof(value) === 'object') if (!getOwnPropertyDescriptor(value, 'critical')) {
var self = this;
defineProperty(value, 'critical', {
get: function get() {
return self.critical;
},
set: function set(value) {
self.critical = value;
},
enumerable: true,
configurable: false
});
}
}
});
return Class;
}; // http://base.garant.ru/70133464/#ixzz4KaOTGI1l
var IssuerSignTool = SEQUENCE({
signTool: UTF8String,
cATool: UTF8String,
signToolCert: UTF8String,
cAToolCert: UTF8String
});
/**
* Extensions is a base class for extension attributes of certificates, CRLs, requests and etc.
*
* @class GostASN1.Extensions
* @extends GostASN1.Set
*/
var Extensions = SEQUENCE_OF(Extension, {
typeName: 'extnID',
valueName: 'extnValue'
});
var CertExtensions = Extensions({
authorityKeyIdentifier: AuthorityKeyIdentifier,
subjectKeyIdentifier: KeyIdentifier,
keyUsage: KeyUsage,
privateKeyUsagePeriod: PrivateKeyUsagePeriod,
certificatePolicies: SEQUENCE_OF(PolicyInformation),
policyMappings: SEQUENCE_OF(PolicyMapping),
subjectAltName: GeneralNames,
issuerAltName: GeneralNames,
subjectDirectoryAttributes: AttributeSequence,
basicConstraints: BasicConstraints,
nameConstraints: NameConstraints,
policyConstraints: PolicyConstraints,
extKeyUsage: ExtKeyUsageSyntax,
cRLDistributionPoints: CRLDistributionPoints,
inhibitAnyPolicy: SkipCerts,
freshestCRL: FreshestCRL,
authorityInfoAccess: SEQUENCE_OF(AccessDescription),
subjectInfoAccess: SEQUENCE_OF(AccessDescription),
subjectSignTool: UTF8String,
issuerSignTool: IssuerSignTool
}, function (id, value) {
return id === 'keyUsage' || id === 'basicConstraints' && value.pathLenConstraint === undefined;
}); // </editor-fold>
/*
* Signature Values
*
* http://tools.ietf.org/html/rfc5280
* http://tools.ietf.org/html/rfc4491
*
*/
// <editor-fold defaultstate="collapsed">
/**
* Gost Signature encode signature values for different GOST signatures
* Support algorithms:
* <pre>
* {
* 'id-GostR3410-94': GostR3410Signature,
* 'id-GostR3410-2001': GostR3410Signature,
* 'id-tc26-gost3410-12-256': GostR3410Signature,
* 'id-tc26-gost3410-12-512': GostR3410Signature,
* 'id-GostR3411-94-with-GostR3410-2001': GostR3410Signature,
* 'id-GostR3411-94-with-GostR3410-94': GostR3410Signature,
* 'id-tc26-signwithdigest-gost3410-12-94': GostR3410Signature,
* 'id-tc26-signwithdigest-gost3410-12-256': GostR3410Signature,
* 'id-tc26-signwithdigest-gost3410-12-512': GostR3410Signature,
* 'id-sc-gostR3410-94': ECDHSignature,
* 'id-sc-gostR3410-2001': ECDHSignature,
* 'id-sc-gostR3411-94-with-gostR3410-94': ECDHSignature,
* 'id-sc-gostR3411-94-with-gostR3410-2001': ECDHSignature
* }
* </pre>
*
* @class GostASN1.GostSignature
* @extends GostASN1.Sequence
*/
// SignalCom signature
var ECDHSignature = SEQUENCE({
r: INTEGER,
s: INTEGER
});
var GostR3410Signature = ANY; // Signature value (only need for CryptoPro
// var GostSignature = extend(CHOICE({
// ecdhSignature: ECDHSignature}, 'ecdhSignature'));
var GostSignature = ECDHSignature; // </editor-fold>
/*
* Certificate
*
* http://tools.ietf.org/html/rfc5280
*
*/
// <editor-fold defaultstate="collapsed">
/**
* The sequence TBSCertificate contains information associated with the
* subject of the certificate and the CA who issued it. Every
* TBSCertificate contains the names of the subject and issuer, a public
* key associated with the subject, a validity period, a version number,
* and a serial number; some MAY contain optional unique identifier
* fields. The remainder of this section describes the syntax and
* semantics of these fields. A TBSCertificate usually includes
* extensions.
* <pre>
* TBSCertificate ::= SEQUENCE {
* version [0] EXPLICIT Version DEFAULT v1,
* serialNumber CertificateSerialNumber,
* signature AlgorithmIdentifier,
* issuer Name,
* validity Validity,
* subject Name,
* subjectPublicKeyInfo SubjectPublicKeyInfo,
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version MUST be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version MUST be v3
* }
*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*
* CertificateSerialNumber ::= INTEGER
*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
*
* UniqueIdentifier ::= BIT STRING
*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
* </pre>
* See {@link GostASN1.Certificate} and {@link GostASN1.SubjectPublicKeyInfo}<br><br>
* RFC 5280 references {@link http://tools.ietf.org/html/rfc5280}
*
* @class GostASN1.TBSCertificate
* @extends GostASN1.Sequence
* @extends GostASN1.Validity
* @property {number} version The version of the encoded certificate
* @property {(number|string)} serialNumber The serial number MUST be a positive integer assigned by the CA to each certificate.
* @property {AlgorithmIdentifier} signature The algorithm identifier for the algorithm used by the CA to sign the certificate.
* @property {GostASN1.Name} issuer The issuer field identifies the entity that has signed and issued the certificate.
* @property {GostASN1.Validity} validity The certificate validity period
* @property {GostASN1.Name} subject The subject field identifies the entity associated with the public key stored in the subject public key field.
* @property {GostASN1.SubjectPublicKeyInfo} subject The public key and identify the algorithm with which the key is used
* @property {CryptoOperationData} issuerUniqueID The issuer unique identifier
* @property {CryptoOperationData} subjectUniqueID The subject unique identifier
* @property {GostASN1.Extensions} extensions The extensions defined for X.509 v3 certificates
*/
var TBSCertificate = COMBINE(SEQUENCE({
version: CTX(0, EXPLICIT(Version)),
serialNumber: CertificateSerialNumber,
signature: SignatureAlgorithmIdentifier,
issuer: Name,
validity: Validity,
subject: Name,
subjectPublicKeyInfo: SubjectPublicKeyInfo,
issuerUniqueID: OPTIONAL(CTX(1, IMPLICIT(UniqueIdentifier))),
// If present, version MUST be v2 or v3
subjectUniqueID: OPTIONAL(CTX(2, IMPLICIT(UniqueIdentifier))),
// If present, version MUST be v2 or v3
extensions: OPTIONAL(CTX(3, EXPLICIT(CertExtensions)))
})); // If present, version MUST be v3
/**
* The X.509 v3 certificate basic syntax is as follows. For signature
* calculation, the data that is to be signed is encoded using the ASN.1
* distinguished encoding rules (DER) [X.690]. ASN.1 DER encoding is a
* tag, length, value encoding system for each element.
* <pre>
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
* </pre>
* See {@link GostASN1.TBSCertificate}<br><br>
* RFC 5280 references {@link http://tools.ietf.org/html/rfc5280}
*
* @class GostASN1.Certificate
* @extends GostASN1.TBSCertificate
* @property {GostASN1.TBSCertificate} tbsCertificate The sequence TBSCertificate
* @property {AlgorithmIndentifier} signatureAlgorithm Identifies signature algorithm
* @property {CryptoOperationData} signatureValue Signature value
*/
var Certificate = SEQUENCE({
tbsCertificate: TBSCertificate,
signatureAlgorithm: SignatureAlgorithmIdentifier,
signatureValue: BIT_STRING
}, 'CERTIFICATE'); // </editor-fold>
/*
* Certification Request
*
* http://tools.ietf.org/html/rfc2986
*
*/
// <editor-fold defaultstate="collapsed">
var ExtensionRequest = CertExtensions;
var CRIAttributes = Attributes({
challengePassword: SET_OF_SINGLE(DirectoryString),
extensionRequest: SET_OF_SINGLE(ExtensionRequest),
msCertExtensions: SET_OF_SINGLE(CertExtensions),
extendedCertificateAttributes: SET_OF_SINGLE(Attributes)
});
/**
* Certification request information shall have ASN.1 type CertificationRequestInfo:
* <pre>
* CertificationRequestInfo ::= SEQUENCE {
* version INTEGER { v1(0) } (v1,...),
* subject Name,
* subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
* attributes [0] Attributes{{ CRIAttributes }}
* }
*
* SubjectPublicKeyInfo { ALGORITHM : IOSet} ::= SEQUENCE {
* algorithm AlgorithmIdentifier {{IOSet}},
* subjectPublicKey BIT STRING
* }
*
* PKInfoAlgorithms ALGORITHM ::= {
* ... -- add any locally defined algorithms here -- }
*
* Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
*
* CRIAttributes ATTRIBUTE ::= {
* ... -- add any locally defined attributes here -- }
*
* Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
* type ATTRIBUTE.&id({IOSet}),
* values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
* }
* </pre>
* See {@link GostASN1.CertificationRequest} and {@link GostASN1.SubjectPublicKeyInfo}<br><br>
* RFC 2986 references {@link http://tools.ietf.org/html/rfc2986}
*
* @class GostASN1.CertificationRequestInfo
* @extends GostASN1.Sequence
* @property {number} version The version of the encoded request
* @property {GostASN1.Name} subject The subject field identifies the entity associated with the public key stored in the subject public key field.
* @property {GostASN1.SubjectPublicKeyInfo} subject The public key and identify the algorithm with which the key is used
* @property {GostASN1.Attributes} attributes The request attributes
*/
var CertificationRequestInfo = COMBINE(SEQUENCE({
version: INTEGER,
subject: Name,
subjectPublicKeyInfo: SubjectPublicKeyInfo,
attributes: CTX(0, IMPLICIT(CRIAttributes))
}));
/**
* A certification request consists of three parts: "certification
* request information," a signature algorithm identifier, and a digital
* signature on the certification request information. The
* certification request information consists of the entity's
* distinguished name, the entity's public key, and a set of attributes
* providing other information about the entity.
* <pre>
* A certification request shall have ASN.1 type CertificationRequest:
*
* CertificationRequest ::= SEQUENCE {
* certificationRequestInfo CertificationRequestInfo,
* signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
* signature BIT STRING
* }
*
* AlgorithmIdentifier {ALGORITHM:IOSet } ::= SEQUENCE {
* algorithm ALGORITHM.&id({IOSet}),
* parameters ALGORITHM.&Type({IOSet}{@algorithm}) OPTIONAL
* }
*
* SignatureAlgorithms ALGORITHM ::= {
* ... -- add any locally defined algorithms here -- }
* </pre>
* See {@link GostASN1.CertificationRequestInfo}
* RFC 2986 references {@link http://tools.ietf.org/html/rfc2986}
*
* @class GostASN1.CertificationRequest
* @extends GostASN1.CertificationRequestInfo
* @property {GostASN1.CertificationRequestInfo} requestInfo Request information
* @property {AlgorithmIndentifier} signatureAlgorithm Identifies signature algorithm
* @property {CryptoOperationData} signatureValue Signature value
*/
var CertificationRequest = SEQUENCE({
requestInfo: CertificationRequestInfo,
signatureAlgorithm: SignatureAlgorithmIdentifier,
signatureValue: BIT_STRING
}, 'CERTIFICATE REQUEST'); // </editor-fold>
/*
* Certificate Revocation List
*
* http://tools.ietf.org/html/rfc5280
*
*/
// <editor-fold defaultstate="collapsed">
var CRLNumber = INTEGER;
var CRLReason = ENUMERATED({
unspecified: 0,
keyCompromise: 1,
cACompromise: 2,
affiliationChanged: 3,
superseded: 4,
cessationOfOperation: 5,
certificateHold: 6,
removeFromCRL: 8,
privilegeWithdrawn: 9,
aACompromise: 10
});
var IssuingDistributionPoint = SEQUENCE({
distributionPoint: OPTIONAL(CTX(0, EXPLICIT(DistributionPointName))),
// DistributionPointName is CHOICE
onlyContainsUserCerts: DEFAULT(CTX(1, IMPLICIT(BOOLEAN)), false),
onlyContainsCACerts: DEFAULT(CTX(2, IMPLICIT(BOOLEAN)), false),
onlySomeReasons: OPTIONAL(CTX(3, IMPLICIT(ReasonFlags))),
indirectCRL: DEFAULT(CTX(4, IMPLICIT(BOOLEAN)), false),
onlyContainsAttributeCerts: DEFAULT(CTX(5, IMPLICIT(BOOLEAN)), false)
});
var CLRExtensions = Extensions({
authorityKeyIdentifier: AuthorityKeyIdentifier,
issuerAltName: GeneralNames,
cRLNumber: CRLNumber,
deltaCRLIndicator: CRLNumber,
issuingDistributionPoint: IssuingDistributionPoint,
freshestCRL: FreshestCRL
}, function (id) {
return id === 'cRLNumber';
});
var CLREntryExtensions = Extensions({
cRLReason: CRLReason,
instructionCode: OBJECT_IDENTIFIER,
invalidityDate: GeneralizedTime,
certificateIssuer: GeneralNames
});
/**
* This field is itself a sequence containing the name of the issuer,
* issue date, issue date of the next list, the optional list of revoked
* certificates, and optional CRL extensions. When there are no revoked
* certificates, the revoked certificates list is absent. When one or
* more certificates are revoked, each entry on the revoked certificate
* list is defined by a sequence of user certificate serial number,
* revocation date, and optional CRL entry extensions.
* <pre>
* TBSCertList ::= SEQUENCE {
* version Version OPTIONAL,
* -- if present, MUST be v2
* signature AlgorithmIdentifier,
* issuer Name,
* thisUpdate Time,
* nextUpdate Time OPTIONAL,
* revokedCertificates SEQUENCE OF SEQUENCE {
* userCertificate CertificateSerialNumber,
* revocationDate Time,
* crlEntryExtensions Extensions OPTIONAL
* -- if present, MUST be v2
* } OPTIONAL,
* crlExtensions [0] EXPLICIT Extensions OPTIONAL
* -- if present, MUST be v2
* }
* </pre>
* See {@link GostASN1.CertificateList}<br><br>
* RFC 5280 references {@link http://tools.ietf.org/html/rfc5280}
*
* @class GostASN1.TBSCertList
* @extends GostASN1.Sequence
* @property {number} version The version of the encoded CRL
* @property {AlgorithmIdentifier} signature The algorithm identifier for the algorithm used to sign the CRL
* @property {Name} issuer The issuer name identifies the entity that has signed and issued the CRL
* @property {Date} thisUpdate The issue date of this CRL
* @property {Date} nextUpdate The date by which the next CRL will be issued
* @property {Array} revokedCertificates The revoked certificates are listed by their serial numbers
* @property {Extensions} crlExtensions The CRL extensions
*/
var TBSCertList = COMBINE(SEQUENCE({
version: OPTIONAL(Version),
// if present, MUST be v2
signature: SignatureAlgorithmIdentifier,
issuer: Name,
thisUpdate: Time,
nextUpdate: OPTIONAL(Time),
revokedCertificates: OPTIONAL(SEQUENCE_OF(SEQUENCE({
userCertificate: CertificateSerialNumber,
revocationDate: Time,
crlEntryExtensions: OPTIONAL(CLREntryExtensions) // if present, MUST be v2
}))),
crlExtensions: OPTIONAL(CTX(0, EXPLICIT(CLRExtensions)))
})); // if present, MUST be v2
/**
* The X.509 v2 CRL syntax is as follows. For signature calculation,
* the data that is to be signed is ASN.1 DER encoded. ASN.1 DER
* encoding is a tag, length, value encoding system for each element.
* <pre>
* CertificateList ::= SEQUENCE {
* tbsCertList TBSCertList,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
* </pre>
* See {@link GostASN1.TBSCertList}<br><br>
* RFC 5280 references {@link http://tools.ietf.org/html/rfc5280}
*
* @class GostASN1.CertificateList
* @extends GostASN1.TBSCertList
* @property {GostASN1.TBSCertList} tbsCertList The tbsCertList
* @property {AlgorithmIndentifier} signatureAlgorithm Identifies signature algorithm
* @property {CryptoOperationData} signatureValue Signature value
*/
var CertificateList = SEQUENCE({
tbsCertList: TBSCertList,
signatureAlgorithm: SignatureAlgorithmIdentifier,
signatureValue: BIT_STRING
}, 'CRL'); // </editor-fold>
/*
* Attribute Certificate Definision
* http://tools.ietf.org/html/rfc5755
*
*/
// <editor-fold defaultstate="collapsed">
var AttCertVersion = INTEGER;
var ObjectDigestInfo = SEQUENCE({
digestedObjectType: ENUMERATED({
publicKey: 0,
publicKeyCert: 1,
otherObjectTypes: 2
}),
// otherObjectTypes MUST NOT be used in this profile
otherObjectTypeID: OPTIONAL(OBJECT_IDENTIFIER),
digestAlgorithm: DigestAlgorithmIdentifier,
objectDigest: BIT_STRING
});
var IssuerSerial = SEQUENCE({
issuer: GeneralNames,
serial: CertificateSerialNumber,
issuerUID: OPTIONAL(UniqueIdentifier)
});
var V2Form = SEQUENCE({
issuerName: OPTIONAL(GeneralNames),
baseCertificateID: OPTIONAL(CTX(0, IMPLICIT(IssuerSerial))),
// issuerName MUST be present in this profile baseCertificateID and
// objectDigestInfo MUST NOT be present in this profile
objectDigestInfo: OPTIONAL(CTX(1, IMPLICIT(ObjectDigestInfo)))
});
var TargetCert = SEQUENCE({
targetCertificate: IssuerSerial,
targetName: OPTIONAL(GeneralName),
certDigestInfo: OPTIONAL(ObjectDigestInfo)
});
var Target = CHOICE({
targetName: CTX(0, EXPLICIT(GeneralName)),
// GeneralName is CHOICE
targetGroup: CTX(1, EXPLICIT(GeneralName)),
targetCert: CTX(2, IMPLICIT(TargetCert))
});
var Targets = SEQUENCE_OF(Target);
var AttCertExtensions = Extensions({
auditIdentity: OCTET_STRING,
targetInformation: Targets,
authorityKeyIdentifier: AuthorityKeyIdentifier,
authorityInfoAccess: SEQUENCE_OF(AccessDescription),
cRLDistributionPoints: CRLDistributionPoints,
noRevAvail: NULL
}, function (id) {
return id === 'auditIdentity' || id === 'targetInformation';
});
var Holder = SEQUENCE({
// the issuer and serial number of the holder's Public Key Certificate
baseCertificateID: OPTIONAL(CTX(0, IMPLICIT(IssuerSerial))),
// the name of the claimant or role
entityName: OPTIONAL(CTX(1, IMPLICIT(GeneralNames))),
// used to directly authenticate the holder, for example, an executable
objectDigestInfo: OPTIONAL(CTX(2, IMPLICIT(ObjectDigestInfo)))
});
var AttCertIssuer = CHOICE({
v1Form: GeneralNames,
// MUST NOT be used in this profile
v2Form: CTX(0, IMPLICIT(V2Form))
}, 'v2Form'); // v2 only
var AttCertValidityPeriod = SEQUENCE({
notBeforeTime: GeneralizedTime,
notAfterTime: GeneralizedTime
});
var SvceAuthInfo = SEQUENCE({
service: GeneralName,
ident: GeneralName,
authInfo: OPTIONAL(OCTET_STRING)
});
var RoleSyntax = SEQUENCE({
roleAuthority: OPTIONAL(CTX(0, IMPLICIT(GeneralNames))),
roleName: CTX(1, EXPLICIT(GeneralName))
}); // GeneralName is CHOICE
var ClassList = BIT_STRING({
unmarked: 0,
unclassified: 1,
restricted: 2,
confidential: 3,
secret: 4,
topSecret: 5
});
var SecurityCategory = SEQUENCE({
type: CTX(0, IMPLICIT(OBJECT_IDENTIFIER)),
value: CTX(1, IMPLICIT(ANY))
});
var Clearance = SEQUENCE({
policyId: CTX(0, IMPLICIT(OBJECT_IDENTIFIER)),
classList: DEFAULT(CTX(1, IMPLICIT(ClassList)), ['unclassified']),
securityCategories: OPTIONAL(CTX(2, IMPLICIT(SET_OF(SecurityCategory))))
});
var IetfAttrSyntax = SEQUENCE({
policyAuthority: OPTIONAL(CTX(0, IMPLICIT(GeneralNames))),
values: SEQUENCE_OF(CHOICE({
octets: OCTET_STRING,
oid: OBJECT_IDENTIFIER,
string: UTF8String
}, function (value) {
return isBinary ? 'octets' : getIdentifier(value) ? 'oid' : 'string';
}))
});
/**
* X.509 Attribute Certificate Definition<br><br>
*
* X.509 contains the definition of an AC given below. All types that
* are not defined in this document can be found in [PKIXPROF].
* <pre>
* AttributeCertificateInfo ::= SEQUENCE {
* version AttCertVersion -- version is v2,
* holder Holder,
* issuer AttCertIssuer,
* signature AlgorithmIdentifier,
* serialNumber CertificateSerialNumber,
* attrCertValidityPeriod AttCertValidityPeriod,
* attributes SEQUENCE OF Attribute,
* issuerUniqueID UniqueIdentifier OPTIONAL,
* extensions Extensions OPTIONAL
* }
* <pre>
* RFC 3281 references {@link http://tools.ietf.org/html/rfc3281}
*
* @class GostASN1.AttributeCertificateInfo
* @extends GostASN1.Sequence
* @property {number} version The version of the encoded certificate
* @property {GostASN1.Name} holder Identifies the holder.
* @property {GostASN1.Name} issuer Identifies the issuer.
* @property {AlgorithmIdentifier} signature The algorithm identifier for the algorithm used by the CA to sign the certificate.
* @property {(number|string)} serialNumber The serial number MUST be a positive integer assigned by the CA to each certificate.
* @property {GostASN1.Validity} attrCertValidityPeriod The certificate validity period
* @property {GostASN1.Attributes} attributes The certificate attributes
* @property {CryptoOperationData} issuerUniqueID The issuer unique identifier
* @property {GostASN1.Extensions} extensions The certificate extensions
*/
var AttributeCertificateInfo = COMBINE(SEQUENCE({
version: AttCertVersion,
// version is v2,
holder: Holder,
issuer: AttCertIssuer,
signature: SignatureAlgorithmIdentifier,
serialNumber: CertificateSerialNumber,
attrCertValidityPeriod: AttCertValidityPeriod,
attributes: AttributeSequence({
authenticationInfo: SET_OF(SvceAuthInfo),
accessIdentity: SET_OF(SvceAuthInfo),
chargingIdentity: SET_OF_SINGLE(IetfAttrSyntax),
group: SET_OF_SINGLE(IetfAttrSyntax),
role: SET_OF(RoleSyntax),
clearance: SET_OF(Clearance)
}),
issuerUniqueID: OPTIONAL(UniqueIdentifier),
extensions: OPTIONAL(AttCertExtensions)
}));
/**
* Attribute Certificate Profile<br></br>
*
* ACs may be used in a wide range of applications and environments
* covering a broad spectrum of interoperability goals and a broader
* spectrum of operational and assurance requirements. The goal of this
* document is to establish a common baseline for generic applications
* requiring broad interoperability and limited special purpose
* requirements. In particular, the emphasis will be on supporting the
* use of attribute certificates for informal Internet electronic mail,
* IPSec, and WWW applications.
* <pre>
* AttributeCertificate ::= SEQUENCE {
* acinfo AttributeCertificateInfo,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
* }
* </pre>
* See {@link GostASN1.AttributeCertificateInfo}<br><br>
* RFC 3281 references {@link http://tools.ietf.org/html/rfc3281}
*
* @class GostASN1.AttributeCertificate
* @extends GostASN1.AttributeCertificateInfo
* @property {GostASN1.AttributeCertificateInfo} acinfo Attribute certificate information
* @property {AlgorithmIndentifier} signatureAlgorithm Identifies signature algorithm
* @property {CryptoOperationData} signatureValue Signature value
*/
var AttributeCertificate = SEQUENCE({
acinfo: AttributeCertificateInfo,
signatureAlgorithm: SignatureAlgorithmIdentifier,
signatureValue: BIT_STRING
}, 'ATTRIBUTE CERTIFICATE'); // </editor-fold>
/*
* Encrypted Key with CMS
*
* http://tools.ietf.org/html/rfc5652
* http://tools.ietf.org/html/rfc4490
*
*/
// <editor-fold defaultstate="collapsed">
// RecipientInfo
var EncryptedKey = OCTET_STRING;
var EncryptedContent = OCTET_STRING;
var SubjectKeyIdentifier = OCTET_STRING;
var UserKeyingMaterial = OCTET_STRING;
var ECCCMSSharedInfo = SEQUENCE({
keyInfo: KeyWrapAlgorithmIdentifier,
entityUInfo: OPTIONAL(CTX(0, EXPLICIT(OCTET_STRING))),
suppPubInfo: CTX(2, EXPLICIT(OCTET_STRING))
}); // GOST Key Transport & Key agreement rfc4490
var Gost2814789EncryptedKey = ENCLOSURE(SEQUENCE({
encryptedKey: Gost2814789Key,
maskKey: OPTIONAL(CTX(0, IMPLICIT(Gost2814789Key))),
macKey: Gost2814789MAC
}), {
encode: function encode(value) {
// wrappedKey: (CEK_ENC(32) | CEK_MAC(4))
var encryptedKey = new Uint8Array(new Uint8Array(value, 0, 32)).buffer,
macKey = new Uint8Array(new Uint8Array(value, 32, 4)).buffer;
return {
// from wrapped key
encryptedKey: encryptedKey,
macKey: macKey
};
},
decode: function decode(value) {
var encryptedKey = value.encryptedKey,
maskKey = value.maskKey,
macKey = value.macKey;
if (maskKey) {
var m = new Int32Array(maskKey),
k = new Int32Array(encryptedKey);
for (var i = 0, n = m.length / k.length; i < n; i++) {
for (var j = 0, l = k.length; j < l; j++) {
k[j] = k[j] + m[l * i + j] & 0xffffffff;
}
}
}
var result = new Uint8Array(encryptedKey.byteLength + macKey.byteLength);
result.set(new Uint8Array(encryptedKey), 0);
result.set(new Uint8Array(macKey), 32);
return result.buffer;
}
});
var GostR3410TransportParameters = SEQUENCE({
encryptionParamSet: Gost2814789ParamSet,
ephemeralPublicKey: OPTIONAL(CTX(0, IMPLICIT(GostSubjectPublicKeyInfo))),
ukm: OCTET_STRING
}); // ( SIZE(8) )
var GostR3410KeyTransport = ENCLOSURE(SEQUENCE({
sessionEncryptedKey: Gost2814789EncryptedKey,
transportParameters: OPTIONAL(CTX(0, IMPLICIT(GostR3410TransportParameters)))
}), {
encode: function encode(value) {
var algorithm = value.algorithm;
return {
sessionEncryptedKey: value.sessionEncryptedKey,
transportParameters: {
encryptionParamSet: attributes['sBox'][algorithm.wrapping.sBox || 'E-A'],
ephemeralPublicKey: algorithm['public'],
ukm: algorithm.ukm
}
};
},
decode: function decode(value) {
return {
algorithm: {
wrapping: parameters[value.transportParameters.encryptionParamSet],
ukm: value.transportParameters.ukm,
'public': value.transportParameters.ephemeralPublicKey
},
sessionEncryptedKey: value.sessionEncryptedKey
};
}
});
var SCGostKeyTransport = ENCLOSURE(SEQUENCE({
sessionEncryptedKey: Gost2814789EncryptedKey,
ukm: SEQUENCE({
ephemeralPublicKey: GostSubjectPublicKeyInfo,
addedukm: OPTIONAL(CTX(0, EXPLICIT(UserKeyingMaterial)))
})
}), {
encode: function encode(value) {
var algorithm = value.algorithm;
return {
sessionEncryptedKey: value.sessionEncryptedKey,
ukm: {
ephemeralPublicKey: algorithm['public'],
addedukm: algorithm.ukm
}
};
},
decode: function decode(value) {
return {
algorithm: {
ukm: value.ukm.addedukm,
'public': value.ukm.ephemeralPublicKey
},
sessionEncryptedKey: value.sessionEncryptedKey
};
}
});
var GostEncryptedKey = function (typeSet) {
/**
* Gost Encrypted key encoder for CMS
*
* @class GostASN1.GostEncryptedKey
* @extends GostASN1.Sequence
* @param {AlgorithmIdentifier} algorithm
*/
return function (algorithm) {
var type = typeSet[algorithm.id];
return type ? ENCAPSULATES(type) : ANY;
};
}({
// Key transport algorithms
'id-sc-gostR3410-2001': SCGostKeyTransport,
'id-sc-gostR3410-94': SCGostKeyTransport,
'id-GostR3410-2001': GostR3410KeyTransport,
'id-GostR3410-94': GostR3410KeyTransport,
'id-tc26-gost3410-12-256': GostR3410KeyTransport,
'id-tc26-gost3410-12-512': GostR3410KeyTransport,
// Key agreement algorithms
'id-GostR3410-94-CryptoPro-ESDH': Gost2814789EncryptedKey,
'id-GostR3410-2001-CryptoPro-ESDH': Gost2814789EncryptedKey,
'id-tc26-agreement-gost-3410-12-256': Gost2814789EncryptedKey,
'id-tc26-agreement-gost-3410-12-512': Gost2814789EncryptedKey,
'id-sc-r3410-ESDH-r3411kdf': Gost2814789EncryptedKey,
// Key encryption key algorithms
'id-Gost28147-89-None-KeyWrap': Gost2814789EncryptedKey,
'id-Gost28147-89-CryptoPro-KeyWrap': Gost2814789EncryptedKey,
'id-sc-cmsGostWrap': Gost2814789EncryptedKey,
'id-sc-cmsGost28147Wrap': Gost2814789EncryptedKey
}); // </editor-fold>
/*
* CryptoPro Gost Private Key Store
*/
// <editor-fold defaultstate="collapsed">
var GostKeyContainerContentAttributes = BIT_STRING({
kccaSoftPassword: 0,
kccaReservePrimary: 1,
kccaPrimaryKeyAbsent: 2,
kccaFKCShared: 3
});
var GostPrivateKeyAttributes = BIT_STRING({
pkaExportable: 0,
pkaUserProtect: 1,
pkaExchange: 2,
pkaEphemeral: 3,
pkaNonCachable: 4,
pkaDhAllowed: 5
});
var GostPrivateKeyParameters = SEQUENCE({
attributes: OPTIONAL(GostPrivateKeyAttributes),
privateKeyAlgorithm: OPTIONAL(CTX(0, IMPLICIT(KeyAlgorithmIdentifier)))
});
var CertificateLink = SEQUENCE({
path: IA5String,
hmac: Gost2814789MAC
});
var PasswordPolicy = AlgorithmIdentifier;
var GostKeyContainerContent = SEQUENCE({
containerAlgoritmIdentifier: OPTIONAL(CTX(0, IMPLICIT(AlgorithmIdentifier))),
containerName: OPTIONAL(IA5String),
attributes: GostKeyContainerContentAttributes,
primaryPrivateKeyParameters: GostPrivateKeyParameters,
hmacPassword: OPTIONAL(CTX(2, IMPLICIT(Gost2814789MAC))),
secondaryEncryptedPrivateKey: OPTIONAL(CTX(3, IMPLICIT(Gost2814789EncryptedKey))),
secondaryPrivateKeyParameters: OPTIONAL(CTX(4, IMPLICIT(GostPrivateKeyParameters))),
primaryCertificate: OPTIONAL(CTX(5, IMPLICIT(OCTET_STRING(ENCAPSULATES(Certificate))))),
secondaryCertificate: OPTIONAL(CTX(6, IMPLICIT(OCTET_STRING(ENCAPSULATES(Certificate))))),
encryptionContainerName: OPTIONAL(CTX(7, IMPLICIT(IA5String))),
primaryCertificateLink: OPTIONAL(CTX(8, IMPLICIT(CertificateLink))),
secondaryCertificateLink: OPTIONAL(CTX(9, IMPLICIT(CertificateLink))),
primaryFP: OPTIONAL(CTX(10, IMPLICIT(OCTET_STRING))),
secondaryFP: OPTIONAL(CTX(11, IMPLICIT(OCTET_STRING))),
passwordPolicy: OPTIONAL(PasswordPolicy),
containerSecurityLevel: OPTIONAL(INTEGER),
extensions: OPTIONAL(CTX(12, IMPLICIT(Extensions({
keyValidity: SEQUENCE({
notBefore: OPTIONAL(CTX(0, IMPLICIT(GeneralizedTime))),
notAfter: OPTIONAL(CTX(1, IMPLICIT(GeneralizedTime)))
})
})))),
secondaryEncryptionContainerName: OPTIONAL(CTX(13, IMPLICIT(IA5String)))
});
/**
* CryptoPro key container header
*
* @class GostASN1.GostKeyContainer
* @extends GostASN1.Sequence
*/
var GostKeyContainer = SEQUENCE({
keyContainerContent: GostKeyContainerContent,
hmacKeyContainerContent: Gost2814789MAC
});
/**
* CryptoPro key container name
*
* @class GostASN1.GostKeyContainerName
* @extends GostASN1.Sequence
*/
var GostKeyContainerName = SEQUENCE({
containerName: IA5String,
extElem1: OPTIONAL(ANY)
});
/**
* PrivateKey encrypted content for CryptoPro key containers
*
* @class GostASN1.GostPrivateKeys
* @extends GostASN1.Sequence
*/
var GostPrivateKeys = SEQUENCE({
primaryKey: Gost2814789Key,
secondaryKey: OPTIONAL(Gost2814789Key),
hmacKey: OPTIONAL(Gost2814789MAC)
});
/**
* PrivateKey masks for CryptoPro key containers
*
* @class GostASN1.GostPrivateMasks
* @extends GostASN1.Sequence
*/
var GostPrivateMasks = SEQUENCE({
mask: Gost2814789Key,
randomStatus: OCTET_STRING,
hmacRandom: Gost2814789MAC
}); // </editor-fold>
/*
* ViPNet Gost Private Key Store
*/
// <editor-fold defaultstate="collapsed">
var ViPNetKeyInfo = SEQUENCE({
keyClass: INTEGER,
keyType: INTEGER,
algorithm: OPTIONAL(CTX(0, EXPLICIT(KeyAlgorithmIdentifier))),
serialNumber: OPTIONAL(CTX(1, EXPLICIT(OCTET_STRING))),
addSerialNumber: OPTIONAL(CTX(2, EXPLICIT(OCTET_STRING))),
certSerialNumber: OPTIONAL(CTX(3, EXPLICIT(OCTET_STRING))),
subjectUID: OPTIONAL(CTX(4, EXPLICIT(OCTET_STRING))),
recipientUID: OPTIONAL(CTX(5, EXPLICIT(OCTET_STRING))),
validity: OPTIONAL(CTX(6, EXPLICIT(CHOICE({
validity: Validity,
keyValidity: SEQUENCE({
notBefore: OPTIONAL(CTX(0, IMPLICIT(GeneralizedTime))),
notAfter: OPTIONAL(CTX(1, IMPLICIT(GeneralizedTime)))
})
}, function () {
return 'keyValidity';
})))),
keyUID: OPTIONAL(CTX(7, EXPLICIT(BIT_STRING))),
flags: OPTIONAL(CTX(10, EXPLICIT(INTEGER)))
});
/**
* ViPNet key container info
*
* @class GostASN1.ViPNetInfo
* @extends GostASN1.Sequence
*/
var ViPNetInfo = SEQUENCE({
version: INTEGER,
keyInfo: ViPNetKeyInfo,
defenceKeyInfo: ViPNetKeyInfo,
certificate: OPTIONAL(CTX(0, EXPLICIT(Certificate))),
publicKey: OPTIONAL(CTX(1, EXPLICIT(OCTET_STRING)))
}); // </editor-fold>
/*
* Cryptographic Message Syntax
*
* http://tools.ietf.org/html/rfc5652
*
*/
// <editor-fold defaultstate="collapsed">
// CMS signed data
var CMSVersion = INTEGER;
var ContentType = OBJECT_IDENTIFIER;
var SigningTime = Time;
var SubjectKeyIdentifier = OCTET_STRING;
var Digest = OCTET_STRING;
var MessageAuthenticationCode = OCTET_STRING;
var BodyPartID = INTEGER;
var BodyPartPath = SEQUENCE_OF(BodyPartID);
var CMCUnsignedData = SEQUENCE({
bodyPartPath: BodyPartPath,
identifier: OBJECT_IDENTIFIER,
content: ANY
}); // DEFINED BY identifier
/**
* SignedAttributes is a collection of attributes that are signed. The
* field is optional, but it MUST be present if the content type of
* the EncapsulatedContentInfo value being signed is not id-data.
* SignedAttributes MUST be DER encoded, even if the rest of the
* structure is BER encoded. Useful attribute types, such as signing
* time, are defined in Section 11. If the field is present, it MUST
* contain, at a minimum, the following two attributes: <br>
*
* A content-type attribute having as its value the content type
* of the EncapsulatedContentInfo value being signed. Section
* 11.1 defines the content-type attribute. However, the
* content-type attribute MUST NOT be used as part of a
* countersignature unsigned attribute as defined in Section 11.4.<br>
*
* A message-digest attribute, having as its value the message
* digest of the content. Section 11.2 defines the message-digest
* attribute.
*
* @class GostASN1.SignedAttributes
* @extends GostASN1.Attributes
*/
var SignedAttributes = Attributes({
contentType: SET_OF_SINGLE(ContentType),
signingTime: SET_OF_SINGLE(SigningTime),
messageDigest: SET_OF_SINGLE(OCTET_STRING)
});
var UnsignedAttributes = Attributes(function (type) {
/**
* UnsignedAttributes is a collection of attributes that are not signed.
* The field is optional. Useful attribute types, such as
* countersignatures.
*
* @class GostASN1.UnsignedAttributes
* @extends GostASN1.Attributes
*/
// var UnsignedAttributes = Attributes({
// countersignature: SET_OF(Countersignature), // -- check forward
// unsignedData: SET_OF(CMCUnsignedData)
// });
return {
countersignature: SET_OF(Countersignature),
// recursion
unsignedData: SET_OF(CMCUnsignedData)
}[type];
});
var AuthAttributes = SignedAttributes,
UnauthAttributes = Attributes,
UnprotectedAttributes = Attributes;
var IssuerAndSerialNumber = SEQUENCE({
issuer: Name,
serialNumber: CertificateSerialNumber
});
var SignerIdentifier = CHOICE({
issuerAndSerialNumber: IssuerAndSerialNumber,
subjectKeyIdentifier: CTX(0, IMPLICIT(SubjectKeyIdentifier))
}, function (value) {
return isBinary(value) ? 'subjectKeyIdentifier' : 'issuerAndSerialNumber';
});
var SignerInfo = SEQUENCE({
version: CMSVersion,
sid: SignerIdentifier,
digestAlgorithm: DigestAlgorithmIdentifier,
signedAttrs: OPTIONAL(CTX(0, IMPLICIT(SignedAttributes))),
signatureAlgorithm: SignatureAlgorithmIdentifier,
signatureValue: OCTET_STRING,
unsignedAttrs: OPTIONAL(CTX(1, IMPLICIT(UnsignedAttributes)))
});
var Countersignature = SignerInfo,
SignerInfos = SET_OF(SignerInfo),
DigestAlgorithmIdentifiers = SET_OF(DigestAlgorithmIdentifier),
AttributeCertificateV2 = AttributeCertificate;
var ExtendedCertificateInfo = COMBINE(SEQUENCE({
version: CMSVersion,
certificate: Certificate,
attributes: UnauthAttributes
}));
var ExtendedCertificate = SEQUENCE({
extendedCertificateInfo: ExtendedCertificateInfo,
signatureAlgorithm: SignatureAlgorithmIdentifier,
signatureValue: BIT_STRING
});
var OtherCertificateFormat = SEQUENCE({
otherCertFormat: OBJECT_IDENTIFIER,
otherCert: ANY
});
var AttributeCertificateInfoV1 = COMBINE(SEQUENCE({
version: INTEGER,
subject: CHOICE({
baseCertificateID: CTX(0, IMPLICIT(IssuerSerial)),
// associated with a Public Key Certificate
subjectName: CTX(1, IMPLICIT(GeneralNames))
}, function (value) {
return value.issuer ? 'baseCertificateID' : 'subjectName';
}),
//associated with a name
issuer: GeneralNames,
signature: SignatureAlgorithmIdentifier,
serialNumber: CertificateSerialNumber,
attCertValidityPeriod: AttCertValidityPeriod,
attributes: AttributeSequence,
issuerUniqueID: OPTIONAL(UniqueIdentifier),
extensions: OPTIONAL(CertExtensions)
}));
var AttributeCertificateV1 = SEQUENCE({
acInfo: AttributeCertificateInfoV1,
signatureAlgorithm: SignatureAlgorithmIdentifier,
signatureValue: BIT_STRING
});
var EncapsulatedContentInfo = SEQUENCE({
eContentType: ContentType,
eContent: OPTIONAL(CTX(0, EXPLICIT(OCTET_STRING)))
});
var CertificateChoices = CHOICE({
certificate: Certificate,
extendedCertificate: CTX(0, IMPLICIT(ExtendedCertificate)),
// Obsolete
v1AttrCert: CTX(1, IMPLICIT(AttributeCertificateV1)),
// Obsolete
v2AttrCert: CTX(2, IMPLICIT(AttributeCertificateV2)),
other: CTX(3, IMPLICIT(OtherCertificateFormat))
}, function (value) {
return value.holder ? 'AttributeCertificateV2' : value.certificate ? 'ExtendedCertificate' : value.otherCertFormat ? 'other' : 'certificate';
});
var OtherRevocationInfoFormat = SEQUENCE({
otherRevInfoFormat: OBJECT_IDENTIFIER,
otherRevInfo: ANY
});
var RevocationInfoChoice = CHOICE({
crl: CertificateList,
other: CTX(1, IMPLICIT(OtherRevocationInfoFormat))
}, function (value) {
return value.otherRevInfoFormat ? 'other' : 'crl';
});
var CertificateSet = SET_OF(CertificateChoices),
RevocationInfoChoices = SET_OF(RevocationInfoChoice);
/**
* The signed-data content type consists of a content of any type and zero or more
* signature values. Any number of signers in parallel can sign any type of content.<br><br>
*
* The signed-data content type shall have ASN.1 type SignedData:<br><br>
*<pre>
*
* SignedData ::= SEQUENCE {
* version CMSVersion,
* digestAlgorithms DigestAlgorithmIdentifiers,
* encapContentInfo EncapsulatedContentInfo,
* certificates [0] IMPLICIT CertificateSet OPTIONAL,
* crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
* signerInfos SignerInfos }
*
* DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
*
* SignerInfos ::= SET OF SignerInfo
*
* EncapsulatedContentInfo ::= SEQUENCE {
* eContentType ContentType,
* eContent [0] EXPLICIT OCTET STRING OPTIONAL }
*
*</pre>
* Per-signer information is represented in the type SignerInfo:<br><br>
*<pre>
*
* SignerInfo ::= SEQUENCE {
* version CMSVersion,
* sid SignerIdentifier,
* digestAlgorithm DigestAlgorithmIdentifier,
* signedAttrs [0] IMPLICIT SignedAttributes OPTIONAL,
* signatureAlgorithm SignatureAlgorithmIdentifier,
* signature SignatureValue,
* unsignedAttrs [1] IMPLICIT UnsignedAttributes OPTIONAL }
*
* SignerIdentifier ::= CHOICE {
* issuerAndSerialNumber IssuerAndSerialNumber,
* subjectKeyIdentifier [0] SubjectKeyIdentifier }
*
* SignedAttributes ::= SET SIZE (1..MAX) OF Attribute
*
* UnsignedAttributes ::= SET SIZE (1..MAX) OF Attribute
*
* SignatureValue ::= OCTET STRING
*
*</pre>
* See also {@link GostASN1.SignedAttributes} and {@link GostASN1.UnsignedAttributes}
* @class GostASN1.SignedData
* @extends GostASN1.Sequence
* @property {number} version The syntax version number
* @property {AlgorithmIdentifier[]} digestAlgorithms Collection of message digest algorithm identifiers
* @property {GostASN1.Sequence} encapContentInfo The content is represented in the type EncapsulatedContentInfo
* @property {GostASN1.Certificate[]} certificates Certificates
* @property {GostASN1.CertificateList[]} crls Certificates
* @property {GostASN1.Sequence[]} signerInfos The Signer information
*/
var SignedData = SEQUENCE({
version: CMSVersion,
digestAlgorithms: DigestAlgorithmIdentifiers,
encapContentInfo: EncapsulatedContentInfo,
certificates: OPTIONAL(CTX(0, IMPLICIT(CertificateSet))),
crls: OPTIONAL(CTX(1, IMPLICIT(RevocationInfoChoices))),
signerInfos: SignerInfos
});
var RecipientIdentifier = CHOICE({
issuerAndSerialNumber: IssuerAndSerialNumber,
subjectKeyIdentifier: CTX(0, IMPLICIT(SubjectKeyIdentifier))
}, function (value) {
return isBinary(value) ? 'subjectKeyIdentifier' : 'issuerAndSerialNumber';
});
var KeyTransRecipientInfo = SEQUENCE({
version: CMSVersion,
// always set to 0 or 2
rid: RecipientIdentifier,
keyEncryptionAlgorithm: KeyEncryptionAlgorithmIdentifier,
encryptedKey: EncryptedKey
});
var OtherKeyAttribute = SEQUENCE({
keyAttrId: OBJECT_IDENTIFIER,
keyAttr: OPTIONAL(ANY)
});
var RecipientKeyIdentifier = SEQUENCE({
subjectKeyIdentifier: SubjectKeyIdentifier,
date: OPTIONAL(GeneralizedTime),
other: OPTIONAL(OtherKeyAttribute)
});
var KeyAgreeRecipientIdentifier = CHOICE({
issuerAndSerialNumber: IssuerAndSerialNumber,
rKeyId: CTX(0, IMPLICIT(RecipientKeyIdentifier))
}, function (value) {
return isBinary(value) ? 'rKeyId' : 'issuerAndSerialNumber';
});
var RecipientEncryptedKey = SEQUENCE({
rid: KeyAgreeRecipientIdentifier,
encryptedKey: EncryptedKey
});
var RecipientEncryptedKeys = SEQUENCE_OF(RecipientEncryptedKey);
var OriginatorPublicKey = SEQUENCE({
algorithm: KeyAlgorithmIdentifier,
publicKey: BIT_STRING
});
var MQVuserKeyingMaterial = SEQUENCE({
// ECC rfc5753 KeyAgreeRecipientInfo in ukm
ephemeralPublicKey: OriginatorPublicKey,
addedukm: OPTIONAL(CTX(0, EXPLICIT(UserKeyingMaterial)))
});
var OriginatorIdentifierOrKey = CHOICE({
issuerAndSerialNumber: IssuerAndSerialNumber,
subjectKeyIdentifier: CTX(0, IMPLICIT(SubjectKeyIdentifier)),
originatorKey: CTX(1, IMPLICIT(OriginatorPublicKey))
}, function (value) {
return isBinary(value) ? 'subjectKeyIdentifier' : value.algorithm ? 'originatorKey' : 'issuerAndSerialNumber';
});
var KeyAgreeRecipientInfo = SEQUENCE({
version: CMSVersion,
// always set to 3
originator: CTX(0, EXPLICIT(OriginatorIdentifierOrKey)),
ukm: OPTIONAL(CTX(1, EXPLICIT(UserKeyingMaterial))),
keyEncryptionAlgorithm: KeyEncryptionAlgorithmIdentifier,
recipientEncryptedKeys: RecipientEncryptedKeys
});
var KEKIdentifier = SEQUENCE({
keyIdentifier: OCTET_STRING,
date: OPTIONAL(GeneralizedTime),
other: OPTIONAL(OtherKeyAttribute)
});
var KEKRecipientInfo = SEQUENCE({
version: CMSVersion,
// always set to 4
kekid: KEKIdentifier,
keyEncryptionAlgorithm: KeyEncryptionAlgorithmIdentifier,
encryptedKey: EncryptedKey
});
var PasswordRecipientInfo = SEQUENCE({
version: CMSVersion,
// always set to 0
friendlyName: OPTIONAL(CTX(0, IMPLICIT(KeyDerivationAlgorithmIdentifier))),
keyEncryptionAlgorithm: KeyEncryptionAlgorithmIdentifier,
encryptedKey: EncryptedKey
});
var OtherRecipientInfo = SEQUENCE({
oriType: OBJECT_IDENTIFIER,
oriValue: ANY
});
var RecipientInfo = CHOICE({
ktri: KeyTransRecipientInfo,
kari: CTX(1, IMPLICIT(KeyAgreeRecipientInfo)),
kekri: CTX(2, IMPLICIT(KEKRecipientInfo)),
pwri: CTX(3, IMPLICIT(PasswordRecipientInfo)),
ori: CTX(4, IMPLICIT(OtherRecipientInfo))
}, function (value) {
return value.rid ? 'ktri' : value.originator ? 'kari' : value.kekid ? 'kekri' : value.oriType ? 'ori' : 'pwri';
});
var OriginatorInfo = SEQUENCE({
certs: OPTIONAL(CTX(0, IMPLICIT(CertificateSet))),
crls: OPTIONAL(CTX(1, IMPLICIT(RevocationInfoChoices)))
});
var RecipientInfos = SET_OF(RecipientInfo); // EncryptedContentInfo
var EncryptedContentInfo = SEQUENCE({
contentType: ContentType,
contentEncryptionAlgorithm: ContentEncryptionAlgorithmIdentifier,
encryptedContent: OPTIONAL(CTX(0, IMPLICIT(EncryptedContent)))
});
/**
* The enveloped-data content type consists of an encrypted content of
* any type and encrypted content-encryption keys for one or more
* recipients. The combination of the encrypted content and one
* encrypted content-encryption key for a recipient is a "digital
* envelope" for that recipient. Any type of content can be enveloped
* for an arbitrary number of recipients using any of the supported key
* management techniques for each recipient.<br><br>
*
* The typical application of the enveloped-data content type will
* represent one or more recipients' digital envelopes on content of the
* data or signed-data content types.<br><br>
* <pre>
*
* EnvelopedData ::= SEQUENCE {
* version CMSVersion,
* originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
* recipientInfos RecipientInfos,
* encryptedContentInfo EncryptedContentInfo,
* unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
*
* OriginatorInfo ::= SEQUENCE {
* certs [0] IMPLICIT CertificateSet OPTIONAL,
* crls [1] IMPLICIT RevocationInfoChoices OPTIONAL }
*
* RecipientInfos ::= SET SIZE (1..MAX) OF RecipientInfo
*
* EncryptedContentInfo ::= SEQUENCE {
* contentType ContentType,
* contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
* encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }
*
* EncryptedContent ::= OCTET STRING
*
* UnprotectedAttributes ::= SET SIZE (1..MAX) OF Attribute
*
* </pre>
* @class GostASN1.EnvelopedData
* @extends GostASN1.Sequence
* @property {number} version The syntax version number
* @property {GostASN1.Sequence} originatorInfo Optionally provides information about the originator.
* @property {GostASN1.Sequence[]} recipientInfos Collection of per-recipient information.
* @property {GostASN1.Sequence} encryptedContentInfo The content is represented in the type EncryptedContentInfo
* @property {Attributes} unprotectedAttrs The unprotected attributes
*/
var EnvelopedData = SEQUENCE({
version: CMSVersion,
originatorInfo: OPTIONAL(CTX(0, IMPLICIT(OriginatorInfo))),
recipientInfos: RecipientInfos,
encryptedContentInfo: EncryptedContentInfo,
unprotectedAttrs: OPTIONAL(CTX(1, IMPLICIT(UnprotectedAttributes)))
});
/**
* The digested-data content type consists of content of any type and a
* message digest of the content.<br><br>
* Typically, the digested-data content type is used to provide content
* integrity, and the result generally becomes an input to the
* enveloped-data content type.<br><br>
* <pre>
*
* DigestedData ::= SEQUENCE {
* version CMSVersion,
* digestAlgorithm DigestAlgorithmIdentifier,
* encapContentInfo EncapsulatedContentInfo,
* digest Digest }
*
* Digest ::= OCTET STRING
*
*</pre>
* @class GostASN1.DigestedData
* @extends GostASN1.Sequence
* @property {number} version The syntax version number
* @property {AlgorithmIdentifier} digestAlgorithm Message digest algorithm identifier
* @property {GostASN1.Sequence} encapContentInfo The content is represented in the type EncapsulatedContentInfo
* @property {CryptoOperationData} digest The degist
*/
var DigestedData = SEQUENCE({
version: CMSVersion,
digestAlgorithm: DigestAlgorithmIdentifier,
encapContentInfo: EncapsulatedContentInfo,
digest: Digest
});
/**
* The encrypted-data content type consists of encrypted content of any
* type. Unlike the enveloped-data content type, the encrypted-data
* content type has neither recipients nor encrypted content-encryption
* keys. Keys MUST be managed by other means.<br><br>
*
* The typical application of the encrypted-data content type will be to
* encrypt the content of the data content type for local storage,
* perhaps where the encryption key is derived from a password.<br><br>
* <pre>
*
* EncryptedData ::= SEQUENCE {
* version CMSVersion,
* encryptedContentInfo EncryptedContentInfo,
* unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
*
* EncryptedContentInfo ::= SEQUENCE {
* contentType ContentType,
* contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
* encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }
*
* EncryptedContent ::= OCTET STRING
*
* </pre>
* @class GostASN1.EncryptedData
* @extends GostASN1.Sequence
* @property {number} version The syntax version number
* @property {GostASN1.Sequence} encryptedContentInfo The content is represented in the type EncryptedContentInfo
* @property {Attributes} unprotectedAttrs The unprotected attributes
*/
var EncryptedData = SEQUENCE({
version: CMSVersion,
encryptedContentInfo: EncryptedContentInfo,
unprotectedAttrs: OPTIONAL(CTX(1, IMPLICIT(UnprotectedAttributes)))
});
/**
* The authenticated-data content type consists of content of any type,
* a message authentication code (MAC), and encrypted authentication
* keys for one or more recipients. The combination of the MAC and one
* encrypted authentication key for a recipient is necessary for that
* recipient to verify the integrity of the content. Any type of
* content can be integrity protected for an arbitrary number of
* recipients.<br><br>
* <pre>
*
* AuthenticatedData ::= SEQUENCE {
* version CMSVersion,
* originatorInfo [0] IMPLICIT OriginatorInfo OPTIONAL,
* recipientInfos RecipientInfos,
* macAlgorithm MessageAuthenticationCodeAlgorithm,
* digestAlgorithm [1] DigestAlgorithmIdentifier OPTIONAL,
* encapContentInfo EncapsulatedContentInfo,
* authAttrs [2] IMPLICIT AuthAttributes OPTIONAL,
* mac MessageAuthenticationCode,
* unauthAttrs [3] IMPLICIT UnauthAttributes OPTIONAL }
*
* AuthAttributes ::= SET SIZE (1..MAX) OF Attribute
*
* UnauthAttributes ::= SET SIZE (1..MAX) OF Attribute
*
* MessageAuthenticationCode ::= OCTET STRING
*
* </pre>
* @class GostASN1.AuthenticatedData
* @extends GostASN1.Sequence
* @property {number} version The syntax version number
* @property {GostASN1.Sequence} originatorInfo Optionally provides information about the originator.
* @property {GostASN1.Sequence[]} recipientInfos Collection of per-recipient information.
* @property {AlgorithmIdentifier} macAlgorithm Identifies the Message Authentication Code algorithm
* @property {AlgorithmIdentifier} digestAlgorithm Identifies the Digest algorithm
* @property {GostASN1.Sequence} encapContentInfo The content is represented in the type EncapsulatedContentInfo
* @property {Attributes} authAttrs The autheniticated attributes
* @property {CryptoOpertionData} mac The Message Authentication Code
* @property {Attributes} unauthAttrs The unautheniticated attributes
*/
var AuthenticatedData = SEQUENCE({
version: CMSVersion,
originatorInfo: OPTIONAL(CTX(0, IMPLICIT(OriginatorInfo))),
recipientInfos: RecipientInfos,
macAlgorithm: MessageAuthenticationCodeAlgorithm,
digestAlgorithm: OPTIONAL(CTX(1, DigestAlgorithmIdentifier)),
encapContentInfo: EncapsulatedContentInfo,
authAttrs: OPTIONAL(CTX(2, IMPLICIT(AuthAttributes))),
mac: MessageAuthenticationCode,
unauthAttrs: OPTIONAL(CTX(3, IMPLICIT(UnauthAttributes)))
}); // AuthEnvelopedData RFC 5911
var AuthEnvelopedData = SEQUENCE({
version: CMSVersion,
originatorInfo: OPTIONAL(CTX(0, IMPLICIT(OriginatorInfo))),
recipientInfos: RecipientInfos,
authEncryptedContentInfo: EncryptedContentInfo,
authAttrs: OPTIONAL(CTX(1, IMPLICIT(AuthAttributes))),
mac: MessageAuthenticationCode,
unauthAttrs: OPTIONAL(CTX(2, IMPLICIT(UnauthAttributes)))
}); // EncryptedKeyPackage rfc6032
var EncryptedKeyPackage = CHOICE({
encrypted: EncryptedData,
enveloped: CTX(0, IMPLICIT(EnvelopedData)),
authEnveloped: CTX(1, IMPLICIT(AuthEnvelopedData))
}, function (value) {
return value.encryptedContentInfo ? value.recipientInfos ? 'enveloped' : 'encrypted' : 'authEnveloped';
});
/**
* Cryptographic Message Syntax<br>
* The CMS associates a content type identifier with a content. The syntax
* MUST have ASN.1 type ContentInfo:
* <pre>
*
* ContentInfo ::= SEQUENCE {
* contentType ContentType,
* content [0] EXPLICIT ANY DEFINED BY contentType }
*
* ContentType ::= OBJECT IDENTIFIER
*
* </pre>
* The fields of ContentInfo have the following meanings:
* <ul>
* <li>contentType indicates the type of the associated content. It is
* an object identifier; it is a unique string of integers assigned
* by an authority that defines the content type.</li>
* <li>content is the associated content. The type of content can be
* determined uniquely by contentType. Content types for data,
* signed-data, enveloped-data, digested-data, encrypted-data, and
* authenticated-data are defined in this document. If additional
* content types are defined in other documents, the ASN.1 type
* defined SHOULD NOT be a CHOICE type.</li>
* </ul>
* RFC 5652 references {@link http://tools.ietf.org/html/rfc5652}
*
* @class GostASN1.ContentInfo
* @extends GostASN1.Sequence
* @property {string} contentType The content type identifier
* @property {(GostASN1.Sequence|CryptoOperationData)} content The content
*/
var ContentType = OBJECT_IDENTIFIER;
var ContentInfo = ATTRIBUTE({
contentType: ContentType,
content: function content(type) {
return CTX(0, EXPLICIT(type));
}
}, 'contentType', 'content', undefined, 'CMS')({
data: OCTET_STRING,
signedData: COMBINE(SignedData),
envelopedData: COMBINE(EnvelopedData),
digestedData: COMBINE(DigestedData),
encryptedData: COMBINE(EncryptedData),
authData: COMBINE(AuthenticatedData),
encryptedKeyPkg: COMBINE(EncryptedKeyPackage),
aKeyPackage: COMBINE(AsymmetricKeyPackage)
});
var DigestInfo = SEQUENCE({
digestAlgorithm: DigestAlgorithmIdentifier,
digest: Digest
}); // </editor-fold>
/*
* PFX format syntax PKCS#12
*
* http://tools.ietf.org/html/rfc7292
*
*/
// <editor-fold defaultstate="collapsed">
var PKCS12Attributes = Attributes({
friendlyName: SET_OF_SINGLE(BMPString),
keyProviderNameAttr: SET_OF_SINGLE(BMPString),
localKeyId: SET_OF_SINGLE(OCTET_STRING),
certKeyIdentifierPropId: SET_OF_SINGLE(OCTET_STRING)
});
var SafeBagType = OBJECT_IDENTIFIER;
var CertType = OBJECT_IDENTIFIER;
var CRLType = OBJECT_IDENTIFIER;
var SecretType = OBJECT_IDENTIFIER;
var KeyBag = PrivateKeyInfo;
var PKCS8ShroudedKeyBag = EncryptedPrivateKeyInfo;
var CertBag = ATTRIBUTE({
certId: CertType,
certValue: function certValue(type) {
return CTX(0, EXPLICIT(type));
}
}, 'certId', 'certValue')({
// DER-encoded X.509 certificate stored in OCTET STRING
x509Certificate: OCTET_STRING(ENCAPSULATES(Certificate)),
// Base64-encoded SDSI certificate stored in IA5String
sdsiCertificate: IA5String
}, OCTET_STRING);
var CRLBag = ATTRIBUTE({
crlId: CRLType,
crlValue: function crlValue(type) {
return CTX(0, EXPLICIT(type));
}
}, 'crlId', 'crlValue')({
// DER-encoded X.509 certificate stored in OCTET STRING
x509CRL: OCTET_STRING(ENCAPSULATES(CertificateList))
}, OCTET_STRING);
var SecretBag = ATTRIBUTE({
secretTypeId: SecretType,
secretValue: function secretValue(type) {
return CTX(0, EXPLICIT(type));
}
}, 'secretTypeId', 'secretValue')({
secret: OCTET_STRING
}, OCTET_STRING);
var SafeBag = ATTRIBUTE({
bagId: SafeBagType,
bagValue: function bagValue(type) {
return CTX(0, EXPLICIT(type));
},
bagAttributes: OPTIONAL(PKCS12Attributes)
}, 'bagId', 'bagValue')(function (type) {
return {
keyBag: KeyBag,
pkcs8ShroudedKeyBag: PKCS8ShroudedKeyBag,
certBag: CertBag,
crlBag: CRLBag,
secretBag: SecretBag,
safeContentsBag: SafeContents // recursion
}[type];
});
/**
* The SafeContents Type<br><br>
*
* The sixth type of bag that can be held in a SafeBag is a
* SafeContents. This recursive structure allows for arbitrary nesting
* of multiple KeyBags, PKCS8ShroudedKeyBags, CertBags, CRLBags, and
* SecretBags within the top-level SafeContents.
* <pre>
* SafeContents ::= SEQUENCE OF SafeBag
* SafeBag ::= SEQUENCE {
* bagId BAG-TYPE.&id ({PKCS12BagSet})
* bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),
* bagAttributes SET OF PKCS12Attribute OPTIONAL
* }
*
* PKCS12Attribute ::= SEQUENCE {
* attrId ATTRIBUTE.&id ({PKCS12AttrSet}),
* attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})
* } -- This type is compatible with the X.500 type ’Attribute’
*
* PKCS12AttrSet ATTRIBUTE ::= {
* friendlyName | -- from PKCS #9 [23]
* localKeyId, -- from PKCS #9
* ... -- Other attributes are allowed
* }
* </pre>
* The SafeContents type is made up of SafeBags. Each SafeBag holds one
* piece of information -- a key, a certificate, etc. -- which is
* identified by an object identifier.<br><br>
*
* See {@link GostASN1.ContentInfo} and {@link GostASN1.PFX}<br><br>
*
* RFC 7292 references {@link http://tools.ietf.org/html/rfc7292}
* @class GostASN1.SafeContents
*/
var SafeContents = SEQUENCE_OF(SafeBag);
/**
* The AuthenticatedSafe<br><br>
* Each compliant platform shall be able to import and export
* AuthenticatedSafe PDUs wrapped in PFX PDUs.<br>
* For integrity, the AuthenticatedSafe is either signed (if public-key
* integrity mode is used) or MACed (if password integrity mode is used)
* to produce a PFX PDU.
* <pre>
* AuthenticatedSafe ::= SEQUENCE OF ContentInfo
*
* -- Data if unencrypted
* -- EncryptedData if password-encrypted
* -- EnvelopedData if public key-encrypted
* </pre>
* As mentioned, the contentType field of authSafe shall be of type data
* or signedData. The content field of the authSafe shall, either
* directly (data case) or indirectly (signedData case), contain a BER-
* encoded value of type AuthenticatedSafe.<br><br>
*
* See {@link GostASN1.ContentInfo} and {@link GostASN1.PFX}<br><br>
*
* RFC 7292 references {@link http://tools.ietf.org/html/rfc7292}
*
* @class GostASN1.AuthenticatedSafe
*/
var AuthenticatedSafe = SEQUENCE_OF(ContentInfo);
var MacData = SEQUENCE({
mac: DigestInfo,
macSalt: OCTET_STRING,
// Note: The default is for historical reasons and its use is deprecated.
iterations: DEFAULT(INTEGER, 1)
});
/**
* PFX format syntax<br><br>
*
* This format corresponds to the data model presented above, with
* wrappers for privacy and integrity. This section makes free
* reference to PKCS #7 {@link GostASN1.ContentInfo}<br>
* All modes of direct exchange use the same PDU format. ASN.1 and BER-
* encoding ensure platform independence.<br>
* This standard has one ASN.1 export: PFX. This is the outer integrity
* wrapper.<br><br>
* Instances of PFX contain:
* <ol>
* <li>A version indicator. The version shall be v3 for this version of
* this document.</li>
* <li>A PKCS #7 ContentInfo, whose contentType is signedData in public-
* key integrity mode and data in password integrity mode.</li>
* <li>An optional instance of MacData, present only in password
* integrity. This object, if present, contains a PKCS #7
* DigestInfo, which holds the MAC value, a macSalt, and an
* iterationCount. As described in Appendix B, the MAC key is
* derived from the password, the macSalt, and the iterationCount;
* the MAC is computed from the authSafe value and the MAC key via HMAC.
* The password and the MAC key are not actually present anywhere in the PFX.
* The salt and (to a certain extent) the iteration count thwarts dictionary
* attacks against the integrity password. </li>
* </ol>
* <pre>
* PFX ::= SEQUENCE {
* version INTEGER {v3(3)}(v3,...),
* authSafe ContentInfo,
* macData MacData OPTIONAL
* }
*
* MacData ::= SEQUENCE {
* mac DigestInfo,
* macSalt OCTET STRING,
* iterations INTEGER DEFAULT 1
* -- Note: The default is for historical reasons and its
* -- use is deprecated.
* }
* </pre>
* See {@link GostASN1.ContentInfo}<br><br>
*
* RFC 7292 references {@link http://tools.ietf.org/html/rfc7292}
* @class GostASN1.PFX
* @extends GostASN1.Sequence
* @property {number} version Encoded version number
* @property {GostASN1.ContentInfo} authSafe ContentInfo with {@link GostASN1.AuthenticatedSafe} content
*/
var PFX = SEQUENCE({
version: INTEGER,
authSafe: ContentInfo,
macData: OPTIONAL(MacData)
}, 'PFX'); // </editor-fold>
/*
* Certificate Request Message Format
*
* http://tools.ietf.org/html/rfc4211
*
*/
// <editor-fold defaultstate="collapsed">
var RegToken = UTF8String;
var Authenticator = UTF8String;
var CertId = SEQUENCE({
issuer: GeneralName,
serialNumber: INTEGER
});
var OldCertId = CertId;
var ProtocolEncrKey = SubjectPublicKeyInfo;
var EncryptedValue = SEQUENCE({
// the intended algorithm for which the value will be used
intendedAlg: OPTIONAL(CTX(0, IMPLICIT(AlgorithmIdentifier))),
// the symmetric algorithm used to encrypt the value
symmAlg: OPTIONAL(CTX(1, IMPLICIT(AlgorithmIdentifier))),
// the (encrypted) symmetric key used to encrypt the value
encSymmKey: OPTIONAL(CTX(2, IMPLICIT(BIT_STRING))),
// algorithm used to encrypt the symmetric key
keyAlg: OPTIONAL(CTX(3, IMPLICIT(AlgorithmIdentifier))),
valueHint: OPTIONAL(CTX(4, IMPLICIT(OCTET_STRING))),
// a brief description or identifier of the encValue content
// (may be meaningful only to the sending entity, and used only
// if EncryptedValue might be re-examined by the sending entity
// in the future)
encValue: BIT_STRING
});
var KeyGenParameters = OCTET_STRING; // The encrypted private key MUST be placed in the envelopedData
// encryptedContentInfo encryptedContent OCTET STRING.
var EncryptedKey = CHOICE({
encryptedValue: EncryptedValue,
// Deprecated
envelopedData: CTX(0, IMPLICIT(EnvelopedData))
}, function (value) {
return value.encryptedContentInfo ? 'envelopedData' : 'encryptedValue';
});
var PKIArchiveOptions = CHOICE({
// the actual value of the private key
encryptedPrivKey: CTX(0, EncryptedKey),
// parameters that allow the private key to be re-generated
keyGenParameters: CTX(1, IMPLICIT(KeyGenParameters)),
// set to TRUE if sender wishes receiver to archive the private
// key of a key pair that the receiver generates in response to
// this request; set to FALSE if no archival is desired.
archiveRemGenPrivKey: CTX(2, IMPLICIT(BOOLEAN))
});
var SinglePubInfo = SEQUENCE({
pubMethod: INTEGER({
dontCare: 0,
x500: 1,
web: 2,
ldap: 3
}),
pubLocation: OPTIONAL(GeneralName)
}); // pubInfos MUST NOT be present if action is "dontPublish"
// (if action is "pleasePublish" and pubInfos is omitted,
// "dontCare" is assumed)
var PKIPublicationInfo = SEQUENCE({
action: INTEGER({
dontPublish: 0,
pleasePublish: 1
}),
pubInfos: OPTIONAL(SEQUENCE_OF(SinglePubInfo))
});
var SubsequentMessage = INTEGER({
// requests that resulting certificate be encrypted for the
// end entity (following which, POP will be proven in a
// confirmation message)
encrCert: 0,
// requests that CA engage in challenge-response exchange with
// end entity in order to prove private key possession
challengeResp: 1
});
var POPOPrivKey = CHOICE({
// possession is proven in this message (which contains the private
// key itself (encrypted for the CA))
thisMessage: CTX(0, IMPLICIT(BIT_STRING)),
// Deprecated
subsequentMessage: CTX(1, IMPLICIT(SubsequentMessage)),
// possession will be proven in a subsequent message
dhMAC: CTX(2, IMPLICIT(BIT_STRING)),
// Deprecated
agreeMAC: CTX(3, IMPLICIT(PKMACValue)),
encryptedKey: CTX(4, IMPLICIT(EnvelopedData))
});
var PBMParameter = SEQUENCE({
salt: OCTET_STRING,
// AlgId for a One-Way Function (SHA-1 recommended)
owf: AlgorithmIdentifier,
// number of times the OWF is applied
iterationCount: INTEGER,
// the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11], or HMAC [HMAC, RFC2202])
mac: AlgorithmIdentifier
});
var PKMACValue = SEQUENCE({
// algorithm value shall be PasswordBasedMac {1 2 840 113533 7 66 13}
// parameter value is PBMParameter
algId: AlgorithmIdentifier,
value: BIT_STRING
});
var POPOSigningKeyInput = SEQUENCE({
authInfo: CHOICE({
// used only if an authenticated identity has been
// established for the sender (e.g., a DN from a
// previously-issued and currently-valid certificate)
sender: CTX(0, EXPLICIT(GeneralName)),
// GeneralName choice - explicit
// used if no authenticated GeneralName currently exists for
// the sender; publicKeyMAC contains a password-based MAC
// on the DER-encoded value of publicKey
publicKeyMAC: PKMACValue
}),
publicKey: SubjectPublicKeyInfo
}); // from CertTemplate
var POPOSigningKey = SEQUENCE({
poposkInput: OPTIONAL(CTX(0, POPOSigningKeyInput)),
algorithmIdentifier: AlgorithmIdentifier,
signature: BIT_STRING
});
var ProofOfPossession = CHOICE({
// used if the RA has already verified that the requester is in
// possession of the private key
raVerified: CTX(0, IMPLICIT(NULL)),
signature: CTX(1, IMPLICIT(POPOSigningKey)),
keyEncipherment: CTX(2, IMPLICIT(POPOPrivKey)),
keyAgreement: CTX(3, IMPLICIT(POPOPrivKey))
});
var Controls = SEQUENCE_OF(AttributeTypeAndValue({
regToken: RegToken,
authenticator: Authenticator,
pkiPublicationInfo: PKIPublicationInfo,
pkiArchiveOptions: PKIArchiveOptions,
oldCertID: OldCertId,
protocolEncrKey: ProtocolEncrKey
}));
var OptionalValidity = SEQUENCE({
notBefore: OPTIONAL(CTX(0, IMPLICIT(Time))),
notAfter: OPTIONAL(CTX(1, IMPLICIT(Time)))
}); // at least one MUST be present
var CertTemplate = SEQUENCE({
version: OPTIONAL(CTX(0, IMPLICIT(Version))),
serialNumber: OPTIONAL(CTX(1, IMPLICIT(INTEGER))),
signingAlg: OPTIONAL(CTX(2, IMPLICIT(AlgorithmIdentifier))),
issuer: OPTIONAL(CTX(3, IMPLICIT(Name))),
validity: OPTIONAL(CTX(4, IMPLICIT(OptionalValidity))),
subject: OPTIONAL(CTX(5, IMPLICIT(Name))),
publicKey: OPTIONAL(CTX(6, IMPLICIT(SubjectPublicKeyInfo))),
issuerUID: OPTIONAL(CTX(7, IMPLICIT(UniqueIdentifier))),
subjectUID: OPTIONAL(CTX(8, IMPLICIT(UniqueIdentifier))),
extensions: OPTIONAL(CTX(9, IMPLICIT(Extensions)))
});
var CertRequest = SEQUENCE({
certReqId: INTEGER,
// ID for matching request and reply
certTemplate: CertTemplate,
// Selected fields of cert to be issued
controls: OPTIONAL(Controls)
}); // Attributes affecting issuance
var UTF8Pairs = UTF8String;
var CertReq = CertRequest;
var EncKeyWithID = SEQUENCE({
privateKey: PrivateKeyInfo,
identifier: OPTIONAL(CHOICE({
string: UTF8String,
generalName: GeneralName
}, function (value) {
return typeof value === 'string' || value instanceof String ? 'string' : 'generalName';
}))
});
var CertReqMsg = SEQUENCE({
certReq: CertRequest,
popo: OPTIONAL(ProofOfPossession),
// content depends upon key type
regInfo: OPTIONAL(SEQUENCE_OF(AttributeTypeAndValue({
utf8Pairs: UTF8Pairs,
certReq: CertReq,
encKeyWithID: EncKeyWithID
})))
});
var CertReqMessages = SEQUENCE_OF(CertReqMsg); // </editor-fold>
/*
* Certificate Management over CMS
*
* http://tools.ietf.org/html/rfc5272
*
*/
// <editor-fold defaultstate="collapsed">
var PendInfo = SEQUENCE({
pendToken: OCTET_STRING,
pendTime: GeneralizedTime
});
var CMCStatus = INTEGER({
success: 0,
failed: 2,
pending: 3,
noSupport: 4,
confirmRequired: 5,
popRequired: 6,
partial: 7
});
var CMCFailInfo = INTEGER({
badAlg: 0,
badMessageCheck: 1,
badRequest: 2,
badTime: 3,
badCertId: 4,
unsupportedExt: 5,
mustArchiveKeys: 6,
badIdentity: 7,
popRequired: 8,
popFailed: 9,
noKeyReuse: 10,
internalCAError: 11,
tryLater: 12,
authDataFail: 13
});
var CMCStatusInfo = SEQUENCE({
cMCStatus: CMCStatus,
bodyList: SEQUENCE_OF(BodyPartID),
statusString: OPTIONAL(UTF8String),
otherInfo: OPTIONAL(CHOICE({
failInfo: CMCFailInfo,
pendInfo: PendInfo
}))
});
var AddExtensions = SEQUENCE({
pkiDataReference: BodyPartID,
certReferences: SEQUENCE_OF(BodyPartID),
extensions: SEQUENCE_OF(Extension)
});
var LraPopWitness = SEQUENCE({
pkiDataBodyid: BodyPartID,
bodyIds: SEQUENCE_OF(BodyPartID)
});
var GetCert = SEQUENCE({
issuerName: GeneralName,
serialNumber: INTEGER
});
var GetCRL = SEQUENCE({
issuerName: Name,
cRLName: OPTIONAL(GeneralName),
time: OPTIONAL(GeneralizedTime),
reasons: OPTIONAL(ReasonFlags)
});
var RevokeRequest = SEQUENCE({
issuerName: Name,
serialNumber: INTEGER,
reason: CRLReason,
invalidityDate: OPTIONAL(GeneralizedTime),
passphrase: OPTIONAL(OCTET_STRING),
comment: OPTIONAL(UTF8String)
});
var DecryptedPOP = SEQUENCE({
bodyPartID: BodyPartID,
thePOPAlgID: AlgorithmIdentifier,
thePOP: OCTET_STRING
});
var CMCCertId = IssuerAndSerialNumber;
var BodyPartReference = CHOICE({
bodyPartID: BodyPartID,
bodyPartPath: BodyPartPath
});
var CMCStatusInfoV2 = SEQUENCE({
cMCStatus: CMCStatus,
bodyList: SEQUENCE_OF(BodyPartReference),
statusString: OPTIONAL(UTF8String),
otherInfo: OPTIONAL(CHOICE({
failInfo: CMCFailInfo,
pendInfo: PendInfo,
extendedFailInfo: SEQUENCE({
failInfoOID: OBJECT_IDENTIFIER,
failInfoValue: AttributeValue
})
}))
});
var PublishTrustAnchors = SEQUENCE({
seqNumber: INTEGER,
hashAlgorithm: AlgorithmIdentifier,
anchorHashes: SEQUENCE_OF(OCTET_STRING)
});
var AuthPublish = BodyPartID;
var BodyPartList = SEQUENCE_OF(BodyPartID);
var CMCPublicationInfo = SEQUENCE({
hashAlg: AlgorithmIdentifier,
certHashes: SEQUENCE_OF(OCTET_STRING),
pubInfo: PKIPublicationInfo
});
var ModCertTemplate = SEQUENCE({
pkiDataReference: BodyPartPath,
certReferences: BodyPartList,
replace: DEFAULT(BOOLEAN, true),
certTemplate: CertTemplate
});
var ControlsProcessed = SEQUENCE({
bodyList: SEQUENCE_OF(BodyPartReference)
});
var IdentifyProofV2 = SEQUENCE({
proofAlgID: AlgorithmIdentifier,
macAlgId: AlgorithmIdentifier,
witness: OCTET_STRING
});
var PopLinkWitnessV2 = SEQUENCE({
keyGenAlgorithm: AlgorithmIdentifier,
macAlgorithm: AlgorithmIdentifier,
witness: OCTET_STRING
});
var TaggedCertificationRequest = SEQUENCE({
bodyPartID: BodyPartID,
certificationRequest: CertificationRequest
});
var TaggedContentInfo = SEQUENCE({
bodyPartID: BodyPartID,
contentInfo: ContentInfo
});
var OtherMsg = SEQUENCE({
bodyPartID: BodyPartID,
otherMsgType: OBJECT_IDENTIFIER,
otherMsgValue: ANY
}); //DEFINED BY otherMsgType
var TaggedRequest = CHOICE({
tcr: CTX(0, IMPLICIT(TaggedCertificationRequest)),
crm: CTX(1, IMPLICIT(CertReqMsg)),
orm: CTX(2, IMPLICIT(SEQUENCE({
bodyPartID: BodyPartID,
requestMessageType: OBJECT_IDENTIFIER,
requestMessageValue: ANY
})))
}); // DEFINED BY requestMessageType
var EncryptedPOP = SEQUENCE({
request: TaggedRequest,
cms: ContentInfo,
thePOPAlgID: AlgorithmIdentifier,
witnessAlgID: AlgorithmIdentifier,
witness: OCTET_STRING
});
var TaggedAttribute = ATTRIBUTE({
bodyPartID: BodyPartID,
attrType: OBJECT_IDENTIFIER,
attrValues: function attrValues(type) {
return SET_OF(type);
}
}, 'attrType', 'attrValues', AttributeValue)({
statusInfo: CMCStatusInfo,
identification: UTF8String,
identityProof: OCTET_STRING,
dataReturn: OCTET_STRING,
transactionId: INTEGER,
senderNonce: OCTET_STRING,
recipientNonce: OCTET_STRING,
addExtensions: AddExtensions,
encryptedPOP: EncryptedPOP,
decryptedPOP: DecryptedPOP,
lraPOPWitness: LraPopWitness,
getCert: GetCert,
getCRL: GetCRL,
revokeRequest: RevokeRequest,
regInfo: OCTET_STRING,
responseInfo: OCTET_STRING,
queryPending: OCTET_STRING,
popLinkRandom: OCTET_STRING,
popLinkWitness: OCTET_STRING,
confirmCertAcceptance: CMCCertId,
statusInfoV2: CMCStatusInfoV2,
trustedAnchors: PublishTrustAnchors,
authPublish: AuthPublish,
batchRequests: BodyPartList,
batchResponses: BodyPartList,
publishCert: CMCPublicationInfo,
modCertTemplate: ModCertTemplate,
controlProcessed: ControlsProcessed,
popLinkWitnessV2: PopLinkWitnessV2,
identityProofV2: IdentifyProofV2
});
/**
* PKIData Content Type<br><br>
*
* The PKIData content type is used for the Full PKI Request. A PKIData
* content type is identified by:
* <pre>
* id-cct-PKIData ::= {id-pkix id-cct(12) 2 }
* </pre>
* The ASN.1 structure corresponding to the PKIData content type is:
* <pre>
* PKIData ::= SEQUENCE {
* controlSequence SEQUENCE SIZE(0..MAX) OF TaggedAttribute,
* reqSequence SEQUENCE SIZE(0..MAX) OF TaggedRequest,
* cmsSequence SEQUENCE SIZE(0..MAX) OF TaggedContentInfo,
* otherMsgSequence SEQUENCE SIZE(0..MAX) OF OtherMsg
* }
* </pre>
* All certification requests encoded into a single PKIData SHOULD be
* for the same identity. RAs that batch process (see Section 6.17) are
* expected to place the PKI Requests received into the cmsSequence of a
* PKIData. <br><br>
* See {@link GostASN1.ContentInfo} and {@link GostASN1.PKIResponse}<br><br>
* RFC 5272 references {@link http://tools.ietf.org/html/rfc5272}
*
* @class GostASN1.PKIData
* @extends GostASN1.Sequence
* @property {GostASN1.Attributes[]} controlSequence
* @property {GostASN1.Sequence[]} reqSequence
* @property {GostASN1.ContentInfo[]} cmsSequence
* @property {GostASN1.Sequence[]} otherMsgSequence
*/
var PKIData = SEQUENCE({
controlSequence: SEQUENCE_OF(TaggedAttribute),
reqSequence: SEQUENCE_OF(TaggedRequest),
cmsSequence: SEQUENCE_OF(TaggedContentInfo),
otherMsgSequence: SEQUENCE_OF(OtherMsg)
}, 'PKI REQUEST');
/**
* PKIResponse Content Type<br><br>
*
* The PKIResponse content type is used for the Full PKI Response. The
* PKIResponse content type is identified by:
* <pre>
* id-cct-PKIResponse ::= {id-pkix id-cct(12) 3 }
* </pre>
* The ASN.1 structure corresponding to the PKIResponse content type is:
* <pre>
* PKIResponse ::= SEQUENCE {
* controlSequence SEQUENCE SIZE(0..MAX) OF TaggedAttribute,
* cmsSequence SEQUENCE SIZE(0..MAX) OF TaggedContentInfo,
* otherMsgSequence SEQUENCE SIZE(0..MAX) OF OtherMsg
* }
*
* ReponseBody ::= PKIResponse
* </pre>
*
* Note: In [RFC2797], this ASN.1 type was named ResponseBody. It has
* been renamed to PKIResponse for clarity and the old name kept as a
* synonym.<br><br>
*
* See {@link GostASN1.ContentInfo} and {@link GostASN1.PKIData}<br><br>
*
* RFC 5272 references {@link http://tools.ietf.org/html/rfc5272}
*
* @class GostASN1.PKIResponse
* @extends GostASN1.Sequence
* @property {GostASN1.Attributes[]} controlSequence
* @property {GostASN1.ContentInfo[]} cmsSequence
* @property {GostASN1.Sequence[]} otherMsgSequence
*/
var PKIResponse = SEQUENCE({
controlSequence: SEQUENCE_OF(TaggedAttribute),
cmsSequence: SEQUENCE_OF(TaggedContentInfo),
otherMsgSequence: SEQUENCE_OF(OtherMsg)
}, 'PKI RESPONSE'); // </editor-fold>
/**
* ASN.1 syntax definitions
*
* @class GostASN1
*/
function GostASN1() {}
GostASN1.prototype = {
/**
* Gost PrivateKey info encoder
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostPrivateKeyInfo
*/
GostPrivateKeyInfo: GostPrivateKeyInfo,
/**
* Gost subject PublicKey info encoder
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostSubjectPublicKeyInfo
*/
GostSubjectPublicKeyInfo: GostSubjectPublicKeyInfo,
/**
* CryptoPro key container header
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostKeyContainer
*/
GostKeyContainer: GostKeyContainer,
/**
* CryptoPro key container name
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostKeyContainerName
*/
GostKeyContainerName: GostKeyContainerName,
/**
* CryptoPro encrypted PrivateKey for key containers
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostPrivateKeys
*/
GostPrivateKeys: GostPrivateKeys,
/**
* CryptoPro PrivateKey masks for key containers
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostPrivateMasks
*/
GostPrivateMasks: GostPrivateMasks,
/**
* ViPNet key container
*
* @memberOf GostASN1
* @instance
* @type GostASN1.ViPNetInfo
*/
ViPNetInfo: ViPNetInfo,
/**
* Gost Signature encoders
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostSignature
*/
GostSignature: GostSignature,
/**
* Gost Encrypted key encoder for CMS
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostEncryptedKey
*/
GostEncryptedKey: GostEncryptedKey,
/**
* SignalCom wrapped PrivateKey
*
* @memberOf GostASN1
* @instance
* @type GostASN1.GostWrappedPrivateKey
*/
GostWrappedPrivateKey: GostWrappedPrivateKey,
/**
* PKCS#8 PrivateKey info
*
* @memberOf GostASN1
* @instance
* @type GostASN1.PrivateKeyInfo
*/
PrivateKeyInfo: PrivateKeyInfo,
/**
* PKCS#8 encrypted PrivateKey info
*
* @memberOf GostASN1
* @instance
* @type GostASN1.EncryptedPrivateKeyInfo
*/
EncryptedPrivateKeyInfo: EncryptedPrivateKeyInfo,
/**
* X.509 subject PublicKey info
*
* @memberOf GostASN1
* @instance
* @type GostASN1.SubjectPublicKeyInfo
*/
SubjectPublicKeyInfo: SubjectPublicKeyInfo,
/**
* X.509 To be signed Certificate
*
* @memberOf GostASN1
* @instance
* @type GostASN1.TBSCertificate
*/
TBSCertificate: TBSCertificate,
/**
* X.509 Certificate
*
* @memberOf GostASN1
* @instance
* @type GostASN1.Certificate
*/
Certificate: Certificate,
/**
* PKCS#10 Certification request definition
*
* @memberOf GostASN1
* @instance
* @type GostASN1.CertificationRequestInfo
*/
CertificationRequestInfo: CertificationRequestInfo,
/**
* PKCS#10 Certification request
*
* @memberOf GostASN1
* @instance
* @type GostASN1.CertificationRequest
*/
CertificationRequest: CertificationRequest,
/**
* X.509 To be signed CRL
*
* @memberOf GostASN1
* @instance
* @type GostASN1.TBSCertList
*/
TBSCertList: TBSCertList,
/**
* X.509 CRL
*
* @memberOf GostASN1
* @instance
* @type GostASN1.CertificateList
*/
CertificateList: CertificateList,
/**
* X.509 Attribute Certificate definition
*
* @memberOf GostASN1
* @instance
* @type GostASN1.AttributeCertificateInfo
*/
AttributeCertificateInfo: AttributeCertificateInfo,
/**
* X.509 Attribute Certificate
*
* @memberOf GostASN1
* @instance
* @type GostASN1.AttributeCertificate
*/
AttributeCertificate: AttributeCertificate,
/**
* CMS Signed Attributes
*
* @memberOf GostASN1
* @instance
* @type GostASN1.SignedAttributes
*/
SignedAttributes: SignedAttributes,
/**
* CMS Unsigned Attributes
*
* @memberOf GostASN1
* @instance
* @type GostASN1.UnsignedAttributes
*/
UnsignedAttributes: UnsignedAttributes,
/**
* CMS Content definition
*
* @memberOf GostASN1
* @instance
* @type GostASN1.ContentInfo
*/
ContentInfo: ContentInfo,
/**
* PKCS#12 Safe Contents
*
* @memberOf GostASN1
* @instance
* @type GostASN1.SafeContents
*/
SafeContents: SafeContents,
/**
* PKCS#12 Authenticated Safe
*
* @memberOf GostASN1
* @instance
* @type GostASN1.AuthenticatedSafe
*/
AuthenticatedSafe: AuthenticatedSafe,
/**
* PKCS#12 Personal Information Exchange (PFX)
*
* @memberOf GostASN1
* @instance
* @type GostASN1.PFX
*/
PFX: PFX,
/**
* PKI Request
*
* @memberOf GostASN1
* @instance
* @type GostASN1.PKIData
*/
PKIData: PKIData,
/**
* PKI Response
*
* @memberOf GostASN1
* @instance
* @type GostASN1.PKIResponse
*/
PKIResponse: PKIResponse
};
/**
* PKCS ASN.1 message syntax and converters
*
* @memberOf gostCrypto
* @type GostASN1
*/
gostCrypto.asn1 = new GostASN1();
return GostASN1;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostCoding":109,"./gostCrypto":110,"./gostSecurity":115}],106:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file Implements the Cryptographic Message Syntax as specified in RFC-2630.
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostCrypto', 'gostASN1', 'gostCert'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostCrypto'), require('./gostASN1'), require('./gostCert'));
} else {
root.GostCMS = factory(root.gostCrypto, root.GostASN1, root.GostCert);
} // </editor-fold>
})(void 0, function (gostCrypto) {
/*
* Common algorithms
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var Promise = root.Promise;
var Object = root.Object;
var CryptoOperationData = root.ArrayBuffer;
var Date = root.Date;
var subtle = gostCrypto.subtle;
var asn1 = gostCrypto.asn1;
var coding = gostCrypto.coding;
var cert = gostCrypto.cert;
var providers = gostCrypto.security.providers; // Expand javascript object
function expand() {
var r = {};
for (var i = 0, n = arguments.length; i < n; i++) {
var item = arguments[i];
if (_typeof(item) === 'object') for (var name in item) {
if (item.hasOwnProperty(name)) r[name] = item[name];
}
}
return r;
}
function defineProperty(object, name, descriptor, enumerable) {
if (_typeof(descriptor) !== 'object') descriptor = {
value: descriptor
};
if (enumerable !== undefined) descriptor.enumerable = enumerable;
Object.defineProperty(object, name, descriptor);
}
function defineProperties(object, properties, enumerable) {
for (var name in properties) {
defineProperty(object, name, properties[name], enumerable);
}
} // Extend javascript class
function extend(Super, Class, propertiesObject, propertiesClass) {
// If constructor not defined
if (typeof Class !== 'function') {
propertiesClass = propertiesObject;
propertiesObject = Class;
Class = function Class() {
Super.apply(this, arguments);
};
} // Create prototype properties
Class.prototype = Object.create(Super.prototype, {
constructor: {
value: Class
},
superclass: {
value: Super.prototype
}
});
if (propertiesObject) defineProperties(Class.prototype, propertiesObject, true); // Inherites super class properties
if (Super !== Object) for (var name in Super) {
Class[name] = Super[name];
}
Class["super"] = Super;
if (propertiesClass) defineProperties(Class, propertiesClass, true);
return Class;
} // Self resolver
function call(callback) {
try {
callback();
} catch (e) {}
} // Check the buffers to equal
function equalBuffers(r1, r2) {
var s1 = new Uint8Array(r1),
s2 = new Uint8Array(r2);
if (s1.length !== s2.length) return false;
for (var i = 0, n = s1.length; i < n; i++) {
if (s1[i] !== s2[i]) return false;
}
return true;
} // True if equal numbers
var equalNumbers = function () {
// Convert number to bigendian hex string
var hex = function hex(s) {
var t = _typeof(s);
return t === 'undefined' || s === '' ? '0' : t === 'number' || s instanceof Number ? s.toString(16).toLowerCase() : s.replace('0x', '').toLowerCase();
}; // Zero left padding
var lpad = function lpad(s, size) {
return (new Array(size + 1).join('0') + s).slice(-size);
};
return function (s1, s2) {
s1 = hex(s1);
s2 = hex(s2);
var len = Math.max(s1.length, s2.length);
return lpad(s1, len) === lpad(s2, len);
};
}(); // Check equal names
function equalNames(name1, name2) {
for (var key in name1) {
if (name1[key] !== name2[key]) return false;
}
for (var key in name2) {
if (name1[key] !== name2[key]) return false;
}
return true;
} // Add unique value to array
function addUnique(array, item, comparator) {
var found = false;
for (var i = 0, n = array.length; i < n; i++) {
if (comparator(array[i], item)) {
found = true;
break;
}
}
if (!found) array.push(item);
} // Set content data
function setContentData(object, data) {
var content = object.content;
switch (object.contentType) {
case 'data':
object.content = data.content;
break;
case 'digestedData':
case 'signedData':
case 'authData':
content.encapContentInfo = {
eContentType: data.contentType,
eContent: data.content
};
break;
case 'envelopedData':
case 'encryptedData':
content.encryptedContentInfo = {
contentType: data.contentType,
encryptedContent: data.content
};
break;
}
} // Get content data
function getContentData(object) {
var content = object.content;
switch (object.contentType) {
case 'data':
return {
contentType: object.contentType,
content: object.content
};
case 'digestedData':
case 'signedData':
case 'authData':
var encap = content.encapContentInfo;
return {
contentType: encap.eContentType,
content: encap.eContent
};
case 'envelopedData':
case 'encryptedData':
var enc = content.encryptedContentInfo;
return {
contentType: enc.contentType,
content: enc.encryptedContent
};
}
} // Check content info type
function checkContentInfo(contentInfo) {
var content, contentType;
if (contentInfo) {
if (typeof contentInfo === 'string') try {
contentInfo = coding.PEM.decode(contentInfo);
} catch (e1) {
contentInfo = coding.Chars.decode(contentInfo);
}
if (contentInfo instanceof CryptoOperationData) try {
contentInfo = asn1.ContentInfo.decode(contentInfo);
} catch (e) {
contentInfo = {
contentType: 'data',
content: contentInfo
};
}
contentType = contentInfo.contentType;
if (!contentType) throw new Error('Invalid content object');
content = contentInfo.content;
if (!(content instanceof CryptoOperationData)) content = content.encode();
return {
contentType: contentType,
content: content
};
} else contentInfo = {
contentType: 'data'
};
return contentInfo;
}
function createContentInfo(contentInfo) {
try {
// Some provider has mistake to envelop ContentInfo enstead
// content field of ContentInfo
contentInfo = new asn1.ContentInfo(contentInfo.content, true);
} catch (e) {} // Create situable content info object
switch (contentInfo.contentType) {
case 'data':
return new DataContentInfo(contentInfo);
case 'digestedData':
return new DigestedDataContentInfo(contentInfo);
case 'signedData':
return new SignedDataContentInfo(contentInfo);
case 'encryptedData':
return new EncryptedDataContentInfo(contentInfo);
case 'envelopedData':
return new EnvelopedDataContentInfo(contentInfo);
default:
return new asn1.ContentInfo(contentInfo);
}
}
;
function matchCert(id, cert) {
return id instanceof CryptoOperationData ? cert.extensions && equalBuffers(id, cert.extensions.subjectKeyIdentifier) : equalNames(cert.issuer, id.issuer) && equalNumbers(cert.serialNumber, id.serialNumber);
} // Get random values
function getSeed(length) {
var seed = new Uint8Array(length);
gostCrypto.getRandomValues(seed);
return seed.buffer;
} // Salt size
function saltSize(algorithm) {
switch (algorithm.id) {
case 'pbeWithSHAAnd40BitRC2-CBC':
case 'pbeWithSHAAnd128BitRC2-CBC':
return 8;
case 'pbeUnknownGost':
return 16;
case 'sha1':
return 20;
default:
return 32;
}
} // Password to bytes
function passwordData(derivation, password) {
if (!password) return new CryptoOperationData(0);
if (password instanceof CryptoOperationData) return password;
if (typeof password !== 'string') throw new Error('The password must be string or raw data type');
if (derivation.name.indexOf('CPKDF') >= 0) {
// CryptoPro store password
var r = [];
for (var i = 0; i < password.length; i++) {
var c = password.charCodeAt(i);
r.push(c & 0xff);
r.push(c >>> 8 & 0xff);
r.push(0);
r.push(0);
}
return new Uint8Array(r).buffer;
} else if (derivation.name.indexOf('PFXKDF') >= 0) // PKCS#12 unicode password
return coding.Chars.decode(password + '\0', 'unicode');else // PKCS#5 password mode
return coding.Chars.decode(password, 'utf8');
} // Define provider for encription algorithm
function encryptionProvider(algorithm) {
var id = algorithm.id;
for (var name in providers) {
var provider = providers[name];
if (provider.encryption.id === id) return provider;
}
} // </editor-fold>
/**
* Provides facilities for handling certificates, CRLs, etc.
* @class GostCMS
*/
function GostCMS() {}
/**
* Message templates
* <ul>
* <li>providerName - provider name for key generation, default 'CP-01'</li>
* <li>autoAddCert - automatic add signer certificate to signature, default false</li>
* <li>useKeyIdentifier - true to add Signer as the SignerIdentifier (v3), otherwise, as the IssuerAndSerialNumber (v1) (default false).</li>
* </ul>
*
* @memberOf GostCMS
* @instance
*/
var options = {
// <editor-fold defaultstate="collapsed">
providerName: 'CP-01',
autoAddCert: false,
useKeyIdentifier: false // </editor-fold>
};
GostCMS.prototype.options = options;
/**
* The base class for all CMS objects.<br><br>
*
* A CMS object consists of a content type, and content.<br><br>
*
* @class GostCMS.DataContentInfo
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The content object.
* @param {string} defaultSet The default object initialization set.
* @extends GostASN1.ContentInfo
*/
function DataContentInfo(contentInfo, defaultSet) // <editor-fold defaultstate="collapsed">
{
asn1.ContentInfo.call(this, contentInfo || defaultSet || {
contentType: 'data'
});
if (defaultSet && this.contentType !== (defaultSet.contentType || 'data')) throw new Error('Invalid content type');
} // </editor-fold>
extend(asn1.ContentInfo, DataContentInfo, {
/**
* Indicates if this is a detached CMS object.
*
* @memberOf GostCMS.DataContentInfo
* @instance
* @returns {boolean} true if detached; false otherwise.
*/
isDetached: {
// <editor-fold defaultstate="collapsed">
value: false,
enumerable: true,
writable: true // </editor-fold>
},
/**
* Indicates if an external (detached) signature must be created.
*
* @memberOf GostCMS.DataContentInfo
* @instance
* @param {boolean} createDetached True if detached; false otherwise.
*/
writeDetached: function writeDetached(createDetached) // <editor-fold defaultstate="collapsed">
{
// Define external signature mode
this.isDetached = createDetached;
},
// </editor-fold>
/**
* Encode the message to binary format 'DER' or 'PEM'
*
* @memberOf GostCMS.DataContentInfo
* @instance
* @param {string} format
* @returns {FormatedData}
*/
// <editor-fold defaultstate="collapsed">
encode: function encode(format) // <editor-fold defaultstate="collapsed">
{
if (this.isDetached) {
var data = getContentData(this);
setContentData(this, {
contentType: data.contentType
});
var result = asn1.ContentInfo.method('encode').call(this, format);
setContentData(this, data);
return result;
} else return asn1.ContentInfo.method('encode').call(this, format);
},
// </editor-fold>
/**
* Enclose content to document.
*
* @memberOf GostCMS.DataContentInfo
* @instance
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo
* @returns {Promise} Promise to return self object after enclose content
*/
encloseContent: function encloseContent(contentInfo) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
self.setEnclosed(contentInfo);
return self;
});
},
// </editor-fold>
/**
* Sets the content of attached document.<br><br>
*
* This is necessary only in detached mode.
*
* @memberOf GostCMS.DataContentInfo
* @instance
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo - The encapsulated CMS Object.
*/
setEnclosed: function setEnclosed(contentInfo) // <editor-fold defaultstate="collapsed">
{
setContentData(this, checkContentInfo(contentInfo));
},
// </editor-fold>
/**
* Returns the document which attached. If the content is not attached, the CMS object
* which is returned will be degenerate.
*
* @memberOf GostCMS.DataContentInfo
* @instance
* @returns {GostASN1.ContentInfo} The encapsulated CMS Object.
*/
getEnclosed: function getEnclosed() // <editor-fold defaultstate="collapsed">
{
return createContentInfo(getContentData(this));
} // </editor-fold>
});
/**
* This class encapsulates a CMS object of content type binary data.
*
* @memberOf GostCMS
* @type GostCMS.DigestedDataContentInfo
*/
GostCMS.prototype.DataContentInfo = DataContentInfo;
/**
* This class encapsulates a CMS object of content type digested-data.
*
* @class GostCMS.DigestedDataContentInfo
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo - The content that is to be signed.
* @extends GostCMS.DataContentInfo
* @extends GostASN1.DigestedData
*/
function DigestedDataContentInfo(contentInfo) // <editor-fold defaultstate="collapsed">
{
DataContentInfo.call(this, contentInfo, {
contentType: 'digestedData',
version: 0,
digestAlgorithm: providers[options.providerName].digest,
encapContentInfo: {
eContentType: 'data'
},
digest: new CryptoOperationData(0)
});
} // </editor-fold>
extend(DataContentInfo, DigestedDataContentInfo, {
/**
* Enclose the content and calculate the message digest with given digest algorithm
*
* @memberOf GostCMS.DigestedDataContentInfo
* @instance
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo Content data to be enclosed.
* @param {(AlgorithmIdentifier|string)} digestAlgorithm Digest algorithm or provider name
* @returns {Promise}
*/
encloseContent: function encloseContent(contentInfo, digestAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
// Set enclosed data
self.setEnclosed(contentInfo); // Define digest algorithm
if (digestAlgorithm) {
var digestProvider = providers[digestAlgorithm];
self.digestAlgorithm = digestProvider && digestProvider.digest || digestAlgorithm;
} // Calculate digest
return subtle.digest(self.digestAlgorithm, self.encapContentInfo.eContent);
}).then(function (digest) {
// Set digest attribute
self.digest = digest;
});
},
// </editor-fold>
/**
* Verify the Message Digest. <br><br>
*
* @memberOf GostCMS.DigestedDataContentInfo
* @instance
* @param contentInfo Detached content (optional)
* @returns {Promise} Promise to return enclosed object {@link GostASN1.ContentInfo} if digest verified
*/
verify: function verify(contentInfo) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
// Append attached
if (contentInfo) self.setEnclosed(contentInfo); // Check data
var dataToVerify = self.encapContentInfo && self.encapContentInfo.eContent;
if (!dataToVerify) throw new Error('Detached content is not found'); // Calculate digest
return subtle.digest(self.digestAlgorithm, self.encapContentInfo.eContent);
}).then(function (digest) {
if (!equalBuffers(digest, self.digest)) throw Error('Message digest is not verified'); // Return content
return createContentInfo({
contentType: self.encapContentInfo.eContentType,
content: self.encapContentInfo.eContent
});
});
} // </editor-fold>
});
/**
* This class encapsulates a CMS object of content type digested-data.
*
* @memberOf GostCMS
* @type GostCMS.DigestedDataContentInfo
*/
GostCMS.prototype.DigestedDataContentInfo = DigestedDataContentInfo;
/**
* This class encapsulates a CMS object of content type signed-data.
*
* Use encloseContent or setEnclosed methods to add a enclosed content before add signatures
*
* @class GostCMS.SignedDataContentInfo
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo - The signed content.
* @extends GostCMS.DataContentInfo
* @extends GostASN1.SignedData
*/
function SignedDataContentInfo(contentInfo) // <editor-fold defaultstate="collapsed">
{
DataContentInfo.call(this, contentInfo, {
contentType: 'signedData',
version: 1,
digestAlgorithms: [],
encapContentInfo: {
eContentType: 'data'
},
signerInfos: []
});
} // </editor-fold>
extend(DataContentInfo, SignedDataContentInfo, {
/**
* Add a Signer using the the IssuerAndSerialNumber as the SignerIdentifier i.e a Version1 CMSSignerInfo
* or SubjectPublicKeyIdentifier as the SignerIdentifier i.e a Version3 CMSSignerInfo.
*
* @memberOf GostCMS.SignedDataContentInfo
* @instance
* @param {GostASN1.PrivateKeyInfo} signerKey Private Key of the signer.
* @param {GostCert.X509} signerCert Signer certificate or certificate chain
* @param {GostASN1.SignedAttributes} signedAttrs The set of signed attributes. Default undefined. If true or {} standard attributes will be appended: contentType and messageDigest
* @param {GostASN1.UnsignedAttributes} unsignedAttrs The set of unsigned attributes. Default undefined.
* @returns {Promise} Promise to return self object after add signature
*/
addSignature: function addSignature(signerKey, signerCert, signedAttrs, unsignedAttrs) // <editor-fold defaultstate="collapsed">
{
var self = this,
signerInfo,
dataToSign,
signerCertChain;
return new Promise(call).then(function () {
// Check attribures
if (!signerKey || !signerCert) throw new Error('Signer key or certificate is not defined'); // Cert chain
if (signerCert instanceof Array) {
signerCertChain = signerCert;
signerCert = signerCertChain[0];
} else signerCertChain = [signerCert]; // Signature algorithm provider
var provider = signerCert.getProvider() || providers[options.providerName];
var useKeyIdentifier = options.useKeyIdentifier && signerCert.extensions && signerCert.extensions.subjectKeyIdentifier; // Get enclosed data
dataToSign = self.encapContentInfo.eContent; // Prepare signer info structure
signerInfo = {
version: useKeyIdentifier ? 2 : 0,
sid: useKeyIdentifier ? signerCert.extensions.subjectKeyIdentifier : {
issuer: signerCert.issuer,
serialNumber: signerCert.serialNumber
},
digestAlgorithm: provider.digest,
signatureAlgorithm: signerCert.subjectPublicKeyInfo.algorithm
}; // Set an unsigned attributes
if (unsignedAttrs) signerInfo.unsignedAttrs = unsignedAttrs; // For a signed attributes calculate digest
if (signedAttrs) {
if (_typeof(signedAttrs) !== 'object') signedAttrs = {};
return subtle.digest(signerInfo.digestAlgorithm, dataToSign);
}
}).then(function (digest) {
if (digest) {
// Add standard signed attributes
signedAttrs.contentType = self.encapContentInfo.eContentType, signedAttrs.messageDigest = digest, signedAttrs.signingTime = new Date();
signerInfo.signedAttrs = signedAttrs, // Now data to sign = attributes
dataToSign = asn1.SignedAttributes.encode(signerInfo.signedAttrs);
} // Import the private key
return subtle.importKey('pkcs8', asn1.PrivateKeyInfo.encode(signerKey), signerKey.privateKeyAlgorithm, false, ['sign']);
}).then(function (key) {
// Sign data
var algorithm = expand(signerInfo.signatureAlgorithm, {
hash: signerInfo.digestAlgorithm
});
return subtle.sign(algorithm, key, dataToSign);
}).then(function (signatureValue) {
signerInfo.signatureValue = signatureValue; // Add digest algorithm
addUnique(self.digestAlgorithms, signerInfo.digestAlgorithm, function (algorithm1, algorithm2) {
return algorithm1.id === algorithm2.id;
}); // Add signer certificate
if (options.autoAddCert) {
if (!self.certificates) self.certificates = [];
for (var i = 0, n = signerCertChain.length; i < n; i++) {
addUnique(self.certificates, signerCertChain[i], function (cert1, cert2) {
return equalNames(cert1.issuer, cert2.issuer) && equalNumbers(cert1.serialNumber, cert2.serialNumber);
});
}
} // Add signer info
self.signerInfos.push(signerInfo);
});
},
// </editor-fold>
/**
* Indicates if this object has any signers i.e. checks for the absence of any SignerInfo structures.
* CMS (RFC-2630) defines a degenerate object as one which has no signers.
*
* @memberOf GostCMS.SignedDataContentInfo
* @instance
* @returns {boolean} True if this object has no signers; false otherwise.
*/
isDegenerate: {
// <editor-fold defaultstate="collapsed">
get: function get() {
return !(this.signerInfos && this.signerInfos.length > 0);
} // </editor-fold>
},
/**
* Returns normally if this CMS signed data object contains at least one valid signature,
* according to the given trust policy; otherwise throws an Error.<br><br>
*
* In order to be considered valid, there must be at least one signature on this CMS
* message which is validated by one of the certificates included with it; furthermore,
* the validating certificate must itself be valid according to the given certificate
* trust policy. This latter validation process may involve examining the other certificates
* or CRLs included with this object, if called for by the trust policy.<br><br>
*
* If a signature is encountered for which a certification path can be found, but is
* invalid, an Error will be created, but will not be thrown until
* all other signatures have been checked. If another signature is found which is valid,
* then the method simply returns and no exception at all is thrown.
*
* @memberOf GostCMS.SignedDataContentInfo
* @instance
* @param {GostCert.CertificateTrustPolicy} trustPolicy The trust prolicy for verification
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The content that was signed (optional)
* @returns {Promise} Promise to return enclosed object {@link GostASN1.ContentInfo} if signature verified
*/
verify: function verify(trustPolicy, contentInfo) // <editor-fold defaultstate="collapsed">
{
var self = this,
result;
return new Promise(call).then(function () {
// Append attached
if (contentInfo) self.setEnclosed(contentInfo);
if (!self.signerInfos || self.signerInfos.length === 0) throw new Error('No signatures found'); // Validate certificate of signers
return Promise.all(self.signerInfos.map(function (signerInfo, i) {
var sid = signerInfo.sid,
selector = sid instanceof CryptoOperationData ? {
subjectKeyIdentifier: sid
} : {
issuer: sid.issuer,
serialNumber: sid.serialNumber
}; // Signing date
var date;
if (signerInfo.signedAttrs && signerInfo.signedAttrs.signingTime) date = signerInfo.signedAttrs.signingTime; // Use certificate trust policy validation
return trustPolicy.getValidCertificate(selector, self.certificates, self.crls, date)["catch"](function () {
return; // Ignore error
});
}));
}).then(function (certs) {
// Get encapsulated data
var verifiers = []; // Verify signatures for each signers
certs.forEach(function (signerCert) {
if (signerCert) verifiers.push(self.verifySignature(signerCert).then(function (data) {
result = data; // Enough one valid signature
}, function () {
return; // Ignore error
}));
});
if (verifiers.length === 0) throw new Error('Valid verification path not found');
return Promise.all(verifiers);
}).then(function () {
if (!result) throw Error('Verification path found but no valid signature'); // Return content
return result;
});
},
// </editor-fold>
/**
* Returns successfully if this CMS signed data object contains a signature which is
* validated by the given certificate and data; otherwise throws an Error.<br><br>
*
* This method verifies the specified signature directly and ignores any certificates
* or CRLs which may be contained in this CMS object. A more complex verification process,
* which does make use of attached certificates and CRLs, is provided by the verify method.
*
* @memberOf GostCMS.SignedDataContentInfo
* @instance
* @param {GostCert.X509} signerCert The signer certificate
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The content that was signed (optional)
* @returns {Promise} Promise to return enclosed object {@link GostASN1.ContentInfo} if signature verified
*/
verifySignature: function verifySignature(signerCert, contentInfo) // <editor-fold defaultstate="collapsed">
{
var self = this,
signerInfo,
dataToVerify,
dataDigest;
return new Promise(call).then(function () {
// Append attached
if (contentInfo) self.setEnclosed(contentInfo);
dataToVerify = self.encapContentInfo && self.encapContentInfo.eContent;
if (!dataToVerify) throw new Error('Detached content is not found'); // Find signer
for (var i = 0; i < self.signerInfos.length; i++) {
var sid = self.signerInfos[i].sid;
if (matchCert(sid, signerCert)) {
signerInfo = self.signerInfos[i];
break;
}
}
if (!signerInfo) throw new Error('Signature not found for the certificate'); // Choice data for verification
if (signerInfo.signedAttrs) {
dataDigest = signerInfo.signedAttrs.messageDigest;
if (!dataDigest) throw new Error('Message digest must present in signed attributes'); // To exclude implicit [0] need to reassemble signed attributes (auto on CTX object)
dataToVerify = signerInfo.signedAttrs.encode();
}
if (!dataToVerify) throw new Error('Data for verification not found'); // Verify signature
var algorithm = expand(signerInfo.signatureAlgorithm, {
hash: signerInfo.digestAlgorithm
});
return signerCert.verifySignature(dataToVerify, signerInfo.signatureValue, algorithm);
}).then(function (result) {
if (!result) throw new Error('Signature not verified'); // Verify digest
if (signerInfo.signedAttrs) return subtle.digest(signerInfo.digestAlgorithm, self.encapContentInfo.eContent);
}).then(function (digest) {
if (digest && !equalBuffers(digest, dataDigest)) throw new Error('Message digest not verified'); // Return content
return createContentInfo({
contentType: self.encapContentInfo.eContentType,
content: self.encapContentInfo.eContent
});
});
} // </editor-fold>
});
/**
* This class encapsulates a CMS object of content type signed-data.
*
* @memberOf GostCMS
* @type GostCMS.SignedDataContentInfo
*/
GostCMS.prototype.SignedDataContentInfo = SignedDataContentInfo;
/**
* This class encapsulates a CMS object of content type encrypted-data.
*
* @class GostCMS.EncryptedDataContentInfo
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The encrypted data content.
* @extends GostCMS.DataContentInfo
* @extends GostASN1.EncryptedData
*/
function EncryptedDataContentInfo(contentInfo) // <editor-fold defaultstate="collapsed">
{
DataContentInfo.call(this, contentInfo, {
contentType: 'encryptedData',
version: 0,
encryptedContentInfo: {
contentType: 'data',
contentEncryptionAlgorithm: providers[options.providerName].encryption
}
});
} // </editor-fold>
extend(DataContentInfo, EncryptedDataContentInfo, {
/**
* Encrypt the content with given encryption algorithm, secret key or password
*
* @memberOf GostCMS.EncryptedDataContentInfo
* @instance
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The content data to be enclosed.
* @param {Key|string} contentEncryptionKey content The encryption key or password for derive key
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return self object after encrypt content
*/
encloseContent: function encloseContent(contentInfo, contentEncryptionKey, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this,
encryption,
derivation;
return new Promise(call).then(function () {
// Check content info
contentInfo = checkContentInfo(contentInfo);
if (!contentInfo.content) throw new Error('Content for encryption must be specified'); // Define encryption algorithm
var type = typeof contentEncryptionKey === 'string' ? 'pbes' : 'encryption';
if (encryptionAlgorithm) {
var provider = providers[encryptionAlgorithm];
encryptionAlgorithm = provider && provider[type] || encryptionAlgorithm;
} else encryptionAlgorithm = providers[options.providerName][type]; // Prepare content encryption key
if (encryptionAlgorithm.derivation) {
// Encrypt with password
derivation = expand(encryptionAlgorithm.derivation);
encryption = expand(encryptionAlgorithm.encryption);
derivation.salt = getSeed(saltSize(encryptionAlgorithm)); // Import password for key generation
var integrityKey;
return subtle.importKey('raw', passwordData(derivation, contentEncryptionKey), derivation, false, ['deriveKey', 'deriveBits']).then(function (key) {
integrityKey = key; // Derive IV
if (derivation.name.indexOf('PFXKDF') >= 0) {
derivation.diversifier = 2;
return subtle.deriveBits(derivation, integrityKey, 64);
}
}).then(function (iv) {
if (iv) encryption.iv = iv; // Generate key from password
derivation.diversifier = 1;
return subtle.deriveKey(derivation, integrityKey, encryption, false, ['encrypt']);
}).then(function (encryptionKey) {
// Content encryption with key
return encryptionKey;
});
} else {
// Base encryption
encryption = expand(encryptionAlgorithm);
if (contentEncryptionKey instanceof CryptoOperationData) {
// Import key
return subtle.importKey('raw', contentEncryptionKey, encryption, false, ['encrypt']);
} else if (contentEncryptionKey.type === 'secret') {
return contentEncryptionKey;
} else throw new Error('Content encryption key must be raw data or secret key type');
}
}).then(function (encryptionKey) {
// Initial vector
if (!encryption.iv) encryption.iv = getSeed(8);
return subtle.encrypt(encryption, encryptionKey, contentInfo.content);
}).then(function (encryptedContent) {
if (encryptionAlgorithm.derivation) {
delete derivation.diversifier;
encryptionAlgorithm = expand(encryptionAlgorithm, {
derivation: derivation,
encryption: encryption
});
} else encryptionAlgorithm = encryption; // Set enclosed data
self.encryptedContentInfo = {
contentType: contentInfo.contentType,
contentEncryptionAlgorithm: encryptionAlgorithm,
encryptedContent: encryptedContent
};
return self;
});
},
// </editor-fold>
/**
* Returns the decrypted content.
*
* @memberOf GostCMS.EncryptedDataContentInfo
* @instance
* @param {Key|string} decryptionKey The decryption key or password for derive key
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The detached content (optional).
* @returns {Promise} Promise to return enclosed object {@ling GostASN1.ContentInfo} after decrypt content
*/
getEnclosed: function getEnclosed(decryptionKey, contentInfo) // <editor-fold defaultstate="collapsed">
{
var self = this,
encryption,
derivation,
encryptedContent;
return new Promise(call).then(function () {
// Append attached
if (contentInfo) self.setEnclosed(contentInfo);
encryptedContent = self.encryptedContentInfo.encryptedContent;
if (!encryptedContent) throw new Error('Encrypted content must be specified');
encryption = expand(self.encryptedContentInfo.contentEncryptionAlgorithm);
if (encryption.derivation) {
// Decrypt with password
derivation = expand(encryption.derivation);
encryption = expand(encryption.encryption); // Derive encryption key from password
var integrityKey;
return subtle.importKey('raw', passwordData(derivation, decryptionKey), derivation, false, ['deriveKey', 'deriveBits']).then(function (key) {
integrityKey = key; // Derive iv for PFX
if (derivation.name.indexOf('PFXKDF') >= 0) {
derivation.diversifier = 2;
return subtle.deriveBits(derivation, integrityKey, 64);
}
}).then(function (iv) {
if (iv) encryption.iv = iv; // Generate key from password
derivation.diversifier = 1;
return subtle.deriveKey(derivation, integrityKey, encryption, false, ['decrypt']);
});
} else {
// Base encryption. Password should be secret key
if (decryptionKey instanceof CryptoOperationData) {
// Import key
return subtle.importKey('raw', decryptionKey, encryption, false, ['decrypt']);
} else if (decryptionKey.type === 'secret') {
return decryptionKey;
} else throw new Error('Decryption key must be raw data or secret key type');
}
}).then(function (encryptionKey) {
// Decrypt key with encryption key
return subtle.decrypt(encryption, encryptionKey, encryptedContent);
}).then(function (decryptedContent) {
// Create content info object
return createContentInfo({
contentType: self.encryptedContentInfo.contentType,
content: decryptedContent
});
});
} // </editor-fold>
});
/**
* This class encapsulates a CMS object of content type encrypted-data.
*
* @memberOf GostCMS
* @type GostCMS.EncryptedDataContentInfo
*/
GostCMS.prototype.EncryptedDataContentInfo = EncryptedDataContentInfo;
/**
* This class encapsulates a CMS object of content type enveloped-data.
*
* @class GostCMS.EnvelopedDataContentInfo
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The encrypted data content.
* @extends GostCMS.DataContentInfo
* @extends GostASN1.EnvelopedData
*/
function EnvelopedDataContentInfo(contentInfo) // <editor-fold defaultstate="collapsed">
{
DataContentInfo.call(this, contentInfo, {
contentType: 'envelopedData',
version: 0,
recipientInfos: [],
encryptedContentInfo: {
contentType: 'data',
contentEncryptionAlgorithm: providers[options.providerName].encryption
}
});
} // </editor-fold>
extend(DataContentInfo, EnvelopedDataContentInfo, {
/**
* Generate content encryption key with given encryption algorithm and encrypt the content
*
* @memberOf GostCMS.EnvelopedDataContentInfo
* @instance
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The content data to be enclosed.
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return self object after encrypt content
*/
encloseContent: function encloseContent(contentInfo, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
// Check content info
contentInfo = checkContentInfo(contentInfo);
if (!contentInfo.content) throw new Error('Content for encryption must be specified'); // Define encryption algorithm
if (encryptionAlgorithm) {
var provider = providers[encryptionAlgorithm];
encryptionAlgorithm = provider && provider.encryption || encryptionAlgorithm;
} else encryptionAlgorithm = providers[options.providerName].encryption; // Generate key for encryption content
return subtle.generateKey(encryptionAlgorithm, true, ['encrypt']);
}).then(function (encryptionKey) {
// Encrypt content
self.contentEncryptionKey = encryptionKey; // Initial vector
if (!encryptionAlgorithm.iv) encryptionAlgorithm.iv = getSeed(8);
return subtle.encrypt(encryptionAlgorithm, encryptionKey, contentInfo.content);
}).then(function (encryptedContent) {
self.encryptedContentInfo = {
contentType: contentInfo.contentType,
contentEncryptionAlgorithm: encryptionAlgorithm,
encryptedContent: encryptedContent
};
return self;
});
},
// </editor-fold>
/**
* Add a recipient. <br><br>
*
* Uses the Recipient Information with IssuerAndSerialNumber as the Recipient Identifier.
* Note: If senderCert specified uses the Key Agreement algorithm overwise Key Transport algorithm.
*
* @memberOf GostCMS.EnvelopedDataContentInfo
* @instance
* @param {GostCert.X509} recipientCert The certificate of recepient
* @param {(AlgorithmIdentifier|string)} keyEncryptionAlgorithm Key encryption algorithm or provider name
* @param {GostASN1.PrivateKeyInfo} senderKey The private key of sender for key agreement protocol
* @param {GostCert.X509} senderCert The certificate of sender for key agreement protocol
* @returns {Promise} Promise to return self object after add recipient
*/
addRecipient: function addRecipient(recipientCert, keyEncryptionAlgorithm, senderKey, senderCert) // <editor-fold defaultstate="collapsed">
{
var self = this,
privateKey,
encryptionProvider,
derivation,
wrapping;
return new Promise(call).then(function () {
// Check for recepient cert
recipientCert = new cert.X509(recipientCert);
if (keyEncryptionAlgorithm && typeof keyEncryptionAlgorithm !== 'string' && !keyEncryptionAlgorithm.algorithm) {
// Sender parameters
senderCert = senderKey;
senderKey = keyEncryptionAlgorithm;
keyEncryptionAlgorithm = undefined;
}
if (keyEncryptionAlgorithm) {
encryptionProvider = providers[keyEncryptionAlgorithm];
} else encryptionProvider = recipientCert.getProvider(); // Check for content encryption key
if (!self.contentEncryptionKey) throw new Error('The content encryption key is not assigned');
if (senderCert) {
// Sender certificate for agreement protocol
var senderCertChain;
if (senderCert instanceof Array) {
senderCertChain = senderCert;
senderCert = senderCertChain[0];
} else senderCertChain = [senderCert]; // Add sender certificate
if (options.autoAddCert) {
if (!self.originatorInfo) self.originatorInfo = {
certs: []
};else if (!self.originatorInfo.certs) self.originatorInfo.certs = [];
for (var i = 0, n = senderCertChain.length; i < n; i++) {
addUnique(self.originatorInfo.certs, senderCertChain[i], function (cert1, cert2) {
return equalNames(cert1.issuer, cert2.issuer) && equalNumbers(cert1.serialNumber, cert2.serialNumber);
});
}
} // Key Agreement
if (encryptionProvider) keyEncryptionAlgorithm = expand(encryptionProvider.agreement);else encryptionProvider = recipientCert.getProvider(); // Certificates must have similar curve parameters
if (recipientCert.subjectPublicKeyInfo.algorithm.namedCurve !== senderCert.subjectPublicKeyInfo.algorithm.namedCurve) throw new Error('The sender and the recipient have different public key algorithms'); // Get private sender key
return subtle.importKey('pkcs8', senderKey.encode(), senderKey.privateKeyAlgorithm, false, ['deriveKey']);
} else {
// Key Transport
if (encryptionProvider) keyEncryptionAlgorithm = expand(recipientCert.subjectPublicKeyInfo.algorithm);else encryptionProvider = recipientCert.getProvider(); // Generate key pair
return subtle.generateKey(keyEncryptionAlgorithm, true, ['deriveKey']).then(function (keyPair) {
keyEncryptionAlgorithm['public'] = keyPair.publicKey;
return keyPair.privateKey;
});
}
}).then(function (key) {
privateKey = key; // Get public key from recipient certificate
return subtle.importKey('spki', recipientCert.subjectPublicKeyInfo.encode(), recipientCert.subjectPublicKeyInfo.algorithm, false, ['deriveKey', 'deriveBits']);
}).then(function (publicKey) {
// Derivate key encryption key
keyEncryptionAlgorithm.ukm = getSeed(8);
derivation = expand(encryptionProvider.agreement, {
sBox: keyEncryptionAlgorithm.sBox,
ukm: keyEncryptionAlgorithm.ukm,
'public': publicKey
});
wrapping = expand(keyEncryptionAlgorithm.wrapping || encryptionProvider.wrapping, {
ukm: keyEncryptionAlgorithm.ukm
});
return subtle.deriveKey(derivation, privateKey, wrapping, true, ['wrapKey']);
}).then(function (wrappingKey) {
// Wrap content encryption key
keyEncryptionAlgorithm.wrapping = wrapping;
return subtle.wrapKey('raw', self.contentEncryptionKey, wrappingKey, wrapping);
}).then(function (wrappedKey) {
// Create recipient info
var recipientInfo;
var useKeyIdentifier = options.useKeyIdentifier && recipientCert.extensions && recipientCert.extensions.subjectKeyIdentifier,
rid = useKeyIdentifier ? recipientCert.extensions.subjectKeyIdentifier : {
issuer: recipientCert.issuer,
serialNumber: recipientCert.serialNumber
};
if (senderCert) {
var spki = senderCert.subjectPublicKeyInfo;
recipientInfo = {
// KeyAgreeRecipientInfo
version: 3,
// always set to 3
originator: {
algorithm: spki.algorithm,
publicKey: spki.subjectPublicKey
},
ukm: keyEncryptionAlgorithm.ukm,
keyEncryptionAlgorithm: keyEncryptionAlgorithm,
recipientEncryptedKeys: [{
// use only one recipient in domain
rid: rid,
encryptedKey: asn1.GostEncryptedKey(keyEncryptionAlgorithm).encode(wrappedKey)
}]
};
} else {
recipientInfo = {
version: 0,
// always set to 0 or 2
rid: rid,
keyEncryptionAlgorithm: keyEncryptionAlgorithm,
encryptedKey: asn1.GostEncryptedKey(keyEncryptionAlgorithm).encode({
algorithm: keyEncryptionAlgorithm,
sessionEncryptedKey: wrappedKey
})
};
}
self.recipientInfos.push(recipientInfo);
return self;
});
},
// </editor-fold>
/**
* Returns the decrypted content.
*
* @memberOf GostCMS.EnvelopedDataContentInfo
* @instance
* @param {GostASN1.PrivateKeyInfo} recipientKey The decryption key or password for derive key
* @param {GostCert.X509} recipientCert The decryption key or password for derive key
* @param {(FormatedData|GostASN1.ContentInfo)} contentInfo The detached content (optional).
* @param {GostCert.X509} originatorCert The originator certificate (optional).
* @returns {Promise} Promise to return enclosed object {@ling GostASN1.ContentInfo} after decrypt content
*/
getEnclosed: function getEnclosed(recipientKey, recipientCert, contentInfo, originatorCert) // <editor-fold defaultstate="collapsed">
{
var self = this,
wrappedKey,
encryptedContent,
derivation,
wrapping,
encryption;
return new Promise(call).then(function () {
var encryptionProvider = recipientCert.getProvider(); // Append attached
if (contentInfo) self.setEnclosed(contentInfo);
encryptedContent = self.encryptedContentInfo.encryptedContent;
if (!encryptedContent) throw new Error('Encrypted content must be specified');
encryption = self.encryptedContentInfo.contentEncryptionAlgorithm; // Find receiver
for (var i = 0; i < self.recipientInfos.length; i++) {
var recipientInfo = self.recipientInfos[i],
algorithm = expand(recipientInfo.keyEncryptionAlgorithm);
if (recipientInfo.rid) {
if (matchCert(recipientInfo.rid, recipientCert)) {
// Algorithm and wrapped key
var transportKey = asn1.GostEncryptedKey(algorithm).decode(recipientInfo.encryptedKey).object;
wrappedKey = transportKey.sessionEncryptedKey;
algorithm = expand(algorithm, transportKey.algorithm);
derivation = expand(encryptionProvider.agreement, {
ukm: algorithm.ukm,
sBox: algorithm.sBox
});
wrapping = expand(encryptionProvider.wrapping, algorithm.wrapping, {
ukm: algorithm.ukm
});
return algorithm['public'];
}
} else {
var keys = recipientInfo.recipientEncryptedKeys;
if (keys) {
for (var j = 0; j < keys.length; j++) {
if (matchCert(keys[j].rid, recipientCert)) {
// Algorithm and wrapped key
algorithm = expand(encryptionProvider.agreement, algorithm, {
ukm: recipientInfo.ukm
});
wrappedKey = asn1.GostEncryptedKey(algorithm).decode(keys[j].encryptedKey).object;
derivation = algorithm;
wrapping = expand(algorithm.wrapping || encryptionProvider.wrapping, {
ukm: recipientInfo.ukm
}); // Check originator
var originator = recipientInfo.originator;
if (originator.algorithm) {
var spki = new asn1.SubjectPublicKeyInfo({
algorithm: originator.algorithm,
subjectPublicKey: originator.publicKey
});
return subtle.importKey('spki', spki.encode(), spki.algorithm, false, ['deriveKey', 'deriveBits']);
} else if (originatorCert && matchCert(originator, originatorCert)) return importKey('pkcs', originatorCert.subjectPublicKeyInfo.encode(), originatorCert.subjectPublicKeyInfo.algorithm, false, ['deriveKey', 'deriveBits']);else throw Error('Originator certificate not specified or not valid');
}
}
}
}
}
throw new Error('Recipient not found or format not supported');
}).then(function (publicKey) {
derivation['public'] = publicKey; // Import private key
return subtle.importKey('pkcs8', recipientKey.encode(), recipientKey.privateKeyAlgorithm, false, ['deriveKey', 'deriveBits']);
}).then(function (privateKey) {
// Derive key
return subtle.deriveKey(derivation, privateKey, wrapping, true, ['unwrapKey']);
}).then(function (unwrappingKey) {
// Unwrap key
return subtle.unwrapKey('raw', wrappedKey, unwrappingKey, wrapping, encryption, false, ['decrypt']);
}).then(function (encryptionKey) {
// Decrypt content
return subtle.decrypt(encryption, encryptionKey, encryptedContent);
}).then(function (decryptedContent) {
return createContentInfo({
contentType: self.encryptedContentInfo.contentType,
content: decryptedContent
});
});
} // </editor-fold>
});
/**
* This class encapsulates a CMS object of content type enveloped-data.
*
* @memberOf GostCMS
* @type GostCMS.EnvelopedDataContentInfo
*/
GostCMS.prototype.EnvelopedDataContentInfo = EnvelopedDataContentInfo;
/**
* Implements the Cryptographic Message Syntax as specified in RFC-2630.
*
* @memberOf gostCrypto
* @type GostCMS
*/
gostCrypto.cms = new GostCMS();
return GostCMS;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostASN1":105,"./gostCert":107,"./gostCrypto":110}],107:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file Provides facilities for handling certificates, CRLs, etc.
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostCrypto', 'gostASN1'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostCrypto'), require('./gostASN1'));
} else {
root.GostCert = factory(root.gostCrypto, root.GostASN1);
} // </editor-fold>
})(void 0, function (gostCrypto) {
/*
* Common algorithms
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var Promise = root.Promise;
var Object = root.Object;
var CryptoOperationData = root.ArrayBuffer;
var Date = root.Date; // Crypto subtle
var subtle = gostCrypto.subtle; // Coding
var coding = gostCrypto.coding; // ASN.1 syntax
var asn1 = gostCrypto.asn1; // Providers
var providers = gostCrypto.security.providers; // Expand javascript object
function expand(r) {
for (var i = 1, n = arguments.length; i < n; i++) {
var item = arguments[i];
if (_typeof(item) === 'object') for (var name in item) {
if (item.hasOwnProperty(name)) r[name] = item[name];
}
}
return r;
} // Extend javascript class
function extend(Class) {
var F = function F() {};
F.prototype = Class.prototype;
var r = new F(),
args = [r];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
return expand.apply(this, args);
} // Today date + n days
function today(n) {
var date = new Date();
date.setHours(0, 0, 0, 0);
if (n) date.setDate(date.getDate() + n);
return date;
} // Self resolver
function call(callback) {
try {
callback();
} catch (e) {}
} // Serial number
function genSerialNumber() {
var seed = new Uint8Array(4);
gostCrypto.getRandomValues(seed);
seed[0] = seed[0] & 0x7f;
return coding.Int16.encode(seed);
} // True if equal numbers
var equalNumbers = function () {
// Convert number to bigendian hex string
var hex = function hex(s) {
var t = _typeof(s);
return t === 'undefined' || s === '' ? '0' : t === 'number' || s instanceof Number ? s.toString(16).toLowerCase() : s.replace('0x', '').toLowerCase();
}; // Zero left padding
var lpad = function lpad(s, size) {
return (new Array(size + 1).join('0') + s).slice(-size);
};
return function (s1, s2) {
s1 = hex(s1);
s2 = hex(s2);
var len = Math.max(s1.length, s2.length);
return lpad(s1, len) === lpad(s2, len);
};
}(); // Check equal names
function equalNames(name1, name2) {
for (var key in name1) {
if (name1[key] !== name2[key]) return false;
}
for (var key in name2) {
if (name1[key] !== name2[key]) return false;
}
return true;
} // Check the buffers to equal
function equalBuffers(r1, r2) {
var s1 = new Uint8Array(r1),
s2 = new Uint8Array(r2);
if (s1.length !== s2.length) return false;
for (var i = 0, n = s1.length; i < n; i++) {
if (s1[i] !== s2[i]) return false;
}
return true;
} // Match certificate
function matchCertificate(cert, selector) {
var skid = cert.extensions && cert.extensions.subjectKeyIdentifier;
return cert && selector && (!selector.issuer || equalNames(cert.issuer, selector.issuer)) && (!selector.serialNumber || equalNumbers(cert.serialNumber, selector.serialNumber)) && (!selector.subjectKeyIdentifier || equalBuffers(skid, selector.subjectKeyIdentifier)) && (!selector.subject || equalNames(cert.subject, selector.subject)) && (!selector.date || cert.notBefore.getTime() <= selector.date.getTime() && cert.notAfter.getTime() > selector.date.getTime());
} // Create authority certificate selector
function authoritySelector(cert, extensions, date) {
var selector = {
subject: cert.issuer,
date: date
},
akid = extensions && extensions.authorityKeyIdentifier;
if (akid) {
selector.subjectKeyIdentifier = akid.keyIdentifier;
if (akid.authorityCertIssuer && akid.authorityCertIssuer[0] && akid.authorityCertSerialNumber) {
selector.issuer = akid.authorityCertIssuer[0];
selector.serialNumber = akid.authorityCertSerialNumber;
}
}
return selector;
} // Find certificates
function selectCertificates(certs, selector) {
var result = [];
for (var i = 0, n = certs.length; i < n; i++) {
if (matchCertificate(certs[i], selector)) result.push(certs[i]);
}
return result;
} // Match CRL
function matchCRL(crl, selector) {
return (!selector.issuer || equalNames(crl.issuer, selector.issuer)) && (!selector.date || crl.thisUpdate.getTime() < selector.date.getTime());
} // Find certificates
function selectCRLs(crls, selector) {
var result = [];
for (var i = 0, n = crls.length; i < n; i++) {
if (matchCRL(crls[i], selector)) result.push(crls[i]);
}
return result;
} // Define provider for key algorithm
function keyProvider(algorithm) {
var id = algorithm.id;
for (var name in providers) {
var provider = providers[name];
if (provider.publicKey.id === id) return provider;
}
}
function defineProperty(object, name, descriptor, enumerable) {
if (_typeof(descriptor) !== 'object') descriptor = {
value: descriptor
};
if (enumerable !== undefined) descriptor.enumerable = enumerable;
Object.defineProperty(object, name, descriptor);
}
function defineProperties(object, properties, enumerable) {
for (var name in properties) {
defineProperty(object, name, properties[name], enumerable);
}
} // Extend javascript class
function extend(Super, Class, propertiesObject, propertiesClass) {
// If constructor not defined
if (typeof Class !== 'function') {
propertiesClass = propertiesObject;
propertiesObject = Class;
Class = function Class() {
Super.apply(this, arguments);
};
} // Create prototype properties
Class.prototype = Object.create(Super.prototype, {
constructor: {
value: Class
},
superclass: {
value: Super.prototype
}
});
if (propertiesObject) defineProperties(Class.prototype, propertiesObject, true); // Inherites super class properties
if (Super !== Object) for (var name in Super) {
Class[name] = Super[name];
}
Class["super"] = Super;
if (propertiesClass) defineProperties(Class, propertiesClass, true);
return Class;
} // </editor-fold>
/**
* Provides facilities for handling certificates, CRLs, etc.
*
* @class GostCert
*/
function GostCert() {}
/**
* Certificate templates
* <ul>
* <li>providerName - provider name for key generation, default 'CP-01'</li>
* <li>subject - template of subject name {countryName: 'RU', commonName: 'Anonymous'}</li>
* <li>caKeyUsage - default key usages for a CA certificates
* ['digitalSignature', 'nonRepudiation', 'keyEncipherment',
* 'dataEncipherment', 'keyAgreement', 'keyCertSign', 'cRLSign']</li>
* <li>caExtKeyUsage - default extended key usages for a CA certificates
* ['serverAuth', 'clientAuth', 'codeSigning', 'emailProtection', 'ipsecEndSystem',
* 'ipsecTunnel', 'ipsecUser', 'timeStamping', 'OCSPSigning']</li>
* <li>userKeyUsage - default key usages for a user certificate
* ['digitalSignature', 'nonRepudiation', 'keyEncipherment', 'dataEncipherment', 'keyAgreement'],
* <li>userExtKeyUsage - default extended key usages for user certificate
* ['clientAuth', 'emailProtection']</li>
* <li>days - validity of the certificate in days, default 7305</li>
* </ul>
*
* @memberOf GostCert
* @instance
*/
var options = {
// <editor-fold defaultstate="collapsed">
providerName: 'CP-01',
subject: {
countryName: 'RU',
commonName: 'Anonymous'
},
caKeyUsage: ['digitalSignature', 'nonRepudiation', 'keyEncipherment', 'dataEncipherment', 'keyAgreement', 'keyCertSign', 'cRLSign'],
caExtKeyUsage: ['serverAuth', 'clientAuth', 'codeSigning', 'emailProtection', 'ipsecEndSystem', 'ipsecTunnel', 'ipsecUser', 'timeStamping', 'OCSPSigning'],
userKeyUsage: ['digitalSignature', 'nonRepudiation', 'keyEncipherment', 'dataEncipherment', 'keyAgreement'],
userExtKeyUsage: ['clientAuth', 'emailProtection'],
days: 7305 // </editor-fold>
};
GostCert.prototype.options = options;
/**
* This class encapsulates X.509 Version 3 certificates.<br><br>
*
* Constructs an X.509 certificate from the given DER encoding or ASN.1 Certificate object.
*
* @class GostCert.X509
* @extends GostASN1.Certificate
* @param {(FormatedData|GostASN1.Certificate)} cert The certificate
*/
var X509 = function X509(cert) // <editor-fold defaultstate="collapsed">
{
try {
// Try to use decode X.509 certificate
asn1.Certificate.call(this, cert, true);
} catch (e) {
try {
// Try to decode certification request
cert = new asn1.CertificationRequest(cert, true);
} catch (e) {} // Create new certificate structure
cert = cert || {};
asn1.Certificate.call(this, {
version: 2,
serialNumber: cert.serialNumber || genSerialNumber(),
signature: cert.signature || {
id: 'noSignature'
},
issuer: cert.subject || options.subject,
notBefore: cert.notBefore || today(),
notAfter: cert.notAfter || today(cert.days || options.days),
subject: cert.subject || options.subject,
subjectPublicKeyInfo: cert.subjectPublicKeyInfo || {
algorithm: {
id: 'noSignature'
},
subjectPublicKey: new CryptoOperationData(0)
},
extensions: cert.attributes && (cert.attributes.extensionRequest || cert.attributes.msCertExtensions) || cert.extensions,
signatureAlgorithm: {
id: 'noSignature'
},
signatureValue: new CryptoOperationData(0)
});
}
}; // </editor-fold>
extend(asn1.Certificate, X509, {
/**
* Generate the contents of this certificate and sign it.<br><br>
*
* If issuerCertificate is not defined self signed certificate generated
*
* @memberOf GostCert.X509
* @instance
* @param {GostASN1.PrivateKeyInfo} issuerPrivateKey The issuer's private key
* @param {GostCert.X509} issuerCertificate The issuer's certificate or undefined for self-signed certificate
* @returns {Promise} Promise to return self object after sign the certificate
*/
sign: function sign(issuerPrivateKey, issuerCertificate) // <editor-fold defaultstate="collapsed">
{
var self = this,
spki = self.subjectPublicKeyInfo;
return new Promise(call).then(function () {
// Need generated key
if (!spki || !spki.algorithm || spki.algorithm === 'noSignature') throw new Error('Key pair was not generated for the certificate'); // Check issuer private key
if (!issuerPrivateKey) throw new Error('The private key of the issuer is not defined'); // Certificate can be self signed
issuerCertificate = issuerCertificate || self; // Calculate subject key indentifier
return subtle.digest('SHA-1', spki.subjectPublicKey);
}).then(function (digest) {
// Signature algorithm
var provider = issuerCertificate.getProvider() || providers[options.providerName];
if (!self.signature || self.signature.id === 'noSignature') self.signature = provider.signature;
self.signatureAlgorithm = self.signature; // Set issuer
self.issuer = issuerCertificate.subject; // Set default extensions
if (!self.extensions) self.extensions = {};
var exts = self.extensions,
ae = issuerCertificate.extensions;
if (self === issuerCertificate) {
// Self-signed CA certificate
// Set key usage
exts.keyUsage = exts.keyUsage || options.caKeyUsage;
exts.extKeyUsage = exts.extKeyUsage || options.caExtKeyUsage; // Set basic constraints
exts.basicConstraints = exts.basicConstraints || {
cA: true
};
} else {
// Check key usage and validity
if (!issuerCertificate.checkUsage('keyCertSign', self.notBefore)) throw new Error('The issuer\'s certificate is not valid for signing a certificate'); // Set key usage
exts.keyUsage = exts.keyUsage || options.userKeyUsage;
exts.extKeyUsage = exts.extKeyUsage || options.userExtKeyUsage; // Set basic constraints
exts.basicConstraints = exts.basicConstraints || {
cA: exts.keyUsage.indexOf('keyCertSign') >= 0
}; // Check path length constraint
if (exts.basicConstraints.cA) {
var pathLen = ae && ae.basicConstraints && ae.pathLenConstraint;
if (pathLen !== undefined) {
if (pathLen > 0) exts.basicConstraints.pathLenConstraint = pathLen - 1;else throw new Error('Path length constraint exceeded');
}
}
} // Subject key identifier 160 bit from public key hash
exts.subjectKeyIdentifier = digest; // Authority key identifier
if (ae && ae.subjectKeyIdentifier) exts.authorityKeyIdentifier = {
keyIdentifier: ae.subjectKeyIdentifier,
authorityCertIssuer: [issuerCertificate.issuer],
authorityCertSerialNumber: issuerCertificate.serialNumber
}; // Import the private key
return subtle.importKey('pkcs8', issuerPrivateKey.encode(), issuerPrivateKey.privateKeyAlgorithm, false, ['sign']);
}).then(function (key) {
// Sign certificate
return subtle.sign(self.signatureAlgorithm, key, self.tbsCertificate.encode());
}).then(function (signatureValue) {
// Siganture value
self.signatureValue = signatureValue;
return self;
});
},
// </editor-fold>
/**
* Generate key pair for certificate
*
* @memberOf GostCert.X509
* @instance
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The key algorithm or name of provider
* @returns {Promise} Promise to return {@link GostASN1.PrivateKeyInfo} after self-signed certificate generation
*/
generate: function generate(keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this,
privateKey,
provider;
if (keyAlgorithm) provider = providers[keyAlgorithm];else provider = this.getProvider() || providers[options.providerName];
if (provider) keyAlgorithm = expand(provider.publicKey, {
privateKey: provider.privateKey
});
return new Promise(call).then(function () {
// Generate key pair
return subtle.generateKey(keyAlgorithm, 'true', ['sign', 'verify']);
}).then(function (keyPair) {
privateKey = keyPair.privateKey; // Export public key
return subtle.exportKey('spki', keyPair.publicKey);
}).then(function (spki) {
self.subjectPublicKeyInfo = new asn1.SubjectPublicKeyInfo(spki);
return subtle.exportKey('pkcs8', privateKey);
}).then(function (pkcs8) {
return new asn1.PrivateKeyInfo(pkcs8);
});
},
// </editor-fold>
/**
* Gets the public key.
*
* @memberOf GostCert.X509
* @instance
* @returns {Promise} Promise to return {@link Key}
*/
getPublicKey: function getPublicKey() // <editor-fold defaultstate="collapsed">
{
var spki = this.subjectPublicKeyInfo,
keyUsages = spki.algorithm.id === 'rsaEncryption' ? ['verify'] : ['verify', 'deriveKey', 'deriveBits'];
return subtle.importKey('spki', spki.encode(), spki.algorithm, 'false', keyUsages);
},
// </editor-fold>
/**
* Get appropriate crypto provider for public key
*
* @memberOf GostCert.X509
* @instance
* @returns Object Set of crypto provider algorithms
*/
getProvider: function getProvider() // <editor-fold defaultstate="collapsed">
{
return keyProvider(this.subjectPublicKeyInfo.algorithm);
},
// </editor-fold>
/**
* Verifies this certificate.<br><br>
*
* More precisely:<br><br>
* <ul>
* <li>Verifies that the current VM date/time is within the validity period of the certificate.</li>
* <li>If an unrecognized critical extension is present, the certificate is rejected.</li>
* <li>If the issuer certificate has been set, verifies that the signing certificate is a
* CA certificate, and that the signature is correct. The signing certificate is considered
* to be a CA certificate unless one of the following two conditions hold: The signing
* certificate contains a basicConstraints extension, and the CA flag is false; or the
* signing certificate contains a keyUsage extension, the keyUsage extension is marked
* critical, and the keyCertSign bit is false.</li>
* <li>If the issuer CRL has been set, verifies that the certificate has not been revoked.</li>
* </ul>
*
* @memberOf GostCert.X509
* @instance
* @param {GostCert.X509} issuerCertificate The issuer X.509 certificate
* @param {GostCert.CRL} issuerCRL The issuer CRL
* @param {Date} date Validation date. Default current date
* @returns {Promise} Promise to return self object if the certificate is valid
*/
verify: function verify(issuerCertificate, issuerCRL, date) // <editor-fold defaultstate="collapsed">
{
var self = this,
exts = self.extensions;
return new Promise(call).then(function () {
// Current date
date = date || today();
if (self.notBefore.getTime() > date.getTime() || self.notAfter.getTime() <= date.getTime()) throw new Error('The certificate has not yet started or expired'); // A unrecognized critical extensions
for (var name in exts) {
var value = exts[name];
if (value.critical && ['authorityKeyIdentifier', 'subjectKeyIdentifier', 'keyUsage', 'certificatePolicies', 'policyMappings', 'basicConstraints', 'nameConstraints', 'policyConstraints', 'extKeyUsage'].indexOf(name) < 0) throw new Error('The critical extension \'' + name + '\' is unrecognized');
} // The certificate can be self-signed
var selector = authoritySelector(self, exts, self.notBefore);
if (!issuerCertificate && matchCertificate(self, selector)) issuerCertificate = self; // Check issuer
if (issuerCertificate) {
if (!matchCertificate(issuerCertificate, selector) || !issuerCertificate.checkUsage('keyCertSign', self.notBefore)) throw new Error('The issuer\'s certificate is not valid'); // Check certificate signature
return issuerCertificate.verifySignature(self.tbsCertificate.encode(), self.signatureValue, self.signatureAlgorithm);
}
return true;
}).then(function (result) {
if (!result) throw new Error('The certificate has invalid signature'); // Check CRL
if (issuerCRL) {
if (!matchCRL(issuerCRL, {
issuer: self.issuer,
date: date
})) throw new Error('The issuer\'s CRL is not valid');
if (issuerCRL.isRevoked(self.serialNumber)) throw new Error('The certificate is revoked');
}
return self;
});
},
// </editor-fold>
/**
* Verify a signature made with this certificate's public key.
*
* @memberOf GostCert.X509
* @instance
* @param {CryptoOperationData} data The signed document.
* @param {CryptoOperationData} signature The signature
* @param {AlgorithmIdentifier} algorithm The algorithm ID used for the signature.
* @returns {Promise} Promise to return true if the signature is verified, and false otherwise
*/
verifySignature: function verifySignature(data, signature, algorithm) // <editor-fold defaultstate="collapsed">
{
return this.getPublicKey().then(function (publicKey) {
return subtle.verify(algorithm, publicKey, signature, data);
});
},
// </editor-fold>
/**
* Check key usage and date validation
*
* @memberOf GostCert.X509
* @instance
* @param {DOMString} operation The operation
* @param {Date} date Operation date. Default current date
* @returns {boolean}
*/
checkUsage: function checkUsage(operation, date) // <editor-fold defaultstate="collapsed">
{
var self = this,
exts = self.extensions;
date = date || today();
return self.notBefore.getTime() <= date.getTime() && self.notAfter.getTime() > date.getTime() && (!exts || !(['keyCertSign', 'cRLSign'].indexOf(operation) > 0 && exts.basicConstraints && !exts.basicConstraints.cA || exts.keyUsage && exts.keyUsage.indexOf(operation) < 0 && exts.extKeyUsage && exts.extKeyUsage.indexOf(operation) < 0));
} // </editor-fold>
});
/**
* This class encapsulates X.509 Version 3 certificates.
*
* @memberOf GostCert
* @type GostCert.X509
*/
GostCert.prototype.X509 = X509;
/**
* This class encapsulates a X.509 certificate revocation list (CRL) of RevokedCertificate objects.<br><br>
*
* Note: the methods and constructors that input a CRL do not automatically verify it.
* You need to explicitly call the verify method.
*
* @class GostCert.CRL
* @extends GostASN1.CertificateList
* @param {(FormatedData|GostASN1.CertificateList)} crl
*/
var CRL = function CRL(crl) // <editor-fold defaultstate="collapsed">
{
// Call super
CRL["super"].call(this, crl); // Initialize defaults
if (!this.version) this.version = 1;
if (!this.revokedCertificates) this.revokedCertificates = [];
if (!this.thisUpdate) this.thisUpdate = today();
}; // </editor-fold>
extend(asn1.CertificateList, CRL, {
/**
* Signs this CRL. The issuer's private key has to be set. The default random number generator is used, if needed.<br><br>
*
* Note: Making any modifications to the contents of the CRL after signing invalidates the signature.
* The sign method must be invoked again after any modifications for a valid signature to be computed.
*
* @memberOf GostCert.CRL
* @instance
* @param {GostASN1.PrivateKeyInfo} issuerPrivateKey the issuer's private signing key
* @param {GostCert.X509} issuerCertificate the issuer's certificate
* @returns {Promise} Promise to return self object after sign the CRL
*/
sign: function sign(issuerPrivateKey, issuerCertificate) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
// Check issuer private key
if (!issuerPrivateKey) throw new Error('The issuer\'s private key is not defined'); // Check issuer certificate
if (!issuerCertificate) throw new Error('The issuer\'s certificate is not defined'); // Check issuer name
if (!self.issuer) self.issuer = issuerCertificate.issuer;else if (!equalNames(self.issuer, issuerCertificate.issuer)) throw new Error('The CRL prototype and authority certificate have different issuers'); // Check key usage and validity
if (!issuerCertificate.checkUsage('cRLSign', self.thisUpdate)) throw new Error('The issuer\'s certificate is not valid for signing a CRL'); // Signature algorithm
var provider = issuerCertificate.getProvider() || providers[options.providerName];
if (!self.signature) self.signature = provider.signature;
self.signatureAlgorithm = self.signature; // Set issuer
self.issuer = issuerCertificate.subject; // Set default extensions
if (!self.crlExtensions) self.crlExtensions = {};
var exts = self.crlExtensions,
ae = issuerCertificate.extensions;
if (ae && ae.subjectKeyIdentifier) exts.authorityKeyIdentifier = {
keyIdentifier: ae.subjectKeyIdentifier,
authorityCertIssuer: [issuerCertificate.issuer],
authorityCertSerialNumber: issuerCertificate.serialNumber
};
exts.cRLNumber = exts.cRLNumber || 0; // Import the private key
return subtle.importKey('pkcs8', issuerPrivateKey.encode(), issuerPrivateKey.privateKeyAlgorithm, false, ['sign']);
}).then(function (key) {
// Sign CRL
return subtle.sign(self.signatureAlgorithm, key, self.tbsCertList.encode());
}).then(function (signatureValue) {
// Siganture value
self.signatureValue = signatureValue;
return self;
});
},
// </editor-fold>
/**
* Verify the CRL. Checks the date and signature if issuer's certifiate has been defined.
*
* @memberOf GostCert.CRL
* @instance
* @param {GostCert.X509} issuerCertificate the issuer's certificate
* @param {Date} date Validation date. Default current date
* @returns {Promise} Promise to return self object if the certificate is valid
*/
verify: function verify(issuerCertificate, date) // <editor-fold defaultstate="collapsed">
{
var self = this,
exts = self.crlExtensions;
return new Promise(call).then(function () {
// Current date
date = date || today();
if (!self.thisUpdate.getTime() > date.getTime()) throw new Error('The CRL has not yet started'); // Check issuer
if (issuerCertificate) {
if (!matchCertificate(issuerCertificate, authoritySelector(self, exts, self.thisUpdate)) || !issuerCertificate.checkUsage('cRLSign', self.thisUpdate)) throw new Error('The issuer\'s certificate is not valid');
if (!self.signatureValue || !self.signatureAlgorithm) throw new Error('The has no signature'); // Check CRL signature
return issuerCertificate.verifySignature(self.tbsCertList.encode(), self.signatureValue, self.signatureAlgorithm);
}
}).then(function (result) {
if (!result) throw new Error('The CRL has invalid signature');
return self;
});
},
// </editor-fold>
/**
* Checks whether this certificate serial number is on the list.
*
* @memberOf GostCert.CRL
* @instance
* @param {Number} serialNumber the issuer's certificate
* @param {Date} date Validation date. Default current date
* @returns {boolean} True if the certificate is valid, and false otherwise
*/
isRevoked: function isRevoked(serialNumber, date) // <editor-fold defaultstate="collapsed">
{
var rc = this.revokedCertificates;
date = date || today();
for (var i = 0; i < rc.length; i++) {
// Check date and serial number
if (date.getTime() >= rc[i].revocationDate.getTime() && equalNumbers(rc[i].userCertificate, serialNumber)) return true;
}
return false;
} // </editor-fold>
});
/**
* This class encapsulates a X.509 certificate revocation list (CRL) of RevokedCertificate objects.
*
* @memberOf GostCert
* @type GostCert.CRL
*/
GostCert.prototype.CRL = CRL;
/**
* A class that encapsulates a DER-encoded PKCS #10 certificate request. The request contains
* the subject's name and public key, and it is signed with the subject's private key.
* The public key contained in the request is used to verify the signature.
* The signature on the request is verified automatically when the request is read.
* Note that the subject's private key is used only to produce a signature when the request is output,
* and is not actually stored with the request.
*
* @class GostCert.Request
* @extends GostASN1.CertificationRequest
* @param {(FormatedData|GostASN1.CertificationRequest)} req
*/
function Request(req) // <editor-fold defaultstate="collapsed">
{
try {
// Try to use encode
asn1.CertificationRequest.call(this, req, true);
} catch (e) {
// Create new certificate structure
req = req || {};
asn1.CertificationRequest.call(this, {
version: 0,
subject: req.subject || options.subject,
subjectPublicKeyInfo: req.subjectPublicKeyInfo || {
algorithm: {
id: 'noSignature'
},
subjectPublicKey: new CryptoOperationData(0)
},
attributes: req.attributes || {
extensionRequest: {
keyUsage: options.userKeyUsage,
extKeyUsage: options.userExtKeyUsage
}
},
signatureAlgorithm: {
id: 'noSignature'
},
signatureValue: new CryptoOperationData(0)
});
}
} // </editor-fold>
extend(asn1.CertificationRequest, Request, {
/**
* Generate key pair and sign request
*
* @memberOf GostCert.Request
* @instance
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm
* @returns {Promise} Promise to return {@link GostASN1.PrivateKeyInfo} after request generation
*/
generate: function generate(keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this,
privateKey,
provider;
if (keyAlgorithm) provider = providers[keyAlgorithm];else provider = this.getProvider() || providers[options.providerName];
if (provider) keyAlgorithm = expand(provider.publicKey, {
privateKey: provider.privateKey
});
return new Promise(call).then(function () {
// Generate key pair
return subtle.generateKey(keyAlgorithm, 'true', ['sign', 'verify']);
}).then(function (keyPair) {
privateKey = keyPair.privateKey; // Export public key
return subtle.exportKey('spki', keyPair.publicKey);
}).then(function (spki) {
self.subjectPublicKeyInfo = new asn1.SubjectPublicKeyInfo(spki);
return subtle.exportKey('pkcs8', privateKey);
}).then(function (pkcs8) {
privateKey = new asn1.PrivateKeyInfo(pkcs8); // Sign request
return self.sign(privateKey);
}).then(function () {
return privateKey;
});
},
// </editor-fold>
/**
* Get appropriate crypto provider for public key
*
* @memberOf GostCert.Request
* @instance
* @returns Object Set of crypto provider algorithms
*/
getProvider: function getProvider() // <editor-fold defaultstate="collapsed">
{
return keyProvider(this.subjectPublicKeyInfo.algorithm);
},
// </editor-fold>
/**
* Generate the contents of this request and sign it.<br><br>
*
* @memberOf GostCert.Request
* @instance
* @param {GostASN1.PrivateKeyInfo} privateKey The subject's private key
* @returns Promise to return self object after sign the request
*/
sign: function sign(privateKey) // <editor-fold defaultstate="collapsed">
{
var self = this,
spki = self.subjectPublicKeyInfo;
return new Promise(call).then(function () {
// Need generated key
if (!spki || !spki.algorithm || spki.algorithm === 'noSignature') throw new Error('Key pair was not generated for the certificate'); // Check issuer private key
if (!privateKey) throw new Error('The private key is not defined'); // Signature algorithm
var provider = keyProvider(spki.algorithm) || providers[options.providerName];
self.signatureAlgorithm = provider.signature; // Import the private key
return subtle.importKey('pkcs8', privateKey.encode(), privateKey.privateKeyAlgorithm, false, ['sign']);
}).then(function (key) {
// Sign the certification request
return subtle.sign(self.signatureAlgorithm, key, self.requestInfo.encode());
}).then(function (signatureValue) {
// Siganture value
self.signatureValue = signatureValue;
return self;
});
},
// </editor-fold>
/**
* Verify the Certification Request. Checks the signature on the public key in the request.
*
* @memberOf GostCert.Request
* @instance
* @returns {Promise} Promise to return self object if the certificate is valid
*/
verify: function verify() // <editor-fold defaultstate="collapsed">
{
var self = this,
spki = self.subjectPublicKeyInfo;
return new Promise(call).then(function () {
// Import key
return subtle.importKey('spki', spki.encode(), spki.algorithm, 'false', ['verify']);
}).then(function (publicKey) {
// Verify signature
return subtle.verify(self.signatureAlgorithm, publicKey, self.signatureValue, self.requestInfo.encode());
}).then(function (result) {
if (!result) throw new Error('The certification request has invalid signature');
return self;
});
} // </editor-fold>
});
/**
* A class that encapsulates a DER-encoded PKCS #10 certificate request.
*
* @memberOf GostCert
* @type GostCert.Request
*/
GostCert.prototype.Request = Request;
/**
* A class for retrieving Certificates and CRLs from a repository.<br><br>
*
* Once the CertStore has been created, it can be used to retrieve Certificates
* and CRLs by calling its getCertificates and getCRLs methods. Unlike a KeyStore,
* which provides access to a cache of private keys and trusted certificates,
* a CertStore is designed to provide access to a potentially vast repository
* of untrusted certificates and CRLs.
*
* @class GostCert.CertStore
* @param {GostCert.X509[]} certificates Certificates
* @param {GostCert.CRL[]} crls CLRs
*/
function CertStore(certificates, crls) // <editor-fold defaultstate="collapsed">
{
this.certificates = certificates || [];
this.crls = crls || [];
} // </editor-fold>
extend(Object, CertStore, {
/**
* Returns a Array of Certificates that match the specified selector.
*
* @memberOf GostCert.CertStore
* @instance
* @param {GostCert.CertSelector} selector Certificate filter selector
* @returns {GostCert.X509[]} Selected certificates
*/
getCertificates: function getCertificates(selector) // <editor-fold defaultstate="collapsed">
{
return selectCertificates(this.certificates, selector);
},
// </editor-fold>
/**
* Returns a Collection of CRLs that match the specified selector.
*
* @memberOf GostCert.CertStore
* @instance
* @param {GostCert.CertSelector} selector CRL filter selector
* @returns {GostCert.CRL[]} selected CRLs
*/
getCRLs: function getCRLs(selector) // <editor-fold defaultstate="collapsed">
{
return selectCRLs(this.certificates, selector);
},
// </editor-fold>
/**
* Loads this CertStore from the given PKCS#7 formated input stream.
*
* @memberOf GostCert.CertStore
* @instance
* @param {(FormatedData|GostASN1.ContentInfo)} store The input stream from which the certstore is loaded
* @returns {GostCert.CertStore} Self object after store loaded
*/
load: function load(store) // <editor-fold defaultstate="collapsed">
{
var info = new asn1.ContentInfo(store),
certs = info.certificates,
crls = info.crls;
for (var i = 0; i < certs.length; i++) {
this.certificates.push(new X509(certs[i]));
}
for (var i = 0; i < crls.length; i++) {
this.crls.push(new CRL(crls[i]));
}
return this;
},
// </editor-fold>
/**
* Stores this CertStore to the given output stream in PKCS#7 format.
*
* @memberOf GostCert.CertStore
* @instance
* @returns {GostASN1.ContentInfo} PKCS#7 content info with certificates and crls from CertStore
*/
store: function store() // <editor-fold defaultstate="collapsed">
{
return new asn1.ContentInfo({
contentType: 'signedData',
version: 0,
digestAlgorithms: [],
encapContentInfo: {
contentType: 'data'
},
certificates: this.certs,
crls: this.crls,
signerInfos: []
});
} // </editor-fold>
});
/**
* A class for retrieving Certificates and CRLs from a repository.
*
* @memberOf GostCert
* @type GostCert.Request
*/
GostCert.prototype.CertStore = CertStore;
/**
* A class for building and validating certification paths (also known as certificate chains).
*
* @class GostCert.CertPath
* @param {GostCert.CertStore} certStore
*/
function CertPath(certStore) // <editor-fold defaultstate="collapsed">
{
this.certStore = certStore;
} // </editor-fold>
extend(Object, CertPath, {
/**
* Attempts to build a certification path using the specified algorithm parameter set.
*
* @memberOf GostCert.CertPath
* @instance
* @param {GostCert.X509} certificate Starting path certificate
* @param {Date} date Validation date. Default today
* @returns {Promise} Promise to return array of {@link GostCert.X509} with certification path
*/
build: function build(certificate, date) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
// Build certification path
var current = new X509(certificate),
certPath = [],
success = false,
verifiers = [];
while (current) {
var foundCRLs = [],
founds = [];
certPath.push(current);
if (!success) {
// Select issuer CRL
foundCRLs = self.certStore.getCRLs({
issuer: current.issuer,
date: date
}); // Create issuer's selection criteria
var selector = authoritySelector(current, current.extensions, current.notBefore); // Self-signed certificate?
if (!matchCertificate(current, selector)) // Select issuer form trusted CA root list
founds = self.certStore.getCertificates(selector);else success = true;
} // Add verification tasks
var next = founds.length > 0 && new X509(founds[0]),
crl = foundCRLs.length > 0 && new CRL(foundCRLs[0]); // Verify CRLs
if (crl) verifiers.push(crl.verify(next, date)); // Verify the certificate
verifiers.push(current.verify(next, crl, date));
current = next;
}
if (!success) throw new Error('Root certificate is not found'); // Verify all certificates in path
return Promise.all(verifiers).then(function (results) {
for (var i = 0; i < results; i++) {
if (!results[i]) throw new Error('Certification path is not validated');
}
return certPath;
});
});
} // </editor-fold>
});
/**
* A class for building and validating certification paths (also known as certificate chains).
*
* @memberOf GostCert
* @type GostCert.CertPath
*/
GostCert.prototype.CertPath = CertPath;
/**
* A generic interface for implementing a particular certificate verification
* scheme, such as constructing and verifying
* certificate chains.
*
* @class GostCert.CertificateTrustPolicy
*/
function CertificateTrustPolicy() {}
extend(Object, CertificateTrustPolicy, {
/**
* Returns a certificate, known to be valid (according to criteria dependent
* on the verification scheme), which has the given selector, certificate and
* CRL lists to implement a particular certificate verification scheme,
* such a forming valid certificate chains.<br>
* Second and third argument to this method may be undefined, and such a case
* must be treated exactly the same as if the particular argument was an empty array.
*
* @memberOf GostCert.CertificateTrustPolicy
* @instance
* @param {GostCert.CertificateSelector} selector Certificate selector
* @param {GostCert.X509[]} certificates Certificates
* @param {GostCert.CRL[]} crls CLRs
* @returns {Promise} Promise to return valid {@link GostCert.X509}
*/
getValidCertificate: function getValidCertificate(selector, certificates, crls) {}
});
/**
* A generic interface for implementing a particular certificate verification
*
* @memberOf GostCert
* @type GostCert.CertificateTrustPolicy
*/
GostCert.prototype.CertificateTrustPolicy = CertificateTrustPolicy;
/**
* A certificate trust policy based on a set of trusted root CAs.<br><br>
*
* In this policy, a certificate will be trusted if and only if it is part of a
* valid certificate chain which terminates in one of the trusted root CAs. <br><br>
*
* This policy has two options for certificate chain verification:
* <ul>
* <li>requireCRL - If true, then for every certificate in a chain
* (unless it is one of the trusted root CA certificates) a valid CRL
* must be provided to determine its revocation status. The default is false.</li>
* <li>requireCAFlag - If true, then every intermediate CA certificate (excluding
* the root CA or the end entity certificate) must contain a Basic Constraints
* extension, with the CA flag set. The default for this option is true.</li>
* </ul>
*
* @class GostCert.TrustedCAPolicy
* @extends GostCert.CertificateTrustPolicy
* @param {GostCert.X509[]} trustedCACerts
* @param {boolean} requireCRL
* @param {boolean} requireCA
*/
function TrustedCAPolicy(trustedCACerts, requireCRL, requireCA) // <editor-fold defaultstate="collapsed">
{
this.trustedCACerts = trustedCACerts || [];
this.requireCRL = requireCRL || false;
this.requireCA = requireCA || true;
} // </editor-fold>
extend(CertificateTrustPolicy, TrustedCAPolicy, {
/**
* Returns a certificate, known to be valid (according to criteria dependent
* on the verification scheme), which has the given selector, certificate and
* CRL lists to implement a particular certificate verification scheme,
* such a forming valid certificate chains.<br>
* Second and third argument to this method may be undefined, and such a case
* must be treated exactly the same as if the particular argument was an empty array.
*
* @memberOf GostCert.TrustedCAPolicy
* @instance
* @param {GostCert.CertificateSelector} selector Certificate selector
* @param {GostASN1.Certificate[]} certificates Certificates
* @param {GostASN1.CertificateList[]} crls CLRs
* @param {Date} date Validation date. Default today
* @returns {Promise} Promise to return valid {@link GostCert.X509}
*/
getValidCertificate: function getValidCertificate(selector, certificates, crls, date) // <editor-fold defaultstate="collapsed">
{
var self = this,
certPath;
return new Promise(call).then(function () {
certificates = certificates || [];
crls = crls || []; // Get certificates from the trusted list
var certs = selectCertificates(self.trustedCACerts, selector);
if (certs.length > 0) return new X509(certs[0]); // Get certificates from the list
certs = selectCertificates(certificates, selector);
if (certs.length === 0) return; // Build certification path
var current = new X509(certs[0]),
success = false,
verifiers = [];
certPath = [];
while (current) {
var foundCRLs = [],
founds = [];
certPath.push(current);
if (!success) {
// Select issuer CRL
foundCRLs = selectCRLs(crls, {
issuer: current.issuer,
date: date
});
if (foundCRLs.length === 0 && self.requireCRL) return; // The issuer\'s CRL is not found
// Create issuer's selection criteria
selector = authoritySelector(current, current.extensions, current.notBefore); // Select issuer form trusted CA root list
founds = selectCertificates(self.trustedCACerts, selector);
if (founds.length === 0) {
// Non-trusted self-signed certificate?
if (!matchCertificate(current, selector)) {
// Select issuer from certificate list
founds = selectCertificates(certificates, selector);
if (founds.length > 0) {
// Check basic contrains and CA flag
var exts = founds[0].extensions;
if (self.requireCA) {
if (!exts || !exts.basicConstraints || !exts.basicConstraints.cA) return; // The issuer\'s certificate is not valid
// Check path length limit
if (exts.basicConstraints.pathLenConstraint !== undefined && exts.basicConstraints.pathLenConstraint < certPath.length - 1) return; // The issuer\'s certificate path length constraint exceeded
}
} else return; // Certification path is not built
}
} else success = true;
} // Add verification tasks
var next = founds.length > 0 && new X509(founds[0]),
crl = foundCRLs.length > 0 && new CRL(foundCRLs[0]); // Verify CRLs
if (crl) verifiers.push(crl.verify(next, date)); // Verify the certificate
verifiers.push(current.verify(next, crl, date));
current = next;
}
if (!success) throw new Error('Trusted root certificate is not found'); // Verify all certificates in path
return Promise.all(verifiers).then(function (results) {
for (var i = 0; i < results; i++) {
if (!results[i]) throw new Error('Certification path is not validated');
}
return certPath[0];
});
});
} // </editor-fold>
});
/**
* A certificate trust policy based on a set of trusted root CAs.
*
* @memberOf GostCert
* @type GostCert.TrustedCAPolicy
*/
GostCert.prototype.TrustedCAPolicy = TrustedCAPolicy;
/**
* Provides facilities for handling certificates, CRLs, etc.
*
* @memberOf gostCrypto
* @type GostCert
*/
gostCrypto.cert = new GostCert();
return GostCert;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostASN1":105,"./gostCrypto":110}],108:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file GOST 28147-89/GOST R 34.12-2015/GOST R 32.13-2015 Encryption Algorithm
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostRandom'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostRandom'));
} else {
root.GostCipher = factory(root.GostRandom);
} // </editor-fold>
})(void 0, function (GostRandom) {
/*
* Initial parameters and common algortithms of GOST 28147-89
*
* http://tools.ietf.org/html/rfc5830
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var rootCrypto = root.crypto || root.msCrypto;
var CryptoOperationData = root.ArrayBuffer;
var SyntaxError = root.SyntaxError || root.Error,
DataError = root.DataError || root.Error,
NotSupportedError = root.NotSupportedError || root.Error;
/*
* Check supported
* This implementation support only Little Endian arhitecture
*/
var littleEndian = function () {
var buffer = new CryptoOperationData(2);
new DataView(buffer).setInt16(0, 256, true);
return new Int16Array(buffer)[0] === 256;
}(); // Default initial vector
var defaultIV = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0]); // Predefined sBox collection
var sBoxes = {
'E-TEST': [0x4, 0x2, 0xF, 0x5, 0x9, 0x1, 0x0, 0x8, 0xE, 0x3, 0xB, 0xC, 0xD, 0x7, 0xA, 0x6, 0xC, 0x9, 0xF, 0xE, 0x8, 0x1, 0x3, 0xA, 0x2, 0x7, 0x4, 0xD, 0x6, 0x0, 0xB, 0x5, 0xD, 0x8, 0xE, 0xC, 0x7, 0x3, 0x9, 0xA, 0x1, 0x5, 0x2, 0x4, 0x6, 0xF, 0x0, 0xB, 0xE, 0x9, 0xB, 0x2, 0x5, 0xF, 0x7, 0x1, 0x0, 0xD, 0xC, 0x6, 0xA, 0x4, 0x3, 0x8, 0x3, 0xE, 0x5, 0x9, 0x6, 0x8, 0x0, 0xD, 0xA, 0xB, 0x7, 0xC, 0x2, 0x1, 0xF, 0x4, 0x8, 0xF, 0x6, 0xB, 0x1, 0x9, 0xC, 0x5, 0xD, 0x3, 0x7, 0xA, 0x0, 0xE, 0x2, 0x4, 0x9, 0xB, 0xC, 0x0, 0x3, 0x6, 0x7, 0x5, 0x4, 0x8, 0xE, 0xF, 0x1, 0xA, 0x2, 0xD, 0xC, 0x6, 0x5, 0x2, 0xB, 0x0, 0x9, 0xD, 0x3, 0xE, 0x7, 0xA, 0xF, 0x4, 0x1, 0x8],
'E-A': [0x9, 0x6, 0x3, 0x2, 0x8, 0xB, 0x1, 0x7, 0xA, 0x4, 0xE, 0xF, 0xC, 0x0, 0xD, 0x5, 0x3, 0x7, 0xE, 0x9, 0x8, 0xA, 0xF, 0x0, 0x5, 0x2, 0x6, 0xC, 0xB, 0x4, 0xD, 0x1, 0xE, 0x4, 0x6, 0x2, 0xB, 0x3, 0xD, 0x8, 0xC, 0xF, 0x5, 0xA, 0x0, 0x7, 0x1, 0x9, 0xE, 0x7, 0xA, 0xC, 0xD, 0x1, 0x3, 0x9, 0x0, 0x2, 0xB, 0x4, 0xF, 0x8, 0x5, 0x6, 0xB, 0x5, 0x1, 0x9, 0x8, 0xD, 0xF, 0x0, 0xE, 0x4, 0x2, 0x3, 0xC, 0x7, 0xA, 0x6, 0x3, 0xA, 0xD, 0xC, 0x1, 0x2, 0x0, 0xB, 0x7, 0x5, 0x9, 0x4, 0x8, 0xF, 0xE, 0x6, 0x1, 0xD, 0x2, 0x9, 0x7, 0xA, 0x6, 0x0, 0x8, 0xC, 0x4, 0x5, 0xF, 0x3, 0xB, 0xE, 0xB, 0xA, 0xF, 0x5, 0x0, 0xC, 0xE, 0x8, 0x6, 0x2, 0x3, 0x9, 0x1, 0x7, 0xD, 0x4],
'E-B': [0x8, 0x4, 0xB, 0x1, 0x3, 0x5, 0x0, 0x9, 0x2, 0xE, 0xA, 0xC, 0xD, 0x6, 0x7, 0xF, 0x0, 0x1, 0x2, 0xA, 0x4, 0xD, 0x5, 0xC, 0x9, 0x7, 0x3, 0xF, 0xB, 0x8, 0x6, 0xE, 0xE, 0xC, 0x0, 0xA, 0x9, 0x2, 0xD, 0xB, 0x7, 0x5, 0x8, 0xF, 0x3, 0x6, 0x1, 0x4, 0x7, 0x5, 0x0, 0xD, 0xB, 0x6, 0x1, 0x2, 0x3, 0xA, 0xC, 0xF, 0x4, 0xE, 0x9, 0x8, 0x2, 0x7, 0xC, 0xF, 0x9, 0x5, 0xA, 0xB, 0x1, 0x4, 0x0, 0xD, 0x6, 0x8, 0xE, 0x3, 0x8, 0x3, 0x2, 0x6, 0x4, 0xD, 0xE, 0xB, 0xC, 0x1, 0x7, 0xF, 0xA, 0x0, 0x9, 0x5, 0x5, 0x2, 0xA, 0xB, 0x9, 0x1, 0xC, 0x3, 0x7, 0x4, 0xD, 0x0, 0x6, 0xF, 0x8, 0xE, 0x0, 0x4, 0xB, 0xE, 0x8, 0x3, 0x7, 0x1, 0xA, 0x2, 0x9, 0x6, 0xF, 0xD, 0x5, 0xC],
'E-C': [0x1, 0xB, 0xC, 0x2, 0x9, 0xD, 0x0, 0xF, 0x4, 0x5, 0x8, 0xE, 0xA, 0x7, 0x6, 0x3, 0x0, 0x1, 0x7, 0xD, 0xB, 0x4, 0x5, 0x2, 0x8, 0xE, 0xF, 0xC, 0x9, 0xA, 0x6, 0x3, 0x8, 0x2, 0x5, 0x0, 0x4, 0x9, 0xF, 0xA, 0x3, 0x7, 0xC, 0xD, 0x6, 0xE, 0x1, 0xB, 0x3, 0x6, 0x0, 0x1, 0x5, 0xD, 0xA, 0x8, 0xB, 0x2, 0x9, 0x7, 0xE, 0xF, 0xC, 0x4, 0x8, 0xD, 0xB, 0x0, 0x4, 0x5, 0x1, 0x2, 0x9, 0x3, 0xC, 0xE, 0x6, 0xF, 0xA, 0x7, 0xC, 0x9, 0xB, 0x1, 0x8, 0xE, 0x2, 0x4, 0x7, 0x3, 0x6, 0x5, 0xA, 0x0, 0xF, 0xD, 0xA, 0x9, 0x6, 0x8, 0xD, 0xE, 0x2, 0x0, 0xF, 0x3, 0x5, 0xB, 0x4, 0x1, 0xC, 0x7, 0x7, 0x4, 0x0, 0x5, 0xA, 0x2, 0xF, 0xE, 0xC, 0x6, 0x1, 0xB, 0xD, 0x9, 0x3, 0x8],
'E-D': [0xF, 0xC, 0x2, 0xA, 0x6, 0x4, 0x5, 0x0, 0x7, 0x9, 0xE, 0xD, 0x1, 0xB, 0x8, 0x3, 0xB, 0x6, 0x3, 0x4, 0xC, 0xF, 0xE, 0x2, 0x7, 0xD, 0x8, 0x0, 0x5, 0xA, 0x9, 0x1, 0x1, 0xC, 0xB, 0x0, 0xF, 0xE, 0x6, 0x5, 0xA, 0xD, 0x4, 0x8, 0x9, 0x3, 0x7, 0x2, 0x1, 0x5, 0xE, 0xC, 0xA, 0x7, 0x0, 0xD, 0x6, 0x2, 0xB, 0x4, 0x9, 0x3, 0xF, 0x8, 0x0, 0xC, 0x8, 0x9, 0xD, 0x2, 0xA, 0xB, 0x7, 0x3, 0x6, 0x5, 0x4, 0xE, 0xF, 0x1, 0x8, 0x0, 0xF, 0x3, 0x2, 0x5, 0xE, 0xB, 0x1, 0xA, 0x4, 0x7, 0xC, 0x9, 0xD, 0x6, 0x3, 0x0, 0x6, 0xF, 0x1, 0xE, 0x9, 0x2, 0xD, 0x8, 0xC, 0x4, 0xB, 0xA, 0x5, 0x7, 0x1, 0xA, 0x6, 0x8, 0xF, 0xB, 0x0, 0x4, 0xC, 0x3, 0x5, 0x9, 0x7, 0xD, 0x2, 0xE],
'E-SC': [0x3, 0x6, 0x1, 0x0, 0x5, 0x7, 0xd, 0x9, 0x4, 0xb, 0x8, 0xc, 0xe, 0xf, 0x2, 0xa, 0x7, 0x1, 0x5, 0x2, 0x8, 0xb, 0x9, 0xc, 0xd, 0x0, 0x3, 0xa, 0xf, 0xe, 0x4, 0x6, 0xf, 0x1, 0x4, 0x6, 0xc, 0x8, 0x9, 0x2, 0xe, 0x3, 0x7, 0xa, 0xb, 0xd, 0x5, 0x0, 0x3, 0x4, 0xf, 0xc, 0x5, 0x9, 0xe, 0x0, 0x6, 0x8, 0x7, 0xa, 0x1, 0xb, 0xd, 0x2, 0x6, 0x9, 0x0, 0x7, 0xb, 0x8, 0x4, 0xc, 0x2, 0xe, 0xa, 0xf, 0x1, 0xd, 0x5, 0x3, 0x6, 0x1, 0x2, 0xf, 0x0, 0xb, 0x9, 0xc, 0x7, 0xd, 0xa, 0x5, 0x8, 0x4, 0xe, 0x3, 0x0, 0x2, 0xe, 0xc, 0x9, 0x1, 0x4, 0x7, 0x3, 0xf, 0x6, 0x8, 0xa, 0xd, 0xb, 0x5, 0x5, 0x2, 0xb, 0x8, 0x4, 0xc, 0x7, 0x1, 0xa, 0x6, 0xe, 0x0, 0x9, 0x3, 0xd, 0xf],
'E-Z': [// This is default S-box in according to draft of new standard
0xc, 0x4, 0x6, 0x2, 0xa, 0x5, 0xb, 0x9, 0xe, 0x8, 0xd, 0x7, 0x0, 0x3, 0xf, 0x1, 0x6, 0x8, 0x2, 0x3, 0x9, 0xa, 0x5, 0xc, 0x1, 0xe, 0x4, 0x7, 0xb, 0xd, 0x0, 0xf, 0xb, 0x3, 0x5, 0x8, 0x2, 0xf, 0xa, 0xd, 0xe, 0x1, 0x7, 0x4, 0xc, 0x9, 0x6, 0x0, 0xc, 0x8, 0x2, 0x1, 0xd, 0x4, 0xf, 0x6, 0x7, 0x0, 0xa, 0x5, 0x3, 0xe, 0x9, 0xb, 0x7, 0xf, 0x5, 0xa, 0x8, 0x1, 0x6, 0xd, 0x0, 0x9, 0x3, 0xe, 0xb, 0x4, 0x2, 0xc, 0x5, 0xd, 0xf, 0x6, 0x9, 0x2, 0xc, 0xa, 0xb, 0x7, 0x8, 0x1, 0x4, 0x3, 0xe, 0x0, 0x8, 0xe, 0x2, 0x5, 0x6, 0x9, 0x1, 0xc, 0xf, 0x4, 0xb, 0x0, 0xd, 0xa, 0x3, 0x7, 0x1, 0x7, 0xe, 0xd, 0x0, 0x5, 0x8, 0x3, 0x4, 0xf, 0xa, 0x6, 0x9, 0xc, 0xb, 0x2],
//S-box for digest
'D-TEST': [0x4, 0xA, 0x9, 0x2, 0xD, 0x8, 0x0, 0xE, 0x6, 0xB, 0x1, 0xC, 0x7, 0xF, 0x5, 0x3, 0xE, 0xB, 0x4, 0xC, 0x6, 0xD, 0xF, 0xA, 0x2, 0x3, 0x8, 0x1, 0x0, 0x7, 0x5, 0x9, 0x5, 0x8, 0x1, 0xD, 0xA, 0x3, 0x4, 0x2, 0xE, 0xF, 0xC, 0x7, 0x6, 0x0, 0x9, 0xB, 0x7, 0xD, 0xA, 0x1, 0x0, 0x8, 0x9, 0xF, 0xE, 0x4, 0x6, 0xC, 0xB, 0x2, 0x5, 0x3, 0x6, 0xC, 0x7, 0x1, 0x5, 0xF, 0xD, 0x8, 0x4, 0xA, 0x9, 0xE, 0x0, 0x3, 0xB, 0x2, 0x4, 0xB, 0xA, 0x0, 0x7, 0x2, 0x1, 0xD, 0x3, 0x6, 0x8, 0x5, 0x9, 0xC, 0xF, 0xE, 0xD, 0xB, 0x4, 0x1, 0x3, 0xF, 0x5, 0x9, 0x0, 0xA, 0xE, 0x7, 0x6, 0x8, 0x2, 0xC, 0x1, 0xF, 0xD, 0x0, 0x5, 0x7, 0xA, 0x4, 0x9, 0x2, 0x3, 0xE, 0x6, 0xB, 0x8, 0xC],
'D-A': [0xA, 0x4, 0x5, 0x6, 0x8, 0x1, 0x3, 0x7, 0xD, 0xC, 0xE, 0x0, 0x9, 0x2, 0xB, 0xF, 0x5, 0xF, 0x4, 0x0, 0x2, 0xD, 0xB, 0x9, 0x1, 0x7, 0x6, 0x3, 0xC, 0xE, 0xA, 0x8, 0x7, 0xF, 0xC, 0xE, 0x9, 0x4, 0x1, 0x0, 0x3, 0xB, 0x5, 0x2, 0x6, 0xA, 0x8, 0xD, 0x4, 0xA, 0x7, 0xC, 0x0, 0xF, 0x2, 0x8, 0xE, 0x1, 0x6, 0x5, 0xD, 0xB, 0x9, 0x3, 0x7, 0x6, 0x4, 0xB, 0x9, 0xC, 0x2, 0xA, 0x1, 0x8, 0x0, 0xE, 0xF, 0xD, 0x3, 0x5, 0x7, 0x6, 0x2, 0x4, 0xD, 0x9, 0xF, 0x0, 0xA, 0x1, 0x5, 0xB, 0x8, 0xE, 0xC, 0x3, 0xD, 0xE, 0x4, 0x1, 0x7, 0x0, 0x5, 0xA, 0x3, 0xC, 0x8, 0xF, 0x6, 0x2, 0x9, 0xB, 0x1, 0x3, 0xA, 0x9, 0x5, 0xB, 0x4, 0xF, 0x8, 0x6, 0x7, 0xE, 0xD, 0x0, 0x2, 0xC],
'D-SC': [0xb, 0xd, 0x7, 0x0, 0x5, 0x4, 0x1, 0xf, 0x9, 0xe, 0x6, 0xa, 0x3, 0xc, 0x8, 0x2, 0x1, 0x2, 0x7, 0x9, 0xd, 0xb, 0xf, 0x8, 0xe, 0xc, 0x4, 0x0, 0x5, 0x6, 0xa, 0x3, 0x5, 0x1, 0xd, 0x3, 0xf, 0x6, 0xc, 0x7, 0x9, 0x8, 0xb, 0x2, 0x4, 0xe, 0x0, 0xa, 0xd, 0x1, 0xb, 0x4, 0x9, 0xc, 0xe, 0x0, 0x7, 0x5, 0x8, 0xf, 0x6, 0x2, 0xa, 0x3, 0x2, 0xd, 0xa, 0xf, 0x9, 0xb, 0x3, 0x7, 0x8, 0xc, 0x5, 0xe, 0x6, 0x0, 0x1, 0x4, 0x0, 0x4, 0x6, 0xc, 0x5, 0x3, 0x8, 0xd, 0xa, 0xb, 0xf, 0x2, 0x1, 0x9, 0x7, 0xe, 0x1, 0x3, 0xc, 0x8, 0xa, 0x6, 0xb, 0x0, 0x2, 0xe, 0x7, 0x9, 0xf, 0x4, 0x5, 0xd, 0xa, 0xb, 0x6, 0x0, 0x1, 0x3, 0x4, 0x7, 0xe, 0xd, 0x5, 0xf, 0x8, 0x2, 0x9, 0xc]
};
var C = new Uint8Array([0x69, 0x00, 0x72, 0x22, 0x64, 0xC9, 0x04, 0x23, 0x8D, 0x3A, 0xDB, 0x96, 0x46, 0xE9, 0x2A, 0xC4, 0x18, 0xFE, 0xAC, 0x94, 0x00, 0xED, 0x07, 0x12, 0xC0, 0x86, 0xDC, 0xC2, 0xEF, 0x4C, 0xA9, 0x2B]);
function signed(x) {
return x >= 0x80000000 ? x - 0x100000000 : x;
}
function unsigned(x) {
return x < 0 ? x + 0x100000000 : x;
} // Set random values into Uint8Arry
// Random generator
function randomSeed(e) {
GostRandom = GostRandom || root.GostRandom;
var randomSource = GostRandom ? new (GostRandom || root.GostRandom)() : rootCrypto;
if (randomSource.getRandomValues) randomSource.getRandomValues(e);else throw new NotSupportedError('Random generator not found');
} // Get buffer
function buffer(d) {
if (d instanceof CryptoOperationData) return d;else if (d && d.buffer && d.buffer instanceof CryptoOperationData) return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ? d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;else throw new DataError('CryptoOperationData required');
} // Get byte array
function byteArray(d) {
return new Uint8Array(buffer(d));
} // Clone byte array
function cloneArray(d) {
return new Uint8Array(byteArray(d));
} // Get int32 array
function intArray(d) {
return new Int32Array(buffer(d));
} // Swap bytes for version 2015
function swap32(b) {
return (b & 0xff) << 24 | (b & 0xff00) << 8 | b >> 8 & 0xff00 | b >> 24 & 0xff;
} // </editor-fold>
/*
* Initial parameters and common algortithms of GOST R 34.12-15
* Algorithm "Kuznechik" 128bit
*
*/
// <editor-fold defaultstate="collapsed">
// Default initial vector
var defaultIV128 = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); // Mult table for R function
var multTable = function () {
// Multiply two numbers in the GF(2^8) finite field defined
// by the polynomial x^8 + x^7 + x^6 + x + 1 = 0 */
function gmul(a, b) {
var p = 0,
counter,
carry;
for (counter = 0; counter < 8; counter++) {
if (b & 1) p ^= a;
carry = a & 0x80; // detect if x^8 term is about to be generated
a = a << 1 & 0xff;
if (carry) a ^= 0xc3; // replace x^8 with x^7 + x^6 + x + 1
b >>= 1;
}
return p & 0xff;
} // It is required only this values for R function
// 0 1 2 3 4 5 6 7
var x = [1, 16, 32, 133, 148, 192, 194, 251];
var m = [];
for (var i = 0; i < 8; i++) {
m[i] = [];
for (var j = 0; j < 256; j++) {
m[i][j] = gmul(x[i], j);
}
}
return m;
}(); // 148, 32, 133, 16, 194, 192, 1, 251, 1, 192, 194, 16, 133, 32, 148, 1
var kB = [4, 2, 3, 1, 6, 5, 0, 7, 0, 5, 6, 1, 3, 2, 4, 0]; // R - function
function funcR(d) {
var sum = 0;
for (var i = 0; i < 16; i++) {
sum ^= multTable[kB[i]][d[i]];
}
for (var i = 16; i > 0; --i) {
d[i] = d[i - 1];
}
d[0] = sum;
}
function funcReverseR(d) {
var tmp = d[0];
for (var i = 0; i < 15; i++) {
d[i] = d[i + 1];
}
d[15] = tmp;
var sum = 0;
for (i = 0; i < 16; i++) {
sum ^= multTable[kB[i]][d[i]];
}
d[15] = sum;
} // Nonlinear transformation
var kPi = [252, 238, 221, 17, 207, 110, 49, 22, 251, 196, 250, 218, 35, 197, 4, 77, 233, 119, 240, 219, 147, 46, 153, 186, 23, 54, 241, 187, 20, 205, 95, 193, 249, 24, 101, 90, 226, 92, 239, 33, 129, 28, 60, 66, 139, 1, 142, 79, 5, 132, 2, 174, 227, 106, 143, 160, 6, 11, 237, 152, 127, 212, 211, 31, 235, 52, 44, 81, 234, 200, 72, 171, 242, 42, 104, 162, 253, 58, 206, 204, 181, 112, 14, 86, 8, 12, 118, 18, 191, 114, 19, 71, 156, 183, 93, 135, 21, 161, 150, 41, 16, 123, 154, 199, 243, 145, 120, 111, 157, 158, 178, 177, 50, 117, 25, 61, 255, 53, 138, 126, 109, 84, 198, 128, 195, 189, 13, 87, 223, 245, 36, 169, 62, 168, 67, 201, 215, 121, 214, 246, 124, 34, 185, 3, 224, 15, 236, 222, 122, 148, 176, 188, 220, 232, 40, 80, 78, 51, 10, 74, 167, 151, 96, 115, 30, 0, 98, 68, 26, 184, 56, 130, 100, 159, 38, 65, 173, 69, 70, 146, 39, 94, 85, 47, 140, 163, 165, 125, 105, 213, 149, 59, 7, 88, 179, 64, 134, 172, 29, 247, 48, 55, 107, 228, 136, 217, 231, 137, 225, 27, 131, 73, 76, 63, 248, 254, 141, 83, 170, 144, 202, 216, 133, 97, 32, 113, 103, 164, 45, 43, 9, 91, 203, 155, 37, 208, 190, 229, 108, 82, 89, 166, 116, 210, 230, 244, 180, 192, 209, 102, 175, 194, 57, 75, 99, 182];
var kReversePi = function () {
var m = [];
for (var i = 0, n = kPi.length; i < n; i++) {
m[kPi[i]] = i;
}
return m;
}();
function funcS(d) {
for (var i = 0; i < 16; ++i) {
d[i] = kPi[d[i]];
}
}
function funcReverseS(d) {
for (var i = 0; i < 16; ++i) {
d[i] = kReversePi[d[i]];
}
}
function funcX(a, b) {
for (var i = 0; i < 16; ++i) {
a[i] ^= b[i];
}
}
function funcL(d) {
for (var i = 0; i < 16; ++i) {
funcR(d);
}
}
function funcReverseL(d) {
for (var i = 0; i < 16; ++i) {
funcReverseR(d);
}
}
function funcLSX(a, b) {
funcX(a, b);
funcS(a);
funcL(a);
}
function funcReverseLSX(a, b) {
funcX(a, b);
funcReverseL(a);
funcReverseS(a);
}
function funcF(inputKey, inputKeySecond, iterationConst) {
var tmp = new Uint8Array(inputKey);
funcLSX(inputKey, iterationConst);
funcX(inputKey, inputKeySecond);
inputKeySecond.set(tmp);
}
function funcC(number, d) {
for (var i = 0; i < 15; i++) {
d[i] = 0;
}
d[15] = number;
funcL(d);
} // </editor-fold>
/**
* Key schedule for GOST R 34.12-15 128bits
*
* @memberOf GostCipher
* @private
* @instance
* @method keySchedule
* @param {type} k
* @returns {Uint8Array}
*/
function keySchedule128(k) // <editor-fold defaultstate="collapsed">
{
var keys = new Uint8Array(160),
c = new Uint8Array(16);
keys.set(byteArray(k));
for (var j = 0; j < 4; j++) {
var j0 = 32 * j,
j1 = 32 * (j + 1);
keys.set(new Uint8Array(keys.buffer, j0, 32), j1);
for (var i = 1; i < 9; i++) {
funcC(j * 8 + i, c);
funcF(new Uint8Array(keys.buffer, j1, 16), new Uint8Array(keys.buffer, j1 + 16, 16), c);
}
}
return keys;
} // </editor-fold>
/**
* GOST R 34.12-15 128 bits encrypt/decrypt process
*
* @memberOf GostCipher
* @private
* @instance
* @method round
* @param {Uint8Array} k Scheduled key
* @param {Uint8Array} d Data
* @param {number} ofs Offsec
* @param {number} e true - decrypt
*/
function process128(k, d, ofs, e) // <editor-fold defaultstate="collapsed">
{
ofs = ofs || d.byteOffset;
var r = new Uint8Array(d.buffer, ofs, 16);
if (e) {
for (var i = 0; i < 9; i++) {
funcReverseLSX(r, new Uint8Array(k.buffer, (9 - i) * 16, 16));
}
funcX(r, new Uint8Array(k.buffer, 0, 16));
} else {
for (var i = 0; i < 9; i++) {
funcLSX(r, new Uint8Array(k.buffer, 16 * i, 16));
}
funcX(r, new Uint8Array(k.buffer, 16 * 9, 16));
}
} // </editor-fold>
/**
* One GOST encryption round
*
* @memberOf GostCipher
* @private
* @instance
* @method round
* @param {Int8Array} S sBox
* @param {Int32Array} m 2x32 bits cipher block
* @param {Int32Array} k 32 bits key[i]
*/
function round(S, m, k) // <editor-fold defaultstate="collapsed">
{
var cm = m[0] + k & 0xffffffff;
var om = S[0 + (cm >> 0 * 4 & 0xF)] << 0 * 4;
om |= S[16 + (cm >> 1 * 4 & 0xF)] << 1 * 4;
om |= S[32 + (cm >> 2 * 4 & 0xF)] << 2 * 4;
om |= S[48 + (cm >> 3 * 4 & 0xF)] << 3 * 4;
om |= S[64 + (cm >> 4 * 4 & 0xF)] << 4 * 4;
om |= S[80 + (cm >> 5 * 4 & 0xF)] << 5 * 4;
om |= S[96 + (cm >> 6 * 4 & 0xF)] << 6 * 4;
om |= S[112 + (cm >> 7 * 4 & 0xF)] << 7 * 4;
cm = om << 11 | om >>> 32 - 11;
cm ^= m[1];
m[1] = m[0];
m[0] = cm;
} // </editor-fold>
/**
* Process encrypt/decrypt block with key K using GOST 28147-89
*
* @memberOf GostCipher
* @private
* @instance
* @method process
* @param k {Int32Array} 8x32 bits key
* @param d {Int32Array} 8x8 bits cipher block
* @param ofs {number} offset
*/
function process89(k, d, ofs) // <editor-fold defaultstate="collapsed">
{
ofs = ofs || d.byteOffset;
var s = this.sBox,
m = new Int32Array(d.buffer, ofs, 2);
for (var i = 0; i < 32; i++) {
round(s, m, k[i]);
}
var r = m[0];
m[0] = m[1];
m[1] = r;
} // </editor-fold>
/**
* Process encrypt/decrypt block with key K using GOST R 34.12-15 64bit block
*
* @memberOf GostCipher
* @private
* @instance
* @method process
* @param k {Int32Array} 8x32 bits key
* @param d {Int32Array} 8x8 bits cipher block
* @param ofs {number} offset
*/
function process15(k, d, ofs) // <editor-fold defaultstate="collapsed">
{
ofs = ofs || d.byteOffset;
var s = this.sBox,
m = new Int32Array(d.buffer, ofs, 2),
r = swap32(m[0]);
m[0] = swap32(m[1]);
m[1] = r;
for (var i = 0; i < 32; i++) {
round(s, m, k[i]);
}
m[0] = swap32(m[0]);
m[1] = swap32(m[1]);
} // </editor-fold>
/**
* Key keySchedule algorithm for GOST 28147-89 64bit cipher
*
* @memberOf GostCipher
* @private
* @instance
* @method process
* @param k {Uint8Array} 8 bit key array
* @param e {boolean} true - decrypt
* @returns {Int32Array} keyScheduled 32-bit key
*/
function keySchedule89(k, e) // <editor-fold defaultstate="collapsed">
{
var sch = new Int32Array(32),
key = new Int32Array(buffer(k));
for (var i = 0; i < 8; i++) {
sch[i] = key[i];
}
if (e) {
for (var i = 0; i < 8; i++) {
sch[i + 8] = sch[7 - i];
}
for (var i = 0; i < 8; i++) {
sch[i + 16] = sch[7 - i];
}
} else {
for (var i = 0; i < 8; i++) {
sch[i + 8] = sch[i];
}
for (var i = 0; i < 8; i++) {
sch[i + 16] = sch[i];
}
}
for (var i = 0; i < 8; i++) {
sch[i + 24] = sch[7 - i];
}
return sch;
} // </editor-fold>
/**
* Key keySchedule algorithm for GOST R 34.12-15 64bit cipher
*
* @memberOf GostCipher
* @private
* @instance
* @method process
* @param k {Uint8Array} 8 bit key array
* @param e {boolean} true - decrypt
* @returns {Int32Array} keyScheduled 32-bit key
*/
function keySchedule15(k, e) // <editor-fold defaultstate="collapsed">
{
var sch = new Int32Array(32),
key = new Int32Array(buffer(k));
for (var i = 0; i < 8; i++) {
sch[i] = swap32(key[i]);
}
if (e) {
for (var i = 0; i < 8; i++) {
sch[i + 8] = sch[7 - i];
}
for (var i = 0; i < 8; i++) {
sch[i + 16] = sch[7 - i];
}
} else {
for (var i = 0; i < 8; i++) {
sch[i + 8] = sch[i];
}
for (var i = 0; i < 8; i++) {
sch[i + 16] = sch[i];
}
}
for (var i = 0; i < 8; i++) {
sch[i + 24] = sch[7 - i];
}
return sch;
} // </editor-fold>
/**
* Key schedule for RC2
*
* https://tools.ietf.org/html/rfc2268
*
* @memberOf GostCipher
* @private
* @instance
* @method keySchedule
* @param {Uint8Array} k
* @returns {Uint16Array}
*/
var keyScheduleRC2 = function () // <editor-fold defaultstate="collapsed">
{
// an array of "random" bytes based on the digits of PI = 3.14159...
var PITABLE = new Uint8Array([0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad]);
return function (k) {
var key = new Uint8Array(buffer(k)),
T = Math.min(key.length, 128),
T1 = this.effectiveLength,
T8 = Math.floor((T1 + 7) / 8),
TM = 0xff % Math.pow(2, 8 + T1 - 8 * T8);
var L = new Uint8Array(128),
K = new Uint16Array(L.buffer);
for (var i = 0; i < T; i++) {
L[i] = key[i];
}
for (var i = T; i < 128; i++) {
L[i] = PITABLE[(L[i - 1] + L[i - T]) % 256];
}
L[128 - T8] = PITABLE[L[128 - T8] & TM];
for (var i = 127 - T8; i >= 0; --i) {
L[i] = PITABLE[L[i + 1] ^ L[i + T8]];
}
return K;
};
} // </editor-fold>
();
/**
* RC2 encrypt/decrypt process
*
* https://tools.ietf.org/html/rfc2268
*
* @memberOf GostCipher
* @private
* @instance
* @method round
* @param {CryptoOperationData} k Scheduled key
* @param {CryptoOperationData} d Data
* @param {number} ofs Offsec
* @param {number} e true - decrypt
*/
var processRC2 = function () // <editor-fold defaultstate="collapsed">
{
var K,
j,
R = new Uint16Array(4),
s = new Uint16Array([1, 2, 3, 5]),
reverse;
function rol(R, s) {
return (R << s | R >>> 16 - s) & 0xffff;
}
function ror(R, s) {
return (R >>> s | R << 16 - s) & 0xffff;
}
function mix(i) {
if (reverse) {
R[i] = ror(R[i], s[i]);
R[i] = R[i] - K[j] - (R[(i + 3) % 4] & R[(i + 2) % 4]) - (~R[(i + 3) % 4] & R[(i + 1) % 4]);
j = j - 1;
} else {
R[i] = R[i] + K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + (~R[(i + 3) % 4] & R[(i + 1) % 4]);
j = j + 1;
R[i] = rol(R[i], s[i]);
}
}
function mash(i) {
if (reverse) {
R[i] = R[i] - K[R[(i + 3) % 4] & 63];
} else {
R[i] = R[i] + K[R[(i + 3) % 4] & 63];
}
}
function perform(method, count) {
count = count || 1;
for (var j = 0; j < count; j++) {
if (reverse) {
for (var i = 3; i >= 0; --i) {
method(i);
}
} else {
for (var i = 0; i < 4; i++) {
method(i);
}
}
}
}
return function (k, d, ofs, e) {
reverse = e; // 1. Initialize words R[0], ..., R[3] to contain the 64-bit
// ciphertext value.
R = new Uint16Array(d.buffer, ofs || d.byteOffset, 4); // 2. Expand the key, so that words K[0], ..., K[63] become
// defined.
K = k; // 3. Initialize j to zero (enc) j to 63 (dec).
j = e ? 63 : 0; // 4. Perform five mixing rounds.
perform(mix, 5); // 5. Perform one mashing round.
perform(mash); // 6. Perform six mixing rounds.
perform(mix, 6); // 7. Perform one mashing round.
perform(mash); // 8. Perform five mixing rounds.
perform(mix, 5);
};
} // </editor-fold>
();
/**
* Algorithm name GOST 28147-ECB<br><br>
*
* encryptECB (K, D) is D, encrypted with key k using GOST 28147/GOST R 34.13 in
* "prostaya zamena" (Electronic Codebook, ECB) mode.
* @memberOf GostCipher
* @method encrypt
* @instance
* @param k {CryptoOperationData} 8x32 bit key
* @param d {CryptoOperationData} 8 bits message
* @return {CryptoOperationData} result
*/
function encryptECB(k, d) // <editor-fold defaultstate="collapsed">
{
var p = this.pad(byteArray(d)),
n = this.blockSize,
b = p.byteLength / n,
key = this.keySchedule(k);
for (var i = 0; i < b; i++) {
this.process(key, p, n * i);
}
return p.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-ECB<br><br>
*
* decryptECB (K, D) is D, decrypted with key K using GOST 28147/GOST R 34.13 in
* "prostaya zamena" (Electronic Codebook, ECB) mode.
*
* @memberOf GostCipher
* @method decrypt
* @instance
* @param k {CryptoOperationData} 8x32 bits key
* @param d {CryptoOperationData} 8 bits message
* @return {CryptoOperationData} result
*/
function decryptECB(k, d) // <editor-fold defaultstate="collapsed">
{
var p = cloneArray(d),
n = this.blockSize,
b = p.byteLength / n,
key = this.keySchedule(k, 1);
for (var i = 0; i < b; i++) {
this.process(key, p, n * i, 1);
}
return this.unpad(p).buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CFB<br><br>
*
* encryptCFB (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13
* in "gammirovanie s obratnoj svyaziyu" (Cipher Feedback, CFB) mode, and IV is
* used as the initialization vector.
*
* @memberOf GostCipher
* @method encrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv initial vector
* @return {CryptoOperationData} result
*/
function encryptCFB(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var s = new Uint8Array(iv || this.iv),
c = cloneArray(d),
m = s.length,
t = new Uint8Array(m),
b = this.shiftBits >> 3,
cb = c.length,
r = cb % b,
q = (cb - r) / b,
key = this.keySchedule(k);
for (var i = 0; i < q; i++) {
for (var j = 0; j < m; j++) {
t[j] = s[j];
}
this.process(key, s);
for (var j = 0; j < b; j++) {
c[i * b + j] ^= s[j];
}
for (var j = 0; j < m - b; j++) {
s[j] = t[b + j];
}
for (var j = 0; j < b; j++) {
s[m - b + j] = c[i * b + j];
}
k = this.keyMeshing(k, s, i, key);
}
if (r > 0) {
this.process(key, s);
for (var i = 0; i < r; i++) {
c[q * b + i] ^= s[i];
}
}
return c.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CFB<br><br>
*
* decryptCFB (IV, K, D) is D, decrypted with key K using GOST 28147/GOST R 34.13
* in "gammirovanie s obratnoj svyaziyu po shifrotekstu" (Cipher Feedback, CFB) mode, and IV is
* used as the initialization vector.
*
* @memberOf GostCipher
* @method decrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv initial vector
* @return {CryptoOperationData} result
*/
function decryptCFB(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var s = new Uint8Array(iv || this.iv),
c = cloneArray(d),
m = s.length,
t = new Uint8Array(m),
b = this.shiftBits >> 3,
cb = c.length,
r = cb % b,
q = (cb - r) / b,
key = this.keySchedule(k);
for (var i = 0; i < q; i++) {
for (var j = 0; j < m; j++) {
t[j] = s[j];
}
this.process(key, s);
for (var j = 0; j < b; j++) {
t[j] = c[i * b + j];
c[i * b + j] ^= s[j];
}
for (var j = 0; j < m - b; j++) {
s[j] = t[b + j];
}
for (var j = 0; j < b; j++) {
s[m - b + j] = t[j];
}
k = this.keyMeshing(k, s, i, key);
}
if (r > 0) {
this.process(key, s);
for (var i = 0; i < r; i++) {
c[q * b + i] ^= s[i];
}
}
return c.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-OFB<br><br>
*
* encryptOFB/decryptOFB (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13
* in "gammirovanie s obratnoj svyaziyu po vyhodu" (Output Feedback, OFB) mode, and IV is
* used as the initialization vector.
*
* @memberOf GostCipher
* @method encrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv 8x8 optional bits initial vector
* @return {CryptoOperationData} result
*/
/**
* Algorithm name GOST 28147-OFB<br><br>
*
* encryptOFB/decryptOFB (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13
* in "gammirovanie s obratnoj svyaziyu po vyhodu" (Output Feedback, OFB) mode, and IV is
* used as the initialization vector.
*
* @memberOf GostCipher
* @method decrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv initial vector
* @return {CryptoOperationData} result
*/
function processOFB(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var s = new Uint8Array(iv || this.iv),
c = cloneArray(d),
m = s.length,
t = new Uint8Array(m),
b = this.shiftBits >> 3,
p = new Uint8Array(b),
cb = c.length,
r = cb % b,
q = (cb - r) / b,
key = this.keySchedule(k);
for (var i = 0; i < q; i++) {
for (var j = 0; j < m; j++) {
t[j] = s[j];
}
this.process(key, s);
for (var j = 0; j < b; j++) {
p[j] = s[j];
}
for (var j = 0; j < b; j++) {
c[i * b + j] ^= s[j];
}
for (var j = 0; j < m - b; j++) {
s[j] = t[b + j];
}
for (var j = 0; j < b; j++) {
s[m - b + j] = p[j];
}
k = this.keyMeshing(k, s, i, key);
}
if (r > 0) {
this.process(key, s);
for (var i = 0; i < r; i++) {
c[q * b + i] ^= s[i];
}
}
return c.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CTR<br><br>
*
* encryptCTR/decryptCTR (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13
* in "gammirovanie" (Counter Mode-CTR) mode, and IV is used as the
* initialization vector.
* @memberOf GostCipher
* @method encrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv 8x8 optional bits initial vector
* @return {CryptoOperationData} result
*/
/**
* Algorithm name GOST 28147-CTR<br><br>
*
* encryptCTR/decryptCTR (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13
* in "gammirovanie" (Counter Mode-CTR) mode, and IV is used as the
* initialization vector.
* @memberOf GostCipher
* @method decrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv initial vector
* @return {CryptoOperationData} result
*/
function processCTR89(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var s = new Uint8Array(iv || this.iv),
c = cloneArray(d),
b = this.blockSize,
t = new Int8Array(b),
cb = c.length,
r = cb % b,
q = (cb - r) / b,
key = this.keySchedule(k),
syn = new Int32Array(s.buffer);
this.process(key, s);
for (var i = 0; i < q; i++) {
syn[0] = syn[0] + 0x1010101 & 0xffffffff; // syn[1] = signed(unsigned((syn[1] + 0x1010104) & 0xffffffff) % 0xffffffff);
var tmp = unsigned(syn[1]) + 0x1010104; // Special thanks to Ilya Matveychikov
syn[1] = signed(tmp < 0x100000000 ? tmp : tmp - 0xffffffff);
for (var j = 0; j < b; j++) {
t[j] = s[j];
}
this.process(key, syn);
for (var j = 0; j < b; j++) {
c[i * b + j] ^= s[j];
}
for (var j = 0; j < b; j++) {
s[j] = t[j];
}
k = this.keyMeshing(k, s, i, key);
}
if (r > 0) {
syn[0] = syn[0] + 0x1010101 & 0xffffffff; // syn[1] = signed(unsigned((syn[1] + 0x1010104) & 0xffffffff) % 0xffffffff);
var tmp = unsigned(syn[1]) + 0x1010104; // Special thanks to Ilya Matveychikov
syn[1] = signed(tmp < 0x100000000 ? tmp : tmp - 0xffffffff);
this.process(key, syn);
for (var i = 0; i < r; i++) {
c[q * b + i] ^= s[i];
}
}
return c.buffer;
} // </editor-fold>
function processCTR15(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var c = cloneArray(d),
n = this.blockSize,
b = this.shiftBits >> 3,
cb = c.length,
r = cb % b,
q = (cb - r) / b,
s = new Uint8Array(n),
t = new Int32Array(n),
key = this.keySchedule(k);
s.set(iv || this.iv);
for (var i = 0; i < q; i++) {
for (var j = 0; j < n; j++) {
t[j] = s[j];
}
this.process(key, s);
for (var j = 0; j < b; j++) {
c[b * i + j] ^= s[j];
}
for (var j = 0; j < n; j++) {
s[j] = t[j];
}
for (var j = n - 1; i >= 0; --i) {
if (s[j] > 0xfe) {
s[j] -= 0xfe;
} else {
s[j]++;
break;
}
}
}
if (r > 0) {
this.process(key, s);
for (var j = 0; j < r; j++) {
c[b * q + j] ^= s[j];
}
}
return c.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CBC<br><br>
*
* encryptCBC (IV, K, D) is D, encrypted with key K using GOST 28147/GOST R 34.13
* in "Prostaya zamena s zatsepleniem" (Cipher-Block-Chaining, CBC) mode and IV is used as the initialization
* vector.
*
* @memberOf GostCipher
* @method encrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv initial vector
* @return {CryptoOperationData} result
*/
function encryptCBC(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var s = new Uint8Array(iv || this.iv),
n = this.blockSize,
m = s.length,
c = this.pad(byteArray(d)),
key = this.keySchedule(k);
for (var i = 0, b = c.length / n; i < b; i++) {
for (var j = 0; j < n; j++) {
s[j] ^= c[i * n + j];
}
this.process(key, s);
for (var j = 0; j < n; j++) {
c[i * n + j] = s[j];
}
if (m !== n) {
for (var j = 0; j < m - n; j++) {
s[j] = s[n + j];
}
for (var j = 0; j < n; j++) {
s[j + m - n] = c[i * n + j];
}
}
k = this.keyMeshing(k, s, i, key);
}
return c.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CBC<br><br>
*
* decryptCBC (IV, K, D) is D, decrypted with key K using GOST 28147/GOST R 34.13
* in "Prostaya zamena s zatsepleniem" (Cipher-Block-Chaining, CBC) mode and IV is used as the initialization
* vector.
*
* @memberOf GostCipher
* @method decrypt
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv initial vector
* @return {CryptoOperationData} result
*/
function decryptCBC(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var s = new Uint8Array(iv || this.iv),
n = this.blockSize,
m = s.length,
c = cloneArray(d),
next = new Uint8Array(n),
key = this.keySchedule(k, 1);
for (var i = 0, b = c.length / n; i < b; i++) {
for (var j = 0; j < n; j++) {
next[j] = c[i * n + j];
}
this.process(key, c, i * n, 1);
for (var j = 0; j < n; j++) {
c[i * n + j] ^= s[j];
}
if (m !== n) {
for (var j = 0; j < m - n; j++) {
s[j] = s[n + j];
}
}
for (var j = 0; j < n; j++) {
s[j + m - n] = next[j];
}
k = this.keyMeshing(k, s, i, key, 1);
}
return this.unpad(c).buffer;
} // </editor-fold>
/**
* The generateKey method returns a new generated key.
*
* @memberOf GostCipher
* @method generateKey
* @instance
* @return {CryptoOperationData} result
*/
function generateKey() // <editor-fold defaultstate="collapsed">
{
// Simple generate 256 bit random seed
var k = new Uint8Array(this.keySize);
randomSeed(k);
return k.buffer;
} // </editor-fold>
/**
* makeIMIT (K, D) is the 32-bit result of the GOST 28147/GOST R 34.13 in
* "imitovstavka" (MAC) mode, used with D as plaintext, K as key and IV
* as initialization vector. Note that the standard specifies its use
* in this mode only with an initialization vector of zero.
*
* @memberOf GostCipher
* @method processMAC
* @private
* @instance
* @param {Int32Array} key 8x32 bits key
* @param {Int32Array} s 8x8 sum array
* @param {Uint8Array} d 8 bits array with data
* @return {Uint8Array} result
*/
function processMAC89(key, s, d) // <editor-fold defaultstate="collapsed">
{
var c = zeroPad.call(this, byteArray(d)),
n = this.blockSize,
q = c.length / n,
sBox = this.sBox,
sum = new Int32Array(s.buffer);
for (var i = 0; i < q; i++) {
for (var j = 0; j < n; j++) {
s[j] ^= c[i * n + j];
}
for (var j = 0; j < 16; j++) {
// 1-16 steps
round(sBox, sum, key[j]);
}
}
} // </editor-fold>
function processKeyMAC15(s) // <editor-fold defaultstate="collapsed">
{
var t = 0,
n = s.length;
for (var i = n - 1; i >= 0; --i) {
var t1 = s[i] >>> 7;
s[i] = s[i] << 1 & 0xff | t;
t = t1;
}
if (t !== 0) {
if (n === 16) s[15] ^= 0x87;else s[7] ^= 0x1b;
}
} // </editor-fold>
function processMAC15(key, s, d) // <editor-fold defaultstate="collapsed">
{
var n = this.blockSize,
sBox = this.sBox,
c = byteArray(d),
r = new Uint8Array(n); // R
this.process(key, r); // K1
processKeyMAC15(r);
if (d.byteLength % n !== 0) {
c = bitPad.call(this, byteArray(d)); // K2
processKeyMAC15(r);
}
for (var i = 0, q = c.length / n; i < q; i++) {
for (var j = 0; j < n; j++) {
s[j] ^= c[i * n + j];
}
if (i === q - 1) {
// Last block
for (var j = 0; j < n; j++) {
s[j] ^= r[j];
}
}
this.process(key, s);
}
} // </editor-fold>
/**
* signMAC (K, D, IV) is the 32-bit result of the GOST 28147/GOST R 34.13 in
* "imitovstavka" (MAC) mode, used with D as plaintext, K as key and IV
* as initialization vector. Note that the standard specifies its use
* in this mode only with an initialization vector of zero.
*
* @memberOf GostCipher
* @method sign
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv initial vector
* @return {CryptoOperationData} result
*/
function signMAC(k, d, iv) // <editor-fold defaultstate="collapsed">
{
var key = this.keySchedule(k),
s = new Uint8Array(iv || this.iv),
m = Math.ceil(this.macLength >> 3) || this.blockSize >> 1;
this.processMAC(key, s, d);
var mac = new Uint8Array(m); // mac size
mac.set(new Uint8Array(s.buffer, 0, m));
return mac.buffer;
} // </editor-fold>
/**
* verifyMAC (K, M, D, IV) the 32-bit result verification of the GOST 28147/GOST R 34.13 in
* "imitovstavka" (MAC) mode, used with D as plaintext, K as key and IV
* as initialization vector. Note that the standard specifies its use
* in this mode only with an initialization vector of zero.
*
* @memberOf GostCipher
* @method verify
* @instance
* @param {CryptoOperationData} k 8x32 bits key
* @param {CryptoOperationData} m 8 bits array with signature
* @param {CryptoOperationData} d 8 bits array with data
* @param {CryptoOperationData} iv 8x8 optional bits initial vector
* @return {boolen} MAC verified = true
*/
function verifyMAC(k, m, d, iv) // <editor-fold defaultstate="collapsed">
{
var mac = new Uint8Array(signMAC.call(this, k, d, iv)),
test = byteArray(m);
if (mac.length !== test.length) return false;
for (var i = 0, n = mac.length; i < n; i++) {
if (mac[i] !== test[i]) return false;
}
return true;
} // </editor-fold>
/**
* Algorithm name GOST 28147-KW<br><br>
*
* This algorithm encrypts GOST 28147-89 CEK with a GOST 28147/GOST R 34.13 KEK.
* Ref. rfc4357 6.1 GOST 28147-89 Key Wrap
* Note: This algorithm MUST NOT be used with a KEK produced by VKO GOST
* R 34.10-94, because such a KEK is constant for every sender-recipient
* pair. Encrypting many different content encryption keys on the same
* constant KEK may reveal that KEK.
*
* @memberOf GostCipher
* @method wrapKey
* @instance
* @param {CryptoOperationData} kek Key encryption key
* @param {CryptoOperationData} cek Content encryption key
* @returns {CryptoOperationData} Encrypted cek
*/
function wrapKeyGOST(kek, cek) // <editor-fold defaultstate="collapsed">
{
var n = this.blockSize,
k = this.keySize,
len = k + (n >> 1); // 1) For a unique symmetric KEK, generate 8 octets at random and call
// the result UKM. For a KEK, produced by VKO GOST R 34.10-2001, use
// the UKM that was used for key derivation.
if (!this.ukm) throw new DataError('UKM must be defined');
var ukm = new Uint8Array(this.ukm); // 2) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK, CEK).
// Call the result CEK_MAC.
var mac = signMAC.call(this, kek, cek, ukm); // 3) Encrypt the CEK in ECB mode using the KEK. Call the ciphertext CEK_ENC.
var enc = encryptECB.call(this, kek, cek); // 4) The wrapped content-encryption key is (UKM | CEK_ENC | CEK_MAC).
var r = new Uint8Array(len);
r.set(new Uint8Array(enc), 0);
r.set(new Uint8Array(mac), k);
return r.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-KW<br><br>
*
* This algorithm decrypts GOST 28147-89 CEK with a GOST 28147 KEK.
* Ref. rfc4357 6.2 GOST 28147-89 Key Unwrap
*
* @memberOf GostCipher
* @method unwrapKey
* @instance
* @param {type} kek Key encryption key
* @param {type} data Content encryption key
* @return {CryptoOperationData} result
*/
function unwrapKeyGOST(kek, data) // <editor-fold defaultstate="collapsed">
{
var n = this.blockSize,
k = this.keySize,
len = k + (n >> 1); // 1) If the wrapped content-encryption key is not 44 octets, then error.
var d = buffer(data);
if (d.byteLength !== len) throw new DataError('Wrapping key size must be ' + len + ' bytes'); // 2) Decompose the wrapped content-encryption key into UKM, CEK_ENC, and CEK_MAC.
// UKM is the most significant (first) 8 octets. CEK_ENC is next 32 octets,
// and CEK_MAC is the least significant (last) 4 octets.
if (!this.ukm) throw new DataError('UKM must be defined');
var ukm = new Uint8Array(this.ukm),
enc = new Uint8Array(d, 0, k),
mac = new Uint8Array(d, k, n >> 1); // 3) Decrypt CEK_ENC in ECB mode using the KEK. Call the output CEK.
var cek = decryptECB.call(this, kek, enc); // 4) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK, CEK),
// compare the result with CEK_MAC. If they are not equal, then error.
var check = verifyMAC.call(this, kek, mac, cek, ukm);
if (!check) throw new DataError('Error verify MAC of wrapping key');
return cek;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CPKW<br><br>
*
* Given a random 64-bit UKM and a GOST 28147 key K, this algorithm
* creates a new GOST 28147-89 key K(UKM).
* Ref. rfc4357 6.3 CryptoPro KEK Diversification Algorithm
*
* @memberOf GostCipher
* @method diversify
* @instance
* @private
* @param {CryptoOperationData} kek Key encryption key
* @param {CryptoOperationData} ukm Random generated value
* @returns {CryptoOperationData} Diversified kek
*/
function diversifyKEK(kek, ukm) // <editor-fold defaultstate="collapsed">
{
var n = this.blockSize; // 1) Let K[0] = K;
var k = intArray(kek); // 2) UKM is split into components a[i,j]:
// UKM = a[0]|..|a[7] (a[i] - byte, a[i,0]..a[i,7] - it’s bits)
var a = [];
for (var i = 0; i < n; i++) {
a[i] = [];
for (var j = 0; j < 8; j++) {
a[i][j] = ukm[i] >>> j & 0x1;
}
} // 3) Let i be 0.
// 4) K[1]..K[8] are calculated by repeating the following algorithm
// eight times:
for (var i = 0; i < n; i++) {
// A) K[i] is split into components k[i,j]:
// K[i] = k[i,0]|k[i,1]|..|k[i,7] (k[i,j] - 32-bit integer)
// B) Vector S[i] is calculated:
// S[i] = ((a[i,0]*k[i,0] + ... + a[i,7]*k[i,7]) mod 2^32) |
// (((~a[i,0])*k[i,0] + ... + (~a[i,7])*k[i,7]) mod 2^32);
var s = new Int32Array(2);
for (var j = 0; j < 8; j++) {
if (a[i][j]) s[0] = s[0] + k[j] & 0xffffffff;else s[1] = s[1] + k[j] & 0xffffffff;
} // C) K[i+1] = encryptCFB (S[i], K[i], K[i])
var iv = new Uint8Array(s.buffer);
k = new Int32Array(encryptCFB.call(this, k, k, iv)); // D) i = i + 1
} // 5) Let K(UKM) be K[8].
return k;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CPKW<br><br>
*
* This algorithm encrypts GOST 28147-89 CEK with a GOST 28147 KEK.
* It can be used with any KEK (e.g., produced by VKO GOST R 34.10-94 or
* VKO GOST R 34.10-2001) because a unique UKM is used to diversify the KEK.
* Ref. rfc4357 6.3 CryptoPro Key Wrap
*
* @memberOf GostCipher
* @method wrapKey
* @instance
* @param {CryptoOperationData} kek Key encryption key
* @param {CryptoOperationData} cek Content encryption key
* @returns {CryptoOperationData} Encrypted cek
*/
function wrapKeyCP(kek, cek) // <editor-fold defaultstate="collapsed">
{
var n = this.blockSize,
k = this.keySize,
len = k + (n >> 1); // 1) For a unique symmetric KEK or a KEK produced by VKO GOST R
// 34.10-94, generate 8 octets at random. Call the result UKM. For
// a KEK, produced by VKO GOST R 34.10-2001, use the UKM that was
// used for key derivation.
if (!this.ukm) throw new DataError('UKM must be defined');
var ukm = new Uint8Array(this.ukm); // 2) Diversify KEK, using the CryptoPro KEK Diversification Algorithm,
// described in Section 6.5. Call the result KEK(UKM).
var dek = diversifyKEK.call(this, kek, ukm); // 3) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK(UKM),
// CEK). Call the result CEK_MAC.
var mac = signMAC.call(this, dek, cek, ukm); // 4) Encrypt CEK in ECB mode using KEK(UKM). Call the ciphertext
// CEK_ENC.
var enc = encryptECB.call(this, dek, cek); // 5) The wrapped content-encryption key is (UKM | CEK_ENC | CEK_MAC).
var r = new Uint8Array(len);
r.set(new Uint8Array(enc), 0);
r.set(new Uint8Array(mac), k);
return r.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-CPKW<br><br>
*
* This algorithm encrypts GOST 28147-89 CEK with a GOST 28147 KEK.
* Ref. rfc4357 6.4 CryptoPro Key Unwrap
*
* @memberOf GostCipher
* @method unwrapKey
* @instance
* @param {CryptoOperationData} kek Key encryption key
* @param {CryptoOperationData} data Encrypted content encryption keu
* @return {CryptoOperationData} result Decrypted content encryption keu
*/
function unwrapKeyCP(kek, data) // <editor-fold defaultstate="collapsed">
{
var n = this.blockSize,
k = this.keySize,
len = k + (n >> 1); // 1) If the wrapped content-encryption key is not 44 octets, then error.
var d = buffer(data);
if (d.byteLength !== len) throw new DataError('Wrapping key size must be ' + len + ' bytes'); // 2) Decompose the wrapped content-encryption key into UKM, CEK_ENC,
// and CEK_MAC. UKM is the most significant (first) 8 octets.
// CEK_ENC is next 32 octets, and CEK_MAC is the least significant
// (last) 4 octets.
if (!this.ukm) throw new DataError('UKM must be defined');
var ukm = new Uint8Array(this.ukm),
enc = new Uint8Array(d, 0, k),
mac = new Uint8Array(d, k, n >> 1); // 3) Diversify KEK using the CryptoPro KEK Diversification Algorithm,
// described in section 6.5. Call the result KEK(UKM).
var dek = diversifyKEK.call(this, kek, ukm); // 4) Decrypt CEK_ENC in ECB mode using KEK(UKM). Call the output CEK.
var cek = decryptECB.call(this, dek, enc); // 5) Compute a 4-byte checksum value, GOST 28147IMIT (UKM, KEK(UKM),
// CEK), compare the result with CEK_MAC. If they are not equal,
// then it is an error.
var check = verifyMAC.call(this, dek, mac, cek, ukm);
if (!check) throw new DataError('Error verify MAC of wrapping key');
return cek;
} // </editor-fold>
/**
* SignalCom master key packing algorithm
*
* kek stored in 3 files - kek.opq, mk.db3, masks.db3
* kek.opq - always 36 bytes length = 32 bytes encrypted kek + 4 bytes mac of decrypted kek
* mk.db3 - 6 bytes header (1 byte magic code 0x22 + 1 byte count of masks + 4 bytes mac of
* xor summarizing masks value) + attached masks
* masks.db3 - detached masks.
* Total length of attached + detached masks = 32 bits * count of masks
* Default value of count 8 = (7 attached + 1 detached). But really no reason for such
* separation - all masks xor summarizing - order is not matter.
* Content of file rand.opq can used as ukm. Don't forget change file content after using.
*
* For usb-token files has names:
* a001 - mk.db3, b001 - masks.db3, c001 - kek.opq, d001 - rand.opq
* For windows registry
* 00000001 - mk.db3, 00000002 - masks.db3, 00000003 - key.opq, 00000004 - rand.opq,
* 00000006 - keys\00000001.key, 0000000A - certificate
*
* @memberOf GostCipher
* @method packKey
* @instance
* @private
* @param {CryptoOperationData} unpacked - clear main key 32 bytes
* @param {CryptoOperationData} ukm - random vector for packing - 32 bytes * (count of masks - 1)
* @returns {CryptoOperationData} packed master key - concatination of mk.db3 + masks.db3
*/
function packKeySC(unpacked, ukm) // <editor-fold defaultstate="collapsed">
{
var m = this.blockSize >> 1,
k = this.keySize;
var mcount = 8;
var key = new Uint8Array(buffer(unpacked));
if (key.byteLength !== k) throw new DataError('Wrong cleartext size ' + key.byteLength + ' bytes'); // Check or generate UKM
ukm = ukm || this.ukm;
if (ukm) {
ukm = new Uint8Array(buffer(ukm));
if (ukm.byteLength > 0 && ukm.byteLength % k === 0) mcount = ukm.byteLength / k + 1;else throw new DataError('Wrong rand size ' + ukm.byteLength + ' bytes');
} else randomSeed(ukm = new Uint8Array((mcount - 1) * k)); // Output array
var d = new Uint8Array(mcount * k + m + 2),
b = d.buffer; // Calculate MAC
var zero32 = new Uint8Array(k);
var mac = signMAC.call(this, key, zero32);
d[0] = 0x22; // Magic code
d[1] = mcount; // Count of masks
d.set(new Uint8Array(mac), 2);
d.set(ukm, k + m + 2);
for (var i = 1; i < mcount; i++) {
var mask = new Uint8Array(b, 2 + m + k * i);
for (var j = 0; j < k; j++) {
key[j] ^= mask[j];
}
}
d.set(key, m + 2);
return d.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-SCKW<br><br>
*
* SignalCom master key unpacking algorithm
*
* @memberOf GostCipher
* @method unpackKey
* @instance
* @private
* @param {CryptoOperationData} packed - concatination of mk.db3 + masks.db3
* @returns {CryptoOperationData} unpacked master key
*/
function unpackKeySC(packed) // <editor-fold defaultstate="collapsed">
{
var m = this.blockSize >> 1,
k = this.keySize;
var b = buffer(packed); // Unpack master key
var magic = new Uint8Array(b, 0, 1)[0];
if (magic !== 0x22) throw new DataError('Invalid magic number');
var mcount = new Uint8Array(b, 1, 1)[0];
var mac = new Uint8Array(b, 2, m); // MAC for summarized mask
// Compute packKey xor summing for all masks
var key = new Uint8Array(k);
for (var i = 0; i < mcount; i++) {
var mask = new Uint8Array(b, 2 + m + k * i, k);
for (var j = 0; j < k; j++) {
key[j] ^= mask[j];
}
} // Test MAC for packKey with default sBox on zero 32 bytes array
var zero32 = new Uint8Array(k);
var test = verifyMAC.call(this, key, mac, zero32);
if (!test) {
// Try to use different sBoxes
var names = ['E-A', 'E-B', 'E-C', 'E-D', 'E-SC'];
for (var i = 0, n = names.length; i < n; i++) {
this.sBox = sBoxes[names[i]];
test = verifyMAC.call(this, key, mac, zero32);
if (test) break;
}
}
if (!test) throw new DataError('Invalid main key MAC');
return key.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-SCKW<br><br>
*
* SignalCom Key Wrapping algorithm
*
* @memberOf GostCipher
* @method wrapKey
* @instance
* @param {CryptoOperationData} kek - clear kek or concatination of mk.db3 + masks.db3
* @param {CryptoOperationData} cek - key for wrapping
* @returns {CryptoOperationData} wrapped key - file kek.opq
*/
function wrapKeySC(kek, cek) // <editor-fold defaultstate="collapsed">
{
var m = this.blockSize >> 1,
n = this.keySize;
var k = buffer(kek);
var c = buffer(cek);
if (k.byteLength !== n) k = unpackKeySC.call(this, k);
var enc = encryptECB.call(this, k, c);
var mac = signMAC.call(this, k, c);
var d = new Uint8Array(m + n);
d.set(new Uint8Array(enc), 0);
d.set(new Uint8Array(mac), n);
return d.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-SCKW<br><br>
*
* SignalCom Key UnWrapping algorithm
*
* @memberOf GostCipher
* @method unwrapKey
* @instance
* @param {CryptoOperationData} kek - concatination of files mk.db3 + masks.db3 or clear kek
* @param {CryptoOperationData} cek - wrapping key - file kek.opq
* @return {CryptoOperationData} result
*/
function unwrapKeySC(kek, cek) // <editor-fold defaultstate="collapsed">
{
var m = this.blockSize >> 1,
n = this.keySize;
var k = buffer(kek);
var c = buffer(cek);
if (k.byteLength !== n) k = unpackKeySC.call(this, k);
var enc = new Uint8Array(c, 0, n); // Encrypted kek
var mac = new Uint8Array(c, n, m); // MAC for clear kek
var d = decryptECB.call(this, k, enc);
if (!verifyMAC.call(this, k, mac, d)) throw new DataError('Invalid key MAC');
return d;
} // </editor-fold>
/**
* Algorithm name GOST 28147-SCKW<br><br>
*
* SignalCom master key generation for wrapping
*
* @memberOf GostCipher
* @method generateKey
* @instance
* @return {CryptoOperationData} result
*/
function generateWrappingKeySC() // <editor-fold defaultstate="collapsed">
{
return packKeySC.call(this, generateKey.call(this));
} // </editor-fold>
function maskKey(mask, key, inverse, keySize) // <editor-fold defaultstate="collapsed">
{
var k = keySize / 4,
m32 = new Int32Array(buffer(mask)),
k32 = new Int32Array(buffer(key)),
r32 = new Int32Array(k);
if (inverse) for (var i = 0; i < k; i++) {
r32[i] = k32[i] + m32[i] & 0xffffffff;
} else for (var i = 0; i < k; i++) {
r32[i] = k32[i] - m32[i] & 0xffffffff;
}
return r32.buffer;
} // </editor-fold>
/**
* Algorithm name GOST 28147-MASK<br><br>
*
* This algorithm wrap key mask
*
* @memberOf GostCipher
* @method wrapKey
* @instance
* @param {CryptoOperationData} mask The mask
* @param {CryptoOperationData} key The key
* @returns {CryptoOperationData} The masked key
*/
function wrapKeyMask(mask, key) // <editor-fold defaultstate="collapsed">
{
return maskKey(mask, key, this.procreator === 'VN', this.keySize);
} // </editor-fold>
/**
* Algorithm name GOST 28147-CPKW<br><br>
*
* This algorithm unwrap key mask
*
* @memberOf GostCipher
* @method unwrapKey
* @instance
* @param {CryptoOperationData} mask The mask
* @param {CryptoOperationData} key The masked key
* @return {CryptoOperationData} result The key
*/
function unwrapKeyMask(mask, key) // <editor-fold defaultstate="collapsed">
{
return maskKey(mask, key, this.procreator !== 'VN', this.keySize);
} // </editor-fold>
/**
* Algorithm name GOST 28147-CPKM<br><br>
*
* Key meshing in according to rfc4357 2.3.2. CryptoPro Key Meshing
*
* @memberOf GostCipher
* @method keyMeshing
* @instance
* @private
* @param {(Uint8Array|CryptoOperationData)} k 8x8 bit key
* @param {Uint8Array} s 8x8 bit sync (iv)
* @param {Integer} i block index
* @param {Int32Array} key 8x32 bit key schedule
* @param {boolean} e true - decrypt
* @returns CryptoOperationData next 8x8 bit key
*/
function keyMeshingCP(k, s, i, key, e) // <editor-fold defaultstate="collapsed">
{
if ((i + 1) * this.blockSize % 1024 === 0) {
// every 1024 octets
// K[i+1] = decryptECB (K[i], C);
k = decryptECB.call(this, k, C); // IV0[i+1] = encryptECB (K[i+1],IVn[i])
s.set(new Uint8Array(encryptECB.call(this, k, s))); // restore key schedule
key.set(this.keySchedule(k, e));
}
return k;
} // </editor-fold>
/**
* Null Key Meshing in according to rfc4357 2.3.1
*
* @memberOf GostCipher
* @method keyMeshing
* @instance
* @private
* @param {(Uint8Array|CryptoOperationData)} k 8x8 bit key
*/
function noKeyMeshing(k) // <editor-fold defaultstate="collapsed">
{
return k;
} // </editor-fold>
/**
* Algorithm name GOST 28147-NoPadding<br><br>
*
* No padding.
*
* @memberOf GostCipher
* @method padding
* @instance
* @private
* @param {Uint8Array} d array with source data
* @returns {Uint8Array} result
*/
function noPad(d) // <editor-fold defaultstate="collapsed">
{
return new Uint8Array(d);
} // </editor-fold>
/**
* Algorithm name GOST 28147-PKCS5Padding<br><br>
*
* PKCS#5 padding: 8-x remaining bytes are filled with the value of
* 8-x. If there’s no incomplete block, one extra block filled with
* value 8 is added
*
* @memberOf GostCipher
* @method padding
* @instance
* @private
* @param {Uint8Array} d array with source data
* @returns {Uint8Array} result
*/
function pkcs5Pad(d) // <editor-fold defaultstate="collapsed">
{
var n = d.byteLength,
nb = this.blockSize,
q = nb - n % nb,
m = Math.ceil((n + 1) / nb) * nb,
r = new Uint8Array(m);
r.set(d);
for (var i = n; i < m; i++) {
r[i] = q;
}
return r;
} // </editor-fold>
function pkcs5Unpad(d) // <editor-fold defaultstate="collapsed">
{
var m = d.byteLength,
nb = this.blockSize,
q = d[m - 1],
n = m - q;
if (q > nb) throw DataError('Invalid padding');
var r = new Uint8Array(n);
if (n > 0) r.set(new Uint8Array(d.buffer, 0, n));
return r;
} // </editor-fold>
/**
* Algorithm name GOST 28147-ZeroPadding<br><br>
*
* Zero padding: 8-x remaining bytes are filled with zero
*
* @memberOf GostCipher
* @method padding
* @instance
* @private
* @param {Uint8Array} d array with source data
* @returns {Uint8Array} result
*/
function zeroPad(d) // <editor-fold defaultstate="collapsed">
{
var n = d.byteLength,
nb = this.blockSize,
m = Math.ceil(n / nb) * nb,
r = new Uint8Array(m);
r.set(d);
for (var i = n; i < m; i++) {
r[i] = 0;
}
return r;
} // </editor-fold>
/**
* Algorithm name GOST 28147-BitPadding<br><br>
*
* Bit padding: P* = P || 1 || 000...0 If there’s no incomplete block,
* one extra block filled with 1 || 000...0
*
* @memberOf GostCipher
* @method padding
* @instance
* @private
* @param {Uint8Array} d array with source data
* @returns {Uint8Array} result
*/
function bitPad(d) // <editor-fold defaultstate="collapsed">
{
var n = d.byteLength,
nb = this.blockSize,
m = Math.ceil((n + 1) / nb) * nb,
r = new Uint8Array(m);
r.set(d);
r[n] = 1;
for (var i = n + 1; i < m; i++) {
r[i] = 0;
}
return r;
} // </editor-fold>
function bitUnpad(d) // <editor-fold defaultstate="collapsed">
{
var m = d.byteLength,
n = m;
while (n > 1 && d[n - 1] === 0) {
n--;
}
if (d[n - 1] !== 1) throw DataError('Invalid padding');
n--;
var r = new Uint8Array(n);
if (n > 0) r.set(new Uint8Array(d.buffer, 0, n));
return r;
} // </editor-fold>
/**
* Algorithm name GOST 28147-RandomPadding<br><br>
*
* Random padding: 8-x remaining bytes of the last block are set to
* random.
*
* @memberOf GostCipher
* @method padding
* @instance
* @private
* @param {Uint8Array} d array with source data
* @returns {Uint8Array} result
*/
function randomPad(d) // <editor-fold defaultstate="collapsed">
{
var n = d.byteLength,
nb = this.blockSize,
q = nb - n % nb,
m = Math.ceil(n / nb) * nb,
r = new Uint8Array(m),
e = new Uint8Array(r.buffer, n, q);
r.set(d);
randomSeed(e);
return r;
} // </editor-fold>
/**
* GOST 28147-89 Encryption Algorithm<br><br>
*
* References {@link http://tools.ietf.org/html/rfc5830}<br><br>
*
* When keys and initialization vectors are converted to/from byte arrays,
* little-endian byte order is assumed.<br><br>
*
* Normalized algorithm identifier common parameters:
*
* <ul>
* <li><b>name</b> Algorithm name 'GOST 28147' or 'GOST R 34.12'</li>
* <li><b>version</b> Algorithm version, number
* <ul>
* <li><b>1989</b> Current version of standard</li>
* <li><b>2015</b> New draft version of standard</li>
* </ul>
* </li>
* <li><b>length</b> Block length
* <ul>
* <li><b>64</b> 64 bits length (default)</li>
* <li><b>128</b> 128 bits length (only for version 2015)</li>
* </ul>
* </li>
* <li><b>mode</b> Algorithm mode, string
* <ul>
* <li><b>ES</b> Encryption mode (default)</li>
* <li><b>MAC</b> "imitovstavka" (MAC) mode</li>
* <li><b>KW</b> Key wrapping mode</li>
* </ul>
* </li>
* <li><b>sBox</b> Paramset sBox for GOST 28147-89, string. Used only if version = 1989</li>
* </ul>
*
* Supported algorithms, modes and parameters:
*
* <ul>
* <li>Encript/Decrypt mode (ES)
* <ul>
* <li><b>block</b> Block mode, string. Default ECB</li>
* <li><b>keyMeshing</b> Key meshing mode, string. Default NO</li>
* <li><b>padding</b> Padding mode, string. Default NO for CFB and CTR modes, or ZERO for others</li>
* <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
* </ul>
* </li>
* <li>Sign/Verify mode (MAC)
* <ul>
* <li><b>macLength</b> Length of mac in bits (default - 32 bits)</li>
* <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
* </ul>
* </li>
* <li>Wrap/Unwrap key mode (KW)
* <ul>
* <li><b>keyWrapping</b> Mode of keywrapping, string. Default NO - standard GOST key wrapping</li>
* <li><b>ukm</b> {@link CryptoOperationData} User key material. Default - random generated value</li>
* </ul>
* </li>
* </ul>
*
* Supported paramters values:
*
* <ul>
* <li>Block modes (parameter 'block')
* <ul>
* <li><b>ECB</b> "prostaya zamena" (ECB) mode (default)</li>
* <li><b>CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
* <li><b>OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
* <li><b>CTR</b> "gammirovanie" (counter) mode</li>
* <li><b>CBC</b> Cipher-Block-Chaining (CBC) mode</li>
* </ul>
* </li>
* <li>Key meshing modes (parameter 'keyMeshing')
* <ul>
* <li><b>NO</b> No key wrapping (default)</li>
* <li><b>CP</b> CryptoPor Key key meshing</li>
* </ul>
* </li>
* <li>Padding modes (parameter 'padding')
* <ul>
* <li><b>NO</b> No padding only for CFB, OFB and CTR modes</li>
* <li><b>PKCS5</b> PKCS#5 padding mode</li>
* <li><b>ZERO</b> Zero bits padding mode</li>
* <li><b>RANDOM</b> Random bits padding mode</li>
* <li><b>BIT</b> One bit padding mode</li>
* </ul>
* </li>
* <li>Wrapping key modes (parameter 'keyWrapping')
* <ul>
* <li><b>NO</b> Ref. rfc4357 6.1 GOST 28147-89 Key wrapping</li>
* <li><b>CP</b> CryptoPro Key wrapping mode</li>
* <li><b>SC</b> SignalCom Key wrapping mode</li>
* </ul>
* </li>
* </ul>
*
* @class GostCipher
* @param {AlgorithmIndentifier} algorithm WebCryptoAPI algorithm identifier
*/
function GostCipher(algorithm) // <editor-fold defaultstate="collapsed">
{
// Check little endian support
if (!littleEndian) throw new NotSupportedError('Big endian platform not supported');
algorithm = algorithm || {};
this.keySize = 32;
this.blockLength = algorithm.length || 64;
this.blockSize = this.blockLength >> 3;
this.name = (algorithm.name || (algorithm.version === 1 ? 'RC2' : algorithm.version === 1989 ? 'GOST 28147' : 'GOST R 34.12')) + (algorithm.version > 4 ? '-' + (algorithm.version || 1989) % 100 : '') + '-' + (this.blockLength === 64 ? '' : this.blockLength + '-') + (algorithm.mode === 'MAC' ? 'MAC-' + (algorithm.macLength || this.blockLength >> 1) : algorithm.mode === 'KW' || algorithm.keyWrapping ? ((algorithm.keyWrapping || 'NO') !== 'NO' ? algorithm.keyWrapping : '') + 'KW' : (algorithm.block || 'ECB') + ((algorithm.block === 'CFB' || algorithm.block === 'OFB' || algorithm.block === 'CTR' && algorithm.version === 2015) && algorithm.shiftBits && algorithm.shiftBits !== this.blockLength ? '-' + algorithm.shiftBits : '') + (algorithm.padding ? '-' + (algorithm.padding || (algorithm.block === 'CTR' || algorithm.block === 'CFB' || algorithm.block === 'OFB' ? 'NO' : 'ZERO')) + 'PADDING' : '') + ((algorithm.keyMeshing || 'NO') !== 'NO' ? '-CPKEYMESHING' : '')) + (algorithm.procreator ? '/' + algorithm.procreator : '') + (typeof algorithm.sBox === 'string' ? '/' + algorithm.sBox : ''); // Algorithm procreator
this.procreator = algorithm.procreator;
switch (algorithm.version || 1989) {
case 1:
this.process = processRC2;
this.keySchedule = keyScheduleRC2;
this.blockLength = 64;
this.effectiveLength = algorithm.length || 32;
this.keySize = 8 * Math.ceil(this.effectiveLength / 8); // Max 128
this.blockSize = this.blockLength >> 3;
break;
case 2015:
this.version = 2015;
if (this.blockLength === 64) {
this.process = process15;
this.keySchedule = keySchedule15;
} else if (this.blockLength === 128) {
this.process = process128;
this.keySchedule = keySchedule128;
} else throw new DataError('Invalid block length');
this.processMAC = processMAC15;
break;
case 1989:
this.version = 1989;
this.process = process89;
this.processMAC = processMAC89;
this.keySchedule = keySchedule89;
if (this.blockLength !== 64) throw new DataError('Invalid block length');
break;
default:
throw new NotSupportedError('Algorithm version ' + algorithm.version + ' not supported');
}
switch (algorithm.mode || algorithm.keyWrapping && 'KW' || 'ES') {
case 'ES':
switch (algorithm.block || 'ECB') {
case 'ECB':
this.encrypt = encryptECB;
this.decrypt = decryptECB;
break;
case 'CTR':
if (this.version === 1989) {
this.encrypt = processCTR89;
this.decrypt = processCTR89;
} else {
this.encrypt = processCTR15;
this.decrypt = processCTR15;
this.shiftBits = algorithm.shiftBits || this.blockLength;
}
break;
case 'CBC':
this.encrypt = encryptCBC;
this.decrypt = decryptCBC;
break;
case 'CFB':
this.encrypt = encryptCFB;
this.decrypt = decryptCFB;
this.shiftBits = algorithm.shiftBits || this.blockLength;
break;
case 'OFB':
this.encrypt = processOFB;
this.decrypt = processOFB;
this.shiftBits = algorithm.shiftBits || this.blockLength;
break;
default:
throw new NotSupportedError('Block mode ' + algorithm.block + ' not supported');
}
switch (algorithm.keyMeshing) {
case 'CP':
this.keyMeshing = keyMeshingCP;
break;
default:
this.keyMeshing = noKeyMeshing;
}
if (this.encrypt === encryptECB || this.encrypt === encryptCBC) {
switch (algorithm.padding) {
case 'PKCS5P':
this.pad = pkcs5Pad;
this.unpad = pkcs5Unpad;
break;
case 'RANDOM':
this.pad = randomPad;
this.unpad = noPad;
break;
case 'BIT':
this.pad = bitPad;
this.unpad = bitUnpad;
break;
default:
this.pad = zeroPad;
this.unpad = noPad;
}
} else {
this.pad = noPad;
this.unpad = noPad;
}
this.generateKey = generateKey;
break;
case 'MAC':
this.sign = signMAC;
this.verify = verifyMAC;
this.generateKey = generateKey;
this.macLength = algorithm.macLength || this.blockLength >> 1;
this.pad = noPad;
this.unpad = noPad;
this.keyMeshing = noKeyMeshing;
break;
case 'KW':
this.pad = noPad;
this.unpad = noPad;
this.keyMeshing = noKeyMeshing;
switch (algorithm.keyWrapping) {
case 'CP':
this.wrapKey = wrapKeyCP;
this.unwrapKey = unwrapKeyCP;
this.generateKey = generateKey;
this.shiftBits = algorithm.shiftBits || this.blockLength;
break;
case 'SC':
this.wrapKey = wrapKeySC;
this.unwrapKey = unwrapKeySC;
this.generateKey = generateWrappingKeySC;
break;
default:
this.wrapKey = wrapKeyGOST;
this.unwrapKey = unwrapKeyGOST;
this.generateKey = generateKey;
}
break;
case 'MASK':
this.wrapKey = wrapKeyMask;
this.unwrapKey = unwrapKeyMask;
this.generateKey = generateKey;
break;
default:
throw new NotSupportedError('Mode ' + algorithm.mode + ' not supported');
} // Define sBox parameter
var sBox = algorithm.sBox,
sBoxName;
if (!sBox) sBox = this.version === 2015 ? sBoxes['E-Z'] : this.procreator === 'SC' ? sBoxes['E-SC'] : sBoxes['E-A'];else if (typeof sBox === 'string') {
sBoxName = sBox.toUpperCase();
sBox = sBoxes[sBoxName];
if (!sBox) throw new SyntaxError('Unknown sBox name: ' + algorithm.sBox);
} else if (!sBox.length || sBox.length !== sBoxes['E-Z'].length) throw new SyntaxError('Length of sBox must be ' + sBoxes['E-Z'].length);
this.sBox = sBox; // Initial vector
if (algorithm.iv) {
this.iv = new Uint8Array(algorithm.iv);
if (this.iv.byteLength !== this.blockSize && this.version === 1989) throw new SyntaxError('Length of iv must be ' + this.blockLength + ' bits');else if (this.iv.byteLength !== this.blockSize >> 1 && this.encrypt === processCTR15) throw new SyntaxError('Length of iv must be ' + this.blockLength >> 1 + ' bits');else if (this.iv.byteLength % this.blockSize !== 0 && this.encrypt !== processCTR15) throw new SyntaxError('Length of iv must be a multiple of ' + this.blockLength + ' bits');
} else this.iv = this.blockLength === 128 ? defaultIV128 : defaultIV; // User key material
if (algorithm.ukm) {
this.ukm = new Uint8Array(algorithm.ukm);
if (this.ukm.byteLength * 8 !== this.blockLength) throw new SyntaxError('Length of ukm must be ' + this.blockLength + ' bits');
}
} // </editor-fold>
return GostCipher;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostRandom":114}],109:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file Coding algorithms: Base64, Hex, Int16, Chars, BER and PEM
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOfTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES Of MERCHANTABILITY AND fITNESS fOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* fOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT Of SUBSTITUTE GOODS OR
* SERVICES; LOSS Of USE, DATA, OR PROfITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY Of LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT Of THE USE
* Of THIS SOfTWARE, EVEN If ADVISED Of THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostCrypto'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostCrypto'));
} else {
root.GostCoding = factory(root.gostCrypto);
} // </editor-fold>
})(void 0, function (gostCrypto) {
/**
* The Coding interface provides string converting methods: Base64, Hex,
* Int16, Chars, BER and PEM
* @class GostCoding
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var DataError = root.DataError || root.Error;
var CryptoOperationData = root.ArrayBuffer;
var Date = root.Date;
function buffer(d) {
if (d instanceof CryptoOperationData) return d;else if (d && d.buffer && d.buffer instanceof CryptoOperationData) return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ? d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;else throw new DataError('CryptoOperationData required');
} // </editor-fold>
function GostCoding() {}
/**
* BASE64 conversion
*
* @class GostCoding.Base64
*/
var Base64 = {
// <editor-fold defaultstate="collapsed">
/**
* Base64.decode convert BASE64 string s to CryptoOperationData
*
* @memberOf GostCoding.Base64
* @param {String} s BASE64 encoded string value
* @returns {CryptoOperationData} Binary decoded data
*/
decode: function decode(s) {
s = s.replace(/[^A-Za-z0-9\+\/]/g, '');
var n = s.length,
k = n * 3 + 1 >> 2,
r = new Uint8Array(k);
for (var m3, m4, u24 = 0, j = 0, i = 0; i < n; i++) {
m4 = i & 3;
var c = s.charCodeAt(i);
c = c > 64 && c < 91 ? c - 65 : c > 96 && c < 123 ? c - 71 : c > 47 && c < 58 ? c + 4 : c === 43 ? 62 : c === 47 ? 63 : 0;
u24 |= c << 18 - 6 * m4;
if (m4 === 3 || n - i === 1) {
for (m3 = 0; m3 < 3 && j < k; m3++, j++) {
r[j] = u24 >>> (16 >>> m3 & 24) & 255;
}
u24 = 0;
}
}
return r.buffer;
},
/**
* Base64.encode(data) convert CryptoOperationData data to BASE64 string
*
* @memberOf GostCoding.Base64
* @param {CryptoOperationData} data Bynary data for encoding
* @returns {String} BASE64 encoded data
*/
encode: function encode(data) {
var slen = 8,
d = new Uint8Array(buffer(data));
var m3 = 2,
s = '';
for (var n = d.length, u24 = 0, i = 0; i < n; i++) {
m3 = i % 3;
if (i > 0 && i * 4 / 3 % (12 * slen) === 0) s += '\r\n';
u24 |= d[i] << (16 >>> m3 & 24);
if (m3 === 2 || n - i === 1) {
for (var j = 18; j >= 0; j -= 6) {
var c = u24 >>> j & 63;
c = c < 26 ? c + 65 : c < 52 ? c + 71 : c < 62 ? c - 4 : c === 62 ? 43 : c === 63 ? 47 : 65;
s += String.fromCharCode(c);
}
u24 = 0;
}
}
return s.substr(0, s.length - 2 + m3) + (m3 === 2 ? '' : m3 === 1 ? '=' : '==');
} // </editor-fold>
};
/**
* BASE64 conversion
*
* @memberOf GostCoding
* @insnance
* @type GostCoding.Base64
*/
GostCoding.prototype.Base64 = Base64;
/**
* Text string conversion <br>
* Methods support charsets: ascii, win1251, utf8, utf16 (ucs2, unicode), utf32 (ucs4)
*
* @class GostCoding.Chars
*/
var Chars = function () {
// <editor-fold defaultstate="collapsed">
var _win1251_ = {
0x402: 0x80,
0x403: 0x81,
0x201A: 0x82,
0x453: 0x83,
0x201E: 0x84,
0x2026: 0x85,
0x2020: 0x86,
0x2021: 0x87,
0x20AC: 0x88,
0x2030: 0x89,
0x409: 0x8A,
0x2039: 0x8B,
0x40A: 0x8C,
0x40C: 0x8D,
0x40B: 0x8E,
0x40f: 0x8f,
0x452: 0x90,
0x2018: 0x91,
0x2019: 0x92,
0x201C: 0x93,
0x201D: 0x94,
0x2022: 0x95,
0x2013: 0x96,
0x2014: 0x97,
0x2122: 0x99,
0x459: 0x9A,
0x203A: 0x9B,
0x45A: 0x9C,
0x45C: 0x9D,
0x45B: 0x9E,
0x45f: 0x9f,
0xA0: 0xA0,
0x40E: 0xA1,
0x45E: 0xA2,
0x408: 0xA3,
0xA4: 0xA4,
0x490: 0xA5,
0xA6: 0xA6,
0xA7: 0xA7,
0x401: 0xA8,
0xA9: 0xA9,
0x404: 0xAA,
0xAB: 0xAB,
0xAC: 0xAC,
0xAD: 0xAD,
0xAE: 0xAE,
0x407: 0xAf,
0xB0: 0xB0,
0xB1: 0xB1,
0x406: 0xB2,
0x456: 0xB3,
0x491: 0xB4,
0xB5: 0xB5,
0xB6: 0xB6,
0xB7: 0xB7,
0x451: 0xB8,
0x2116: 0xB9,
0x454: 0xBA,
0xBB: 0xBB,
0x458: 0xBC,
0x405: 0xBD,
0x455: 0xBE,
0x457: 0xBf
};
var _win1251back_ = {};
for (var from in _win1251_) {
var to = _win1251_[from];
_win1251back_[to] = from;
}
return {
/**
* Chars.decode(s, charset) convert string s with defined charset to CryptoOperationData
*
* @memberOf GostCoding.Chars
* @param {string} s Javascript string
* @param {string} charset Charset, default 'win1251'
* @returns {CryptoOperationData} Decoded binary data
*/
decode: function decode(s, charset) {
charset = (charset || 'win1251').toLowerCase().replace('-', '');
var r = [];
for (var i = 0, j = s.length; i < j; i++) {
var c = s.charCodeAt(i);
if (charset === 'utf8') {
if (c < 0x80) {
r.push(c);
} else if (c < 0x800) {
r.push(0xc0 + (c >>> 6));
r.push(0x80 + (c & 63));
} else if (c < 0x10000) {
r.push(0xe0 + (c >>> 12));
r.push(0x80 + (c >>> 6 & 63));
r.push(0x80 + (c & 63));
} else if (c < 0x200000) {
r.push(0xf0 + (c >>> 18));
r.push(0x80 + (c >>> 12 & 63));
r.push(0x80 + (c >>> 6 & 63));
r.push(0x80 + (c & 63));
} else if (c < 0x4000000) {
r.push(0xf8 + (c >>> 24));
r.push(0x80 + (c >>> 18 & 63));
r.push(0x80 + (c >>> 12 & 63));
r.push(0x80 + (c >>> 6 & 63));
r.push(0x80 + (c & 63));
} else {
r.push(0xfc + (c >>> 30));
r.push(0x80 + (c >>> 24 & 63));
r.push(0x80 + (c >>> 18 & 63));
r.push(0x80 + (c >>> 12 & 63));
r.push(0x80 + (c >>> 6 & 63));
r.push(0x80 + (c & 63));
}
} else if (charset === 'unicode' || charset === 'ucs2' || charset === 'utf16') {
if (c < 0xD800 || c >= 0xE000 && c <= 0x10000) {
r.push(c >>> 8);
r.push(c & 0xff);
} else if (c >= 0x10000 && c < 0x110000) {
c -= 0x10000;
var first = ((0xffc00 & c) >> 10) + 0xD800;
var second = (0x3ff & c) + 0xDC00;
r.push(first >>> 8);
r.push(first & 0xff);
r.push(second >>> 8);
r.push(second & 0xff);
}
} else if (charset === 'utf32' || charset === 'ucs4') {
r.push(c >>> 24 & 0xff);
r.push(c >>> 16 & 0xff);
r.push(c >>> 8 & 0xff);
r.push(c & 0xff);
} else if (charset === 'win1251') {
if (c >= 0x80) {
if (c >= 0x410 && c < 0x450) // А..Яа..я
c -= 0x350;else c = _win1251_[c] || 0;
}
r.push(c);
} else r.push(c & 0xff);
}
return new Uint8Array(r).buffer;
},
/**
* Chars.encode(data, charset) convert CryptoOperationData data to string with defined charset
*
* @memberOf GostCoding.Chars
* @param {CryptoOperationData} data Binary data
* @param {string} charset Charset, default win1251
* @returns {string} Encoded javascript string
*/
encode: function encode(data, charset) {
charset = (charset || 'win1251').toLowerCase().replace('-', '');
var r = [],
d = new Uint8Array(buffer(data));
for (var i = 0, n = d.length; i < n; i++) {
var c = d[i];
if (charset === 'utf8') {
c = c >= 0xfc && c < 0xfe && i + 5 < n ? // six bytes
(c - 0xfc) * 1073741824 + (d[++i] - 0x80 << 24) + (d[++i] - 0x80 << 18) + (d[++i] - 0x80 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80 : c >> 0xf8 && c < 0xfc && i + 4 < n ? // five bytes
(c - 0xf8 << 24) + (d[++i] - 0x80 << 18) + (d[++i] - 0x80 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80 : c >> 0xf0 && c < 0xf8 && i + 3 < n ? // four bytes
(c - 0xf0 << 18) + (d[++i] - 0x80 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80 : c >= 0xe0 && c < 0xf0 && i + 2 < n ? // three bytes
(c - 0xe0 << 12) + (d[++i] - 0x80 << 6) + d[++i] - 0x80 : c >= 0xc0 && c < 0xe0 && i + 1 < n ? // two bytes
(c - 0xc0 << 6) + d[++i] - 0x80 : c; // one byte
} else if (charset === 'unicode' || charset === 'ucs2' || charset === 'utf16') {
c = (c << 8) + d[++i];
if (c >= 0xD800 && c < 0xE000) {
var first = c - 0xD800 << 10;
c = d[++i];
c = (c << 8) + d[++i];
var second = c - 0xDC00;
c = first + second + 0x10000;
}
} else if (charset === 'utf32' || charset === 'ucs4') {
c = (c << 8) + d[++i];
c = (c << 8) + d[++i];
c = (c << 8) + d[++i];
} else if (charset === 'win1251') {
if (c >= 0x80) {
if (c >= 0xC0 && c < 0x100) c += 0x350; // А..Яа..я
else c = _win1251back_[c] || 0;
}
}
r.push(String.fromCharCode(c));
}
return r.join('');
}
}; // </editor-fold>
}();
/**
* Text string conversion
*
* @memberOf GostCoding
* @insnance
* @type GostCoding.Chars
*/
GostCoding.prototype.Chars = Chars;
/**
* HEX conversion
*
* @class GostCoding.Hex
*/
var Hex = {
// <editor-fold defaultstate="collapsed">
/**
* Hex.decode(s, endean) convert HEX string s to CryptoOperationData in endean mode
*
* @memberOf GostCoding.Hex
* @param {string} s Hex encoded string
* @param {boolean} endean Little or Big Endean, default Little
* @returns {CryptoOperationData} Decoded binary data
*/
decode: function decode(s, endean) {
s = s.replace(/[^A-fa-f0-9]/g, '');
var n = Math.ceil(s.length / 2),
r = new Uint8Array(n);
s = (s.length % 2 > 0 ? '0' : '') + s;
if (endean && (typeof endean !== 'string' || endean.toLowerCase().indexOf('little') < 0)) for (var i = 0; i < n; i++) {
r[i] = parseInt(s.substr((n - i - 1) * 2, 2), 16);
} else for (var i = 0; i < n; i++) {
r[i] = parseInt(s.substr(i * 2, 2), 16);
}
return r.buffer;
},
/**
* Hex.encode(data, endean) convert CryptoOperationData data to HEX string in endean mode
*
* @memberOf GostCoding.Hex
* @param {CryptoOperationData} data Binary data
* @param {boolean} endean Little/Big Endean, default Little
* @returns {string} Hex decoded string
*/
encode: function encode(data, endean) {
var s = [],
d = new Uint8Array(buffer(data)),
n = d.length;
if (endean && (typeof endean !== 'string' || endean.toLowerCase().indexOf('little') < 0)) for (var i = 0; i < n; i++) {
var j = n - i - 1;
s[j] = (j > 0 && j % 32 === 0 ? '\r\n' : '') + ('00' + d[i].toString(16)).slice(-2);
} else for (var i = 0; i < n; i++) {
s[i] = (i > 0 && i % 32 === 0 ? '\r\n' : '') + ('00' + d[i].toString(16)).slice(-2);
}
return s.join('');
} // </editor-fold>
};
/**
* HEX conversion
* @memberOf GostCoding
* @insnance
* @type GostCoding.Hex
*/
GostCoding.prototype.Hex = Hex;
/**
* String hex-encoded integer conversion
*
* @class GostCoding.Int16
*/
var Int16 = {
// <editor-fold defaultstate="collapsed">
/**
* Int16.decode(s) convert hex big insteger s to CryptoOperationData
*
* @memberOf GostCoding.Int16
* @param {string} s Int16 string
* @returns {CryptoOperationData} Decoded binary data
*/
decode: function decode(s) {
s = (s || '').replace(/[^\-A-fa-f0-9]/g, '');
if (s.length === 0) s = '0'; // Signature
var neg = false;
if (s.charAt(0) === '-') {
neg = true;
s = s.substring(1);
} // Align 2 chars
while (s.charAt(0) === '0' && s.length > 1) {
s = s.substring(1);
}
s = (s.length % 2 > 0 ? '0' : '') + s; // Padding for singanuture
// '800000' - 'ffffff' - for positive
// '800001' - 'ffffff' - for negative
if (!neg && !/^[0-7]/.test(s) || neg && !/^[0-7]|8[0]+$/.test(s)) s = '00' + s; // Convert hex
var n = s.length / 2,
r = new Uint8Array(n),
t = 0;
for (var i = n - 1; i >= 0; --i) {
var c = parseInt(s.substr(i * 2, 2), 16);
if (neg && c + t > 0) {
c = 256 - c - t;
t = 1;
}
r[i] = c;
}
return r.buffer;
},
/**
* Int16.encode(data) convert CryptoOperationData data to big integer hex string
*
* @memberOf GostCoding.Int16
* @param {CryptoOperationData} data Binary data
* @returns {string} Int16 encoded string
*/
encode: function encode(data) {
var d = new Uint8Array(buffer(data)),
n = d.length;
if (d.length === 0) return '0x00';
var s = [],
neg = d[0] > 0x7f,
t = 0;
for (var i = n - 1; i >= 0; --i) {
var v = d[i];
if (neg && v + t > 0) {
v = 256 - v - t;
t = 1;
}
s[i] = ('00' + v.toString(16)).slice(-2);
}
s = s.join('');
while (s.charAt(0) === '0') {
s = s.substring(1);
}
return (neg ? '-' : '') + '0x' + s;
} // </editor-fold>
};
/**
* String hex-encoded integer conversion
* @memberOf GostCoding
* @insnance
* @type GostCoding.Int16
*/
GostCoding.prototype.Int16 = Int16;
/**
* BER, DER, CER conversion
*
* @class GostCoding.BER
*/
var BER = function () {
// <editor-fold defaultstate="collapsed">
// Predefenition block
function encodeBER(source, format, onlyContent) {
// Correct primitive type
var object = source.object;
if (object === undefined) object = source; // Determinate tagClass
var tagClass = source.tagClass = source.tagClass || 0; // Universial default
// Determinate tagNumber. Use only for Universal class
if (tagClass === 0) {
var tagNumber = source.tagNumber;
if (typeof tagNumber === 'undefined') {
if (typeof object === 'string') {
if (object === '') // NULL
tagNumber = 0x05;else if (/^\-?0x[0-9a-fA-F]+$/.test(object)) // INTEGER
tagNumber = 0x02;else if (/^(\d+\.)+\d+$/.test(object)) // OID
tagNumber = 0x06;else if (/^[01]+$/.test(object)) // BIT STRING
tagNumber = 0x03;else if (/^(true|false)$/.test(object)) // BOOLEAN
tagNumber = 0x01;else if (/^[0-9a-fA-F]+$/.test(object)) // OCTET STRING
tagNumber = 0x04;else tagNumber = 0x13; // Printable string (later can be changed to UTF8String)
} else if (typeof object === 'number') {
// INTEGER
tagNumber = 0x02;
} else if (typeof object === 'boolean') {
// BOOLEAN
tagNumber = 0x01;
} else if (object instanceof Array) {
// SEQUENCE
tagNumber = 0x10;
} else if (object instanceof Date) {
// GeneralizedTime
tagNumber = 0x18;
} else if (object instanceof CryptoOperationData || object && object.buffer instanceof CryptoOperationData) {
tagNumber = 0x04;
} else throw new DataError('Unrecognized type for ' + object);
}
} // Determinate constructed
var tagConstructed = source.tagConstructed;
if (typeof tagConstructed === 'undefined') tagConstructed = source.tagConstructed = object instanceof Array; // Create content
var content;
if (object instanceof CryptoOperationData || object && object.buffer instanceof CryptoOperationData) {
// Direct
content = new Uint8Array(buffer(object));
if (tagNumber === 0x03) {
// BITSTRING
// Set unused bits
var a = new Uint8Array(buffer(content));
content = new Uint8Array(a.length + 1);
content[0] = 0; // No unused bits
content.set(a, 1);
}
} else if (tagConstructed) {
// Sub items coding
if (object instanceof Array) {
var bytelen = 0,
ba = [],
offset = 0;
for (var i = 0, n = object.length; i < n; i++) {
ba[i] = encodeBER(object[i], format);
bytelen += ba[i].length;
}
if (tagNumber === 0x11) ba.sort(function (a, b) {
// Sort order for SET components
for (var i = 0, n = Math.min(a.length, b.length); i < n; i++) {
var r = a[i] - b[i];
if (r !== 0) return r;
}
return a.length - b.length;
});
if (format === 'CER') {
// final for CER 00 00
ba[n] = new Uint8Array(2);
bytelen += 2;
}
content = new Uint8Array(bytelen);
for (var i = 0, n = ba.length; i < n; i++) {
content.set(ba[i], offset);
offset = offset + ba[i].length;
}
} else throw new DataError('Constracted block can\'t be primitive');
} else {
switch (tagNumber) {
// 0x00: // EOC
case 0x01:
// BOOLEAN
content = new Uint8Array(1);
content[0] = object ? 0xff : 0;
break;
case 0x02: // INTEGER
case 0x0a:
// ENUMIRATED
content = Int16.decode(typeof object === 'number' ? object.toString(16) : object);
break;
case 0x03:
// BIT STRING
if (typeof object === 'string') {
var unusedBits = 7 - (object.length + 7) % 8;
var n = Math.ceil(object.length / 8);
content = new Uint8Array(n + 1);
content[0] = unusedBits;
for (var i = 0; i < n; i++) {
var c = 0;
for (var j = 0; j < 8; j++) {
var k = i * 8 + j;
c = (c << 1) + (k < object.length ? object.charAt(k) === '1' ? 1 : 0 : 0);
}
content[i + 1] = c;
}
}
break;
case 0x04:
content = Hex.decode(typeof object === 'number' ? object.toString(16) : object);
break;
// case 0x05: // NULL
case 0x06:
// OBJECT IDENTIFIER
var a = object.match(/\d+/g),
r = [];
for (var i = 1; i < a.length; i++) {
var n = +a[i],
r1 = [];
if (i === 1) n = n + a[0] * 40;
do {
r1.push(n & 0x7F);
n = n >>> 7;
} while (n); // reverse order
for (j = r1.length - 1; j >= 0; --j) {
r.push(r1[j] + (j === 0 ? 0x00 : 0x80));
}
}
content = new Uint8Array(r);
break;
// case 0x07: // ObjectDescriptor
// case 0x08: // EXTERNAL
// case 0x09: // REAL
// case 0x0A: // ENUMERATED
// case 0x0B: // EMBEDDED PDV
case 0x0C:
// UTF8String
content = Chars.decode(object, 'utf8');
break;
// case 0x10: // SEQUENCE
// case 0x11: // SET
case 0x12: // NumericString
case 0x16: // IA5String // ASCII
case 0x13: // PrintableString // ASCII subset
case 0x14: // TeletexString // aka T61String
case 0x15: // VideotexString
case 0x19: // GraphicString
case 0x1A: // VisibleString // ASCII subset
case 0x1B:
// GeneralString
// Reflect on character encoding
for (var i = 0, n = object.length; i < n; i++) {
if (object.charCodeAt(i) > 255) tagNumber = 0x0C;
}
if (tagNumber === 0x0C) content = Chars.decode(object, 'utf8');else content = Chars.decode(object, 'ascii');
break;
case 0x17: // UTCTime
case 0x18:
// GeneralizedTime
var result = object.original;
if (!result) {
var date = new Date(object);
date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); // to UTC
var ms = tagNumber === 0x18 ? date.getMilliseconds().toString() : ''; // Milliseconds, remove trailing zeros
while (ms.length > 0 && ms.charAt(ms.length - 1) === '0') {
ms = ms.substring(0, ms.length - 1);
}
if (ms.length > 0) ms = '.' + ms;
result = (tagNumber === 0x17 ? date.getYear().toString().slice(-2) : date.getFullYear().toString()) + ('00' + (date.getMonth() + 1)).slice(-2) + ('00' + date.getDate()).slice(-2) + ('00' + date.getHours()).slice(-2) + ('00' + date.getMinutes()).slice(-2) + ('00' + date.getSeconds()).slice(-2) + ms + 'Z';
}
content = Chars.decode(result, 'ascii');
break;
case 0x1C:
// UniversalString
content = Chars.decode(object, 'utf32');
break;
case 0x1E:
// BMPString
content = Chars.decode(object, 'utf16');
break;
}
}
if (!content) content = new Uint8Array(0);
if (content instanceof CryptoOperationData) content = new Uint8Array(content);
if (!tagConstructed && format === 'CER') {
// Encoding CER-form for string types
var k;
switch (tagNumber) {
case 0x03:
// BIT_STRING
k = 1;
// ingnore unused bit for bit string
case 0x04: // OCTET_STRING
case 0x0C: // UTF8String
case 0x12: // NumericString
case 0x13: // PrintableString
case 0x14: // TeletexString
case 0x15: // VideotexString
case 0x16: // IA5String
case 0x19: // GraphicString
case 0x1A: // VisibleString
case 0x1B: // GeneralString
case 0x1C: // UniversalString
case 0x1E:
// BMPString
k = k || 0; // Split content on 1000 octet len parts
var size = 1000;
var bytelen = 0,
ba = [],
offset = 0;
for (var i = k, n = content.length; i < n; i += size - k) {
ba[i] = encodeBER({
object: new Unit8Array(content.buffer, i, Math.min(size - k, n - i)),
tagNumber: tagNumber,
tagClass: 0,
tagConstructed: false
}, format);
bytelen += ba[i].length;
}
ba[n] = new Uint8Array(2); // final for CER 00 00
bytelen += 2;
content = new Uint8Array(bytelen);
for (var i = 0, n = ba.length; i < n; i++) {
content.set(ba[i], offset);
offset = offset + ba[i].length;
}
}
} // Restore tagNumber for all classes
if (tagClass === 0) source.tagNumber = tagNumber;else source.tagNumber = tagNumber = source.tagNumber || 0;
source.content = content;
if (onlyContent) return content; // Create header
// tagNumber
var ha = [],
first = tagClass === 3 ? 0xC0 : tagClass === 2 ? 0x80 : tagClass === 1 ? 0x40 : 0x00;
if (tagConstructed) first |= 0x20;
if (tagNumber < 0x1F) {
first |= tagNumber & 0x1F;
ha.push(first);
} else {
first |= 0x1F;
ha.push(first);
var n = tagNumber,
ha1 = [];
do {
ha1.push(n & 0x7F);
n = n >>> 7;
} while (n); // reverse order
for (var j = ha1.length - 1; j >= 0; --j) {
ha.push(ha1[j] + (j === 0 ? 0x00 : 0x80));
}
} // Length
if (tagConstructed && format === 'CER') {
ha.push(0x80);
} else {
var len = content.length;
if (len > 0x7F) {
var l2 = len,
ha2 = [];
do {
ha2.push(l2 & 0xff);
l2 = l2 >>> 8;
} while (l2);
ha.push(ha2.length + 0x80); // reverse order
for (var j = ha2.length - 1; j >= 0; --j) {
ha.push(ha2[j]);
}
} else {
// simple len
ha.push(len);
}
}
var header = source.header = new Uint8Array(ha); // Result - complete buffer
var block = new Uint8Array(header.length + content.length);
block.set(header, 0);
block.set(content, header.length);
return block;
}
function decodeBER(source, offset) {
// start pos
var pos = offset || 0,
start = pos;
var tagNumber, tagClass, tagConstructed, content, header, buffer, sub, len;
if (source.object) {
// Ready from source
tagNumber = source.tagNumber;
tagClass = source.tagClass;
tagConstructed = source.tagConstructed;
content = source.content;
header = source.header;
buffer = source.object instanceof CryptoOperationData ? new Uint8Array(source.object) : null;
sub = source.object instanceof Array ? source.object : null;
len = buffer && buffer.length || null;
} else {
// Decode header
var d = source; // Read tag
var buf = d[pos++];
tagNumber = buf & 0x1f;
tagClass = buf >> 6;
tagConstructed = (buf & 0x20) !== 0;
if (tagNumber === 0x1f) {
// long tag
tagNumber = 0;
do {
if (tagNumber > 0x1fffffffffff80) throw new DataError('Convertor not supported tag number more then (2^53 - 1) at position ' + offset);
buf = d[pos++];
tagNumber = (tagNumber << 7) + (buf & 0x7f);
} while (buf & 0x80);
} // Read len
buf = d[pos++];
len = buf & 0x7f;
if (len !== buf) {
if (len > 6) // no reason to use Int10, as it would be a huge buffer anyways
throw new DataError('Length over 48 bits not supported at position ' + offset);
if (len === 0) len = null; // undefined
else {
buf = 0;
for (var i = 0; i < len; ++i) {
buf = (buf << 8) + d[pos++];
}
len = buf;
}
}
start = pos;
sub = null;
if (tagConstructed) {
// must have valid content
sub = [];
if (len !== null) {
// definite length
var end = start + len;
while (pos < end) {
var s = decodeBER(d, pos);
sub.push(s);
pos += s.header.length + s.content.length;
}
if (pos !== end) throw new DataError('Content size is not correct for container starting at offset ' + start);
} else {
// undefined length
try {
for (;;) {
var s = decodeBER(d, pos);
pos += s.header.length + s.content.length;
if (s.tagClass === 0x00 && s.tagNumber === 0x00) break;
sub.push(s);
}
len = pos - start;
} catch (e) {
throw new DataError('Exception ' + e + ' while decoding undefined length content at offset ' + start);
}
}
} // Header and content
header = new Uint8Array(d.buffer, offset, start - offset);
content = new Uint8Array(d.buffer, start, len);
buffer = content;
} // Constructed types - check for string concationation
if (sub !== null && tagClass === 0) {
var k;
switch (tagNumber) {
case 0x03:
// BIT_STRING
k = 1;
// ingnore unused bit for bit string
case 0x04: // OCTET_STRING
case 0x0C: // UTF8String
case 0x12: // NumericString
case 0x13: // PrintableString
case 0x14: // TeletexString
case 0x15: // VideotexString
case 0x16: // IA5String
case 0x19: // GraphicString
case 0x1A: // VisibleString
case 0x1B: // GeneralString
case 0x1C: // UniversalString
case 0x1E:
// BMPString
k = k || 0; // Concatination
if (sub.length === 0) throw new DataError('No constructed encoding content of string type at offset ' + start);
len = k;
for (var i = 0, n = sub.length; i < n; i++) {
var s = sub[i];
if (s.tagClass !== tagClass || s.tagNumber !== tagNumber || s.tagConstructed) throw new DataError('Invalid constructed encoding of string type at offset ' + start);
len += s.content.length - k;
}
buffer = new Uint8Array(len);
for (var i = 0, n = sub.length, j = k; i < n; i++) {
var s = sub[i];
if (k > 0) buffer.set(s.content.subarray(1), j);else buffer.set(s.content, j);
j += s.content.length - k;
}
tagConstructed = false; // follow not required
sub = null;
break;
}
} // Primitive types
var object = '';
if (sub === null) {
if (len === null) throw new DataError('Invalid tag with undefined length at offset ' + start);
if (tagClass === 0) {
switch (tagNumber) {
case 0x01:
// BOOLEAN
object = buffer[0] !== 0;
break;
case 0x02: // INTEGER
case 0x0a:
// ENUMIRATED
if (len > 6) {
object = Int16.encode(buffer);
} else {
var v = buffer[0];
if (buffer[0] > 0x7f) v = v - 256;
for (var i = 1; i < len; i++) {
v = v * 256 + buffer[i];
}
object = v;
}
break;
case 0x03:
// BIT_STRING
if (len > 5) {
// Content buffer
object = new Uint8Array(buffer.subarray(1)).buffer;
} else {
// Max bit mask only for 32 bit
var unusedBit = buffer[0],
skip = unusedBit,
s = [];
for (var i = len - 1; i >= 1; --i) {
var b = buffer[i];
for (var j = skip; j < 8; ++j) {
s.push(b >> j & 1 ? '1' : '0');
}
skip = 0;
}
object = s.reverse().join('');
}
break;
case 0x04:
// OCTET_STRING
object = new Uint8Array(buffer).buffer;
break;
// case 0x05: // NULL
case 0x06:
// OBJECT_IDENTIFIER
var s = '',
n = 0,
bits = 0;
for (var i = 0; i < len; ++i) {
var v = buffer[i];
n = (n << 7) + (v & 0x7F);
bits += 7;
if (!(v & 0x80)) {
// finished
if (s === '') {
var m = n < 80 ? n < 40 ? 0 : 1 : 2;
s = m + "." + (n - m * 40);
} else s += "." + n.toString();
n = 0;
bits = 0;
}
}
if (bits > 0) throw new DataError('Incompleted OID at offset ' + start);
object = s;
break;
//case 0x07: // ObjectDescriptor
//case 0x08: // EXTERNAL
//case 0x09: // REAL
//case 0x0A: // ENUMERATED
//case 0x0B: // EMBEDDED_PDV
case 0x10: // SEQUENCE
case 0x11:
// SET
object = [];
break;
case 0x0C:
// UTF8String
object = Chars.encode(buffer, 'utf8');
break;
case 0x12: // NumericString
case 0x13: // PrintableString
case 0x14: // TeletexString
case 0x15: // VideotexString
case 0x16: // IA5String
case 0x19: // GraphicString
case 0x1A: // VisibleString
case 0x1B:
// GeneralString
object = Chars.encode(buffer, 'ascii');
break;
case 0x1C:
// UniversalString
object = Chars.encode(buffer, 'utf32');
break;
case 0x1E:
// BMPString
object = Chars.encode(buffer, 'utf16');
break;
case 0x17: // UTCTime
case 0x18:
// GeneralizedTime
var shortYear = tagNumber === 0x17;
var s = Chars.encode(buffer, 'ascii'),
m = (shortYear ? /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/ : /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/).exec(s);
if (!m) throw new DataError('Unrecognized time format "' + s + '" at offset ' + start);
if (shortYear) {
// Where YY is greater than or equal to 50, the year SHALL be interpreted as 19YY; and
// Where YY is less than 50, the year SHALL be interpreted as 20YY
m[1] = +m[1];
m[1] += m[1] < 50 ? 2000 : 1900;
}
var dt = new Date(m[1], +m[2] - 1, +m[3], +(m[4] || '0'), +(m[5] || '0'), +(m[6] || '0'), +(m[7] || '0')),
tz = dt.getTimezoneOffset();
if (m[8] || tagNumber === 0x17) {
if (m[8].toUpperCase() !== 'Z' && m[9]) {
tz = tz + parseInt(m[9]);
}
dt.setMinutes(dt.getMinutes() - tz);
}
dt.original = s;
object = dt;
break;
}
} else // OCTET_STRING
object = new Uint8Array(buffer).buffer;
} else object = sub; // result
return {
tagConstructed: tagConstructed,
tagClass: tagClass,
tagNumber: tagNumber,
header: header,
content: content,
object: object
};
}
return {
/**
* BER.decode(object, format) convert javascript object to ASN.1 format CryptoOperationData<br><br>
* If object has members tagNumber, tagClass and tagConstructed
* it is clear define encoding rules. Else method use defaul rules:
* <ul>
* <li>Empty string or null - NULL</li>
* <li>String starts with '0x' and has 0-9 and a-f characters - INTEGER</li>
* <li>String like d.d.d.d (d - set of digits) - OBJECT IDENTIFIER</li>
* <li>String with characters 0 and 1 - BIT STRING</li>
* <li>Strings 'true' or 'false' - BOOLEAN</li>
* <li>String has only 0-9 and a-f characters - OCTET STRING</li>
* <li>String has only characters with code 0-255 - PrintableString</li>
* <li>Other strings - UTF8String</li>
* <li>Number - INTEGER</li>
* <li>Date - GeneralizedTime</li>
* <li>Boolean - SEQUENCE</li>
* <li>CryptoOperationData - OCTET STRING</li>
* </ul>
* SEQUENCE or SET arrays recursively encoded for each item.<br>
* OCTET STRING and BIT STRING can presents as array with one item.
* It means encapsulates encoding for child element.<br>
*
* If CONTEXT or APPLICATION classes item presents as array with one
* item we use EXPLICIT encoding for element, else IMPLICIT encoding.<br>
*
* @memberOf GostCoding.BER
* @param {Object} object Object to encoding
* @param {string} format Encoding rule: 'DER' or 'CER', default 'DER'
* @param {boolean} onlyContent Encode content only, without header
* @returns {CryptoOperationData} BER encoded data
*/
encode: function encode(object, format, onlyContent) {
return encodeBER(object, format, onlyContent).buffer;
},
/**
* BER.encode(data) convert ASN.1 format CryptoOperationData data to javascript object<br><br>
*
* Conversion rules to javascript object:
* <ul>
* <li>BOOLEAN - Boolean object</li>
* <li>INTEGER, ENUMIRATED - Integer object if len <= 6 (48 bits) else Int16 encoded string</li>
* <li>BIT STRING - Integer object if len <= 5 (w/o unsedBit octet - 32 bits) else String like '10111100' or Array with one item in case of incapsulates encoding</li>
* <li>OCTET STRING - Hex encoded string or Array with one item in case of incapsulates encoding</li>
* <li>OBJECT IDENTIFIER - String with object identifier</li>
* <li>SEQUENCE, SET - Array of encoded items</li>
* <li>UTF8String, NumericString, PrintableString, TeletexString, VideotexString,
* IA5String, GraphicString, VisibleString, GeneralString, UniversalString,
* BMPString - encoded String</li>
* <li>UTCTime, GeneralizedTime - Date</li>
* </ul>
* @memberOf GostCoding.BER
* @param {(CryptoOperationData|GostCoding.BER)} data Binary data to decode
* @returns {Object} Javascript object with result of decoding
*/
decode: function decode(data) {
return decodeBER(data.object ? data : new Uint8Array(buffer(data)), 0);
}
}; // </editor-fold>
}();
/**
* BER, DER, CER conversion
* @memberOf GostCoding
* @insnance
* @type GostCoding.BER
*/
GostCoding.prototype.BER = BER;
/**
* PEM conversion
* @class GostCoding.PEM
*/
var PEM = {
// <editor-fold defaultstate="collapsed">
/**
* PEM.encode(data, name) encode CryptoOperationData to PEM format with name label
*
* @memberOf GostCoding.PEM
* @param {(Object|CryptoOperationData)} data Java script object or BER-encoded binary data
* @param {string} name Name of PEM object: 'certificate', 'private key' etc.
* @returns {string} Encoded object
*/
encode: function encode(data, name) {
return (name ? '-----BEGIN ' + name.toUpperCase() + '-----\r\n' : '') + Base64.encode(data instanceof CryptoOperationData ? data : BER.encode(data)) + (name ? '\r\n-----END ' + name.toUpperCase() + '-----' : '');
},
/**
* PEM.decode(s, name, deep) decode PEM format s labeled name to CryptoOperationData or javascript object in according to deep parameter
*
* @memberOf GostCoding.PEM
* @param {string} s PEM encoded string
* @param {string} name Name of PEM object: 'certificate', 'private key' etc.
* @param {boolean} deep If true method do BER-decoding, else only BASE64 decoding
* @param {integer} index Index of decoded value
* @returns {(Object|CryptoOperationData)} Decoded javascript object if deep=true, else CryptoOperationData for father BER decoding
*/
decode: function decode(s, name, deep, index) {
// Try clear base64
var re1 = /([A-Za-z0-9\+\/\s\=]+)/g,
valid = re1.exec(s);
if (valid[1].length !== s.length) valid = false;
if (!valid && name) {
// Try with the name
var re2 = new RegExp('-----\\s?BEGIN ' + name.toUpperCase() + '-----([A-Za-z0-9\\+\\/\\s\\=]+)-----\\s?END ' + name.toUpperCase() + '-----', 'g');
valid = re2.exec(s);
}
if (!valid) {
// Try with some name
var re3 = new RegExp('-----\\s?BEGIN [A-Z0-9\\s]+' + '-----([A-Za-z0-9\\+\\/\\s\\=]+)-----\\s?END ' + '[A-Z0-9\\s]+-----', 'g');
valid = re3.exec(s);
}
var r = valid && valid[1 + (index || 0)];
if (!r) throw new DataError('Not valid PEM format');
var out = Base64.decode(r);
if (deep) out = BER.decode(out);
return out;
} // </editor-fold>
};
/**
* PEM conversion
* @memberOf GostCoding
* @insnance
* @type GostCoding.PEM
*/
GostCoding.prototype.PEM = PEM;
if (gostCrypto)
/**
* Coding algorithms: Base64, Hex, Int16, Chars, BER and PEM
*
* @memberOf gostCrypto
* @type GostCoding
*/
gostCrypto.coding = new GostCoding();
return GostCoding;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostCrypto":110}],110:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file Implementation Web Crypto interfaces for GOST algorithms
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostRandom'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostRandom'));
} else {
root.gostCrypto = factory(root.GostRandom);
} // </editor-fold>
})(void 0, function (GostRandom) {
/*
* Algorithm normalization
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var rootCrypto = root.crypto || root.msCrypto;
var SyntaxError = root.SyntaxError || root.Error,
DataError = root.DataError || root.Error,
NotSupportedError = root.NotSupportedError || root.Error,
OperationError = root.OperationError || root.Error,
InvalidStateError = root.InvalidAccessError || root.Error,
InvalidAccessError = root.InvalidAccessError || root.Error; // Normalize algorithm
function normalize(algorithm, method) {
if (typeof algorithm === 'string' || algorithm instanceof String) algorithm = {
name: algorithm
};
var name = algorithm.name;
if (!name) throw new SyntaxError('Algorithm name not defined'); // Extract algorithm modes from name
var modes = name.split('/'),
modes = modes[0].split('-').concat(modes.slice(1)); // Normalize the name with default modes
var na = {};
name = modes[0].replace(/[\.\s]/g, '');
modes = modes.slice(1);
if (name.indexOf('28147') >= 0) {
na = {
name: 'GOST 28147',
version: 1989,
mode: (algorithm.mode || ( // ES, MAC, KW
method === 'sign' || method === 'verify' ? 'MAC' : method === 'wrapKey' || method === 'unwrapKey' ? 'KW' : 'ES')).toUpperCase(),
length: algorithm.length || 64
};
} else if (name.indexOf('3412') >= 0) {
na = {
name: 'GOST R 34.12',
version: 2015,
mode: (algorithm.mode || ( // ES, MAC, KW
method === 'sign' || method === 'verify' ? 'MAC' : method === 'wrapKey' || method === 'unwrapKey' ? 'KW' : 'ES')).toUpperCase(),
length: algorithm.length || 64 // 128
};
} else if (name.indexOf('3411') >= 0) {
na = {
name: 'GOST R 34.11',
version: 2012,
// 1994
mode: (algorithm.mode || ( // HASH, KDF, HMAC, PBKDF2, PFXKDF, CPKDF
method === 'deriveKey' || method === 'deriveBits' ? 'KDF' : method === 'sign' || method === 'verify' ? 'HMAC' : 'HASH')).toUpperCase(),
length: algorithm.length || 256 // 512
};
} else if (name.indexOf('3410') >= 0) {
na = {
name: 'GOST R 34.10',
version: 2012,
// 1994, 2001
mode: (algorithm.mode || ( // SIGN, DH, MASK
method === 'deriveKey' || method === 'deriveBits' ? 'DH' : 'SIGN')).toUpperCase(),
length: algorithm.length || 256 // 512
};
} else if (name.indexOf('SHA') >= 0) {
na = {
name: 'SHA',
version: (algorithm.length || 160) === 160 ? 1 : 2,
// 1, 2
mode: (algorithm.mode || ( // HASH, KDF, HMAC, PBKDF2, PFXKDF
method === 'deriveKey' || method === 'deriveBits' ? 'KDF' : method === 'sign' || method === 'verify' ? 'HMAC' : 'HASH')).toUpperCase(),
length: algorithm.length || 160
};
} else if (name.indexOf('RC2') >= 0) {
na = {
name: 'RC2',
version: 1,
mode: (algorithm.mode || ( // ES, MAC, KW
method === 'sign' || method === 'verify' ? 'MAC' : method === 'wrapKey' || method === 'unwrapKey' ? 'KW' : 'ES')).toUpperCase(),
length: algorithm.length || 32 // 1 - 1024
};
} else if (name.indexOf('PBKDF2') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'PBKDF2';
} else if (name.indexOf('PFXKDF') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'PFXKDF';
} else if (name.indexOf('CPKDF') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'CPKDF';
} else if (name.indexOf('HMAC') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'HMAC';
} else throw new NotSupportedError('Algorithm not supported'); // Compile modes
modes.forEach(function (mode) {
mode = mode.toUpperCase();
if (/^[0-9]+$/.test(mode)) {
if (['8', '16', '32'].indexOf(mode) >= 0 || na.length === '128' && mode === '64') {
// Shift bits
if (na.mode === 'ES') na.shiftBits = parseInt(mode);else if (na.mode === 'MAC') na.macLength = parseInt(mode);else throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
} else if (['89', '94', '01', '12', '15', '1989', '1994', '2001', '2012', '2015'].indexOf(mode) >= 0) {
// GOST Year
var version = parseInt(mode);
version = version < 1900 ? version < 80 ? 2000 + version : 1900 + version : version;
na.version = version;
} else if (['1'].indexOf(mode) >= 0 && na.name === 'SHA') {
// SHA-1
na.version = 1;
na.length = 160;
} else if (['256', '384', '512'].indexOf(mode) >= 0 && na.name === 'SHA') {
// SHA-2
na.version = 2;
na.length = parseInt(mode);
} else if (['40', '128'].indexOf(mode) >= 0 && na.name === 'RC2') {
// RC2
na.version = 1;
na.length = parseInt(mode); // key size
} else if (['64', '128', '256', '512'].indexOf(mode) >= 0) // block size
na.length = parseInt(mode);else if (['1000', '2000'].indexOf(mode) >= 0) // Iterations
na.iterations = parseInt(mode); // Named Paramsets
} else if (['E-TEST', 'E-A', 'E-B', 'E-C', 'E-D', 'E-SC', 'E-Z', 'D-TEST', 'D-A', 'D-SC'].indexOf(mode) >= 0) {
na.sBox = mode;
} else if (['S-TEST', 'S-A', 'S-B', 'S-C', 'S-D', 'X-A', 'X-B', 'X-C'].indexOf(mode) >= 0) {
na.namedParam = mode;
} else if (['S-256-TEST', 'S-256-A', 'S-256-B', 'S-256-C', 'P-256', 'T-512-TEST', 'T-512-A', 'T-512-B', 'X-256-A', 'X-256-B', 'T-256-TEST', 'T-256-A', 'T-256-B', 'S-256-B', 'T-256-C', 'S-256-C'].indexOf(mode) >= 0) {
na.namedCurve = mode;
} else if (['SC', 'CP', 'VN'].indexOf(mode) >= 0) {
na.procreator = mode; // Encription GOST 28147 or GOST R 34.12
} else if (na.name === 'GOST 28147' || na.name === 'GOST R 34.12' || na.name === 'RC2') {
if (['ES', 'MAC', 'KW', 'MASK'].indexOf(mode) >= 0) {
na.mode = mode;
} else if (['ECB', 'CFB', 'OFB', 'CTR', 'CBC'].indexOf(mode) >= 0) {
na.mode = 'ES';
na.block = mode;
} else if (['CPKW', 'NOKW', 'SCKW'].indexOf(mode) >= 0) {
na.mode = 'KW';
na.keyWrapping = mode.replace('KW', '');
} else if (['ZEROPADDING', 'PKCS5PADDING', 'NOPADDING', 'RANDOMPADDING', 'BITPADDING'].indexOf(mode) >= 0) {
na.padding = mode.replace('PADDING', '');
} else if (['NOKM', 'CPKM'].indexOf(mode) >= 0) {
na.keyMeshing = mode.replace('KM', '');
} else throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported'); // Digesting GOST 34.11
} else if (na.name === 'GOST R 34.11' || na.name === 'SHA') {
if (['HASH', 'KDF', 'HMAC', 'PBKDF2', 'PFXKDF', 'CPKDF'].indexOf(mode) >= 0) na.mode = mode;else throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported'); // Signing GOST 34.10
} else if (na.name === 'GOST R 34.10') {
var hash = mode.replace(/[\.\s]/g, '');
if (hash.indexOf('GOST') >= 0 && hash.indexOf('3411') >= 0) na.hash = mode;else if (['SIGN', 'DH', 'MASK'].indexOf(mode)) na.mode = mode;else throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
}
}); // Procreator
na.procreator = algorithm.procreator || na.procreator || 'CP'; // Key size
switch (na.name) {
case 'GOST R 34.10':
na.keySize = na.length / (na.version === 1994 ? 4 : 8);
break;
case 'GOST R 34.11':
na.keySize = 32;
break;
case 'GOST 28147':
case 'GOST R 34.12':
na.keySize = 32;
break;
case 'RC2':
na.keySize = Math.ceil(na.length / 8);
break;
case 'SHA':
na.keySize = na.length / 8;
break;
} // Encrypt additional modes
if (na.mode === 'ES') {
if (algorithm.block) na.block = algorithm.block; // ECB, CFB, OFB, CTR, CBC
if (na.block) na.block = na.block.toUpperCase();
if (algorithm.padding) na.padding = algorithm.padding; // NO, ZERO, PKCS5, RANDOM, BIT
if (na.padding) na.padding = na.padding.toUpperCase();
if (algorithm.shiftBits) na.shiftBits = algorithm.shiftBits; // 8, 16, 32, 64
if (algorithm.keyMeshing) na.keyMeshing = algorithm.keyMeshing; // NO, CP
if (na.keyMeshing) na.keyMeshing = na.keyMeshing.toUpperCase(); // Default values
if (method !== 'importKey' && method !== 'generateKey') {
na.block = na.block || 'ECB';
na.padding = na.padding || (na.block === 'CBC' || na.block === 'ECB' ? 'ZERO' : 'NO');
if (na.block === 'CFB' || na.block === 'OFB') na.shiftBits = na.shiftBits || na.length;
na.keyMeshing = na.keyMeshing || 'NO';
}
}
if (na.mode === 'KW') {
if (algorithm.keyWrapping) na.keyWrapping = algorithm.keyWrapping; // NO, CP, SC
if (na.keyWrapping) na.keyWrapping = na.keyWrapping.toUpperCase();
if (method !== 'importKey' && method !== 'generateKey') na.keyWrapping = na.keyWrapping || 'NO';
} // Paramsets
['sBox', 'namedParam', 'namedCurve', 'curve', 'param', 'modulusLength'].forEach(function (name) {
algorithm[name] && (na[name] = algorithm[name]);
}); // Default values
if (method !== 'importKey' && method !== 'generateKey') {
if (na.name === 'GOST 28147') {
na.sBox = na.sBox || (na.procreator === 'SC' ? 'E-SC' : 'E-A'); // 'E-A', 'E-B', 'E-C', 'E-D', 'E-SC'
} else if (na.name === 'GOST R 34.12' && na.length === 64) {
na.sBox = 'E-Z';
} else if (na.name === 'GOST R 34.11' && na.version === 1994) {
na.sBox = na.sBox || (na.procreator === 'SC' ? 'D-SC' : 'D-A'); // 'D-SC'
} else if (na.name === 'GOST R 34.10' && na.version === 1994) {
na.namedParam = na.namedParam || (na.mode === 'DH' ? 'X-A' : 'S-A'); // 'S-B', 'S-C', 'S-D', 'X-B', 'X-C'
} else if (na.name === 'GOST R 34.10' && na.version === 2001) {
na.namedCurve = na.namedCurve || (na.length === 256 ? na.procreator === 'SC' ? 'P-256' : na.mode === 'DH' ? 'X-256-A' : 'S-256-A' : // 'S-256-B', 'S-256-C', 'X-256-B', 'T-256-A', 'T-256-B', 'T-256-C', 'P-256'
na.mode === 'T-512-A'); // 'T-512-B', 'T-512-C'
} else if (na.name === 'GOST R 34.10' && na.version === 2012) {
na.namedCurve = na.namedCurve || (na.length === 256 ? na.procreator === 'SC' ? 'P-256' : na.mode === 'DH' ? 'X-256-A' : 'S-256-A' : // 'S-256-B', 'S-256-C', 'X-256-B', 'T-256-A', 'T-256-B', 'T-256-C', 'P-256'
na.mode === 'T-512-A'); // 'T-512-B', 'T-512-C'
}
} // Vectors
switch (na.mode) {
case 'DH':
algorithm.ukm && (na.ukm = algorithm.ukm);
algorithm['public'] && (na['public'] = algorithm['public']);
break;
case 'SIGN':
case 'KW':
algorithm.ukm && (na.ukm = algorithm.ukm);
break;
case 'ES':
case 'MAC':
algorithm.iv && (na.iv = algorithm.iv);
break;
case 'KDF':
algorithm.label && (na.label = algorithm.label);
algorithm.contex && (na.context = algorithm.contex);
break;
case 'PBKDF2':
algorithm.salt && (na.salt = algorithm.salt);
algorithm.iterations && (na.iterations = algorithm.iterations);
algorithm.diversifier && (na.diversifier = algorithm.diversifier);
break;
case 'PFXKDF':
algorithm.salt && (na.salt = algorithm.salt);
algorithm.iterations && (na.iterations = algorithm.iterations);
algorithm.diversifier && (na.diversifier = algorithm.diversifier);
break;
case 'CPKDF':
algorithm.salt && (na.salt = algorithm.salt);
algorithm.iterations && (na.iterations = algorithm.iterations);
break;
} // Verification method and modes
if (method && (na.mode !== 'ES' && na.mode !== 'SIGN' && na.mode !== 'MAC' && na.mode !== 'HMAC' && na.mode !== 'KW' && na.mode !== 'DH' && na.mode !== 'MASK' && method === 'generateKey' || na.mode !== 'ES' && (method === 'encrypt' || method === 'decrypt') || na.mode !== 'SIGN' && na.mode !== 'MAC' && na.mode !== 'HMAC' && (method === 'sign' || method === 'verify') || na.mode !== 'HASH' && method === 'digest' || na.mode !== 'KW' && na.mode !== 'MASK' && (method === 'wrapKey' || method === 'unwrapKey') || na.mode !== 'DH' && na.mode !== 'PBKDF2' && na.mode !== 'PFXKDF' && na.mode !== 'CPKDF' && na.mode !== 'KDF' && (method === 'deriveKey' || method === 'deriveBits'))) throw new NotSupportedError('Algorithm mode ' + na.mode + ' not valid for method ' + method); // Normalize hash algorithm
algorithm.hash && (na.hash = algorithm.hash);
if (na.hash) {
if ((typeof na.hash === 'string' || na.hash instanceof String) && na.procreator) na.hash = na.hash + '/' + na.procreator;
na.hash = normalize(na.hash, 'digest');
} // Algorithm object identirifer
algorithm.id && (na.id = algorithm.id);
return na;
} // Check for possibility use native crypto.subtle
function checkNative(algorithm) {
if (!rootCrypto || !rootCrypto.subtle || !algorithm) return false; // Prepare name
var name = typeof algorithm === 'string' || algorithm instanceof String ? name = algorithm : algorithm.name;
if (!name) return false;
name = name.toUpperCase(); // Digest algorithm for key derivation
if ((name.indexOf('KDF') >= 0 || name.indexOf('HMAC') >= 0) && algorithm.hash) return checkNative(algorithm.hash); // True if no supported names
return name.indexOf('GOST') === -1 && name.indexOf('SHA-1') === -1 && name.indexOf('RC2') === -1 && name.indexOf('?DES') === -1;
} // </editor-fold>
/*
* Key conversion methods
*
*/
// <editor-fold defaultstate="collapsed">
// Check key parameter
function checkKey(key, method) {
if (!key.algorithm) throw new SyntaxError('Key algorithm not defined');
if (!key.algorithm.name) throw new SyntaxError('Key algorithm name not defined');
var name = key.algorithm.name,
gostCipher = name === 'GOST 28147' || name === 'GOST R 34.12' || name === 'RC2',
gostDigest = name === 'GOST R 34.11' || name === 'SHA',
gostSign = name === 'GOST R 34.10';
if (!gostCipher && !gostSign && !gostDigest) throw new NotSupportedError('Key algorithm ' + name + ' is unsupproted');
if (!key.type) throw new SyntaxError('Key type not defined');
if ((gostCipher || gostDigest) && key.type !== 'secret' || gostSign && !(key.type === 'public' || key.type === 'private')) throw new DataError('Key type ' + key.type + ' is not valid for algorithm ' + name);
if (!key.usages || !key.usages.indexOf) throw new SyntaxError('Key usages not defined');
for (var i = 0, n = key.usages.length; i < n; i++) {
var md = key.usages[i];
if ((md === 'encrypt' || md === 'decrypt') && key.type !== 'secret' || md === 'sign' && key.type === 'public' || md === 'verify' && key.type === 'private') throw new InvalidStateError('Key type ' + key.type + ' is not valid for ' + md);
}
if (method) if (key.usages.indexOf(method) === -1) throw new InvalidAccessError('Key usages is not contain method ' + method);
if (!key.buffer) throw new SyntaxError('Key buffer is not defined');
var size = key.buffer.byteLength * 8,
keySize = 8 * key.algorithm.keySize;
if (key.type === 'secret' && size !== (keySize || 256) && (key.usages.indexOf('encrypt') >= 0 || key.usages.indexOf('decrypt') >= 0) || key.type === 'private' && !(size === 256 || size === 512) || key.type === 'public' && !(size === 512 || size === 1024)) throw new SyntaxError('Key buffer has wrong size ' + size + ' bit');
} // Extract key and enrich cipher algorithm
function extractKey(method, algorithm, key) {
checkKey(key, method);
if (algorithm) {
var params;
switch (algorithm.mode) {
case 'ES':
params = ['sBox', 'keyMeshing', 'padding', 'block'];
break;
case 'SIGN':
params = ['namedCurve', 'namedParam', 'sBox', 'curve', 'param', 'modulusLength'];
break;
case 'MAC':
params = ['sBox'];
break;
case 'KW':
params = ['keyWrapping', 'ukm'];
break;
case 'DH':
params = ['namedCurve', 'namedParam', 'sBox', 'ukm', 'curve', 'param', 'modulusLength'];
break;
case 'KDF':
params = ['context', 'label'];
break;
case 'PBKDF2':
params = ['sBox', 'iterations', 'salt'];
break;
case 'PFXKDF':
params = ['sBox', 'iterations', 'salt', 'diversifier'];
break;
case 'CPKDF':
params = ['sBox', 'salt'];
break;
}
if (params) params.forEach(function (name) {
key.algorithm[name] && (algorithm[name] = key.algorithm[name]);
});
}
return key.buffer;
} // Make key definition
function convertKey(algorithm, extractable, keyUsages, keyData, keyType) {
var key = {
type: keyType || (algorithm.name === 'GOST R 34.10' ? 'private' : 'secret'),
extractable: extractable || 'false',
algorithm: algorithm,
usages: keyUsages || [],
buffer: keyData
};
checkKey(key);
return key;
}
function convertKeyPair(publicAlgorithm, privateAlgorithm, extractable, keyUsages, publicBuffer, privateBuffer) {
if (!keyUsages || !keyUsages.indexOf) throw new SyntaxError('Key usages not defined');
var publicUsages = keyUsages.filter(function (value) {
return value !== 'sign';
});
var privateUsages = keyUsages.filter(function (value) {
return value !== 'verify';
});
return {
publicKey: convertKey(publicAlgorithm, extractable, publicUsages, publicBuffer, 'public'),
privateKey: convertKey(privateAlgorithm, extractable, privateUsages, privateBuffer, 'private')
};
} // Swap bytes in buffer
function swapBytes(src) {
if (src instanceof CryptoOperationData) src = new Uint8Array(src);
var dst = new Uint8Array(src.length);
for (var i = 0, n = src.length; i < n; i++) {
dst[n - i - 1] = src[i];
}
return dst.buffer;
} // </editor-fold>
/**
* Promise stub object (not fulfill specification, only for internal use)
* Class not defined if Promise class already defined in root context<br><br>
*
* The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:
* <ul>
* <li>pending: initial state, not fulfilled or rejected.</li>
* <li>fulfilled: successful operation</li>
* <li>rejected: failed operation.</li>
* </ul>
* Another term describing the state is settled: the Promise is either fulfilled or rejected, but not pending.<br><br>
* @class Promise
* @global
* @param {function} executor Function object with two arguments resolve and reject.
* The first argument fulfills the promise, the second argument rejects it.
* We can call these functions, once our operation is completed.
*/
// <editor-fold defaultstate="collapsed">
if (!root.Promise) {
root.Promise = function () {
function mswrap(value) {
if (value && value.oncomplete === null && value.onerror === null) {
return new Promise(function (resolve, reject) {
value.oncomplete = function () {
resolve(value.result);
};
value.onerror = function () {
reject(new OperationError(value.toString()));
};
});
} else return value;
}
function Promise(executor) {
var state = 'pending',
result,
resolveQueue = [],
rejectQueue = [];
function call(callback) {
try {
callback();
} catch (e) {}
}
try {
executor(function (value) {
if (state === 'pending') {
state = 'fulfilled';
result = value;
resolveQueue.forEach(call);
}
}, function (reason) {
if (state === 'pending') {
state = 'rejected';
result = reason;
rejectQueue.forEach(call);
}
});
} catch (error) {
if (state === 'pending') {
state = 'rejected';
result = error;
rejectQueue.forEach(call);
}
}
/**
* The then() method returns a Promise. It takes two arguments, both are
* callback functions for the success and failure cases of the Promise.
*
* @method then
* @memberOf Promise
* @instance
* @param {function} onFulfilled A Function called when the Promise is fulfilled. This function has one argument, the fulfillment value.
* @param {function} onRejected A Function called when the Promise is rejected. This function has one argument, the rejection reason.
* @returns {Promise}
*/
this.then = function (onFulfilled, onRejected) {
return new Promise(function (resolve, reject) {
function asyncOnFulfilled() {
var value;
try {
value = onFulfilled ? onFulfilled(result) : result;
} catch (error) {
reject(error);
return;
}
value = mswrap(value);
if (value && value.then && value.then.call) {
value.then(resolve, reject);
} else {
resolve(value);
}
}
function asyncOnRejected() {
var reason;
try {
reason = onRejected ? onRejected(result) : result;
} catch (error) {
reject(error);
return;
}
reason = mswrap(reason);
if (reason && reason.then && reason.then.call) {
reason.then(resolve, reject);
} else {
reject(reason);
}
}
if (state === 'fulfilled') {
asyncOnFulfilled();
} else if (state === 'rejected') {
asyncOnRejected();
} else {
resolveQueue.push(asyncOnFulfilled);
rejectQueue.push(asyncOnRejected);
}
});
};
/**
* The catch() method returns a Promise and deals with rejected cases only.
* It behaves the same as calling Promise.prototype.then(undefined, onRejected).
*
* @method catch
* @memberOf Promise
* @instance
* @param {function} onRejected A Function called when the Promise is rejected. This function has one argument, the rejection reason.
* @returns {Promise}
*/
this['catch'] = function (onRejected) {
return this.then(undefined, onRejected);
};
}
/**
* The Promise.all(iterable) method returns a promise that resolves when all
* of the promises in the iterable argument have resolved.<br><br>
*
* The result is passed as an array of values from all the promises.
* If something passed in the iterable array is not a promise, it's converted to
* one by Promise.resolve. If any of the passed in promises rejects, the
* all Promise immediately rejects with the value of the promise that rejected,
* discarding all the other promises whether or not they have resolved.
*
* @method all
* @memberOf Promise
* @static
* @param {KeyUsages} promises Array with promises.
* @returns {Promise}
*/
Promise.all = function (promises) {
return new Promise(function (resolve, reject) {
var result = [],
count = 0;
function asyncResolve(k) {
count++;
return function (data) {
result[k] = data;
count--;
if (count === 0) resolve(result);
};
}
function asyncReject(reason) {
if (count > 0) reject(reason);
count = 0;
}
for (var i = 0, n = promises.length; i < n; i++) {
var data = promises[i];
if (data.then && data.then.call) data.then(asyncResolve(i), asyncReject);else result[i] = data;
}
if (count === 0) resolve(result);
});
};
return Promise;
}();
} // </editor-fold>
/*
* Worker executor
*
*/
// <editor-fold defaultstate="collapsed">
var baseUrl = '',
nameSuffix = ''; // Try to define from DOM model
if (typeof document !== 'undefined') {
(function () {
var regs = /^(.*)gostCrypto(.*)\.js$/i;
var list = document.querySelectorAll('script');
for (var i = 0, n = list.length; i < n; i++) {
var value = list[i].getAttribute('src');
var test = regs.exec(value);
if (test) {
baseUrl = test[1];
nameSuffix = test[2];
}
}
})();
} // Local importScripts procedure for include dependens
function importScripts() {
for (var i = 0, n = arguments.length; i < n; i++) {
var name = arguments[i].split('.'),
src = baseUrl + name[0] + nameSuffix + '.' + name[1];
var el = document.querySelector('script[src="' + src + '"]');
if (!el) {
el = document.createElement('script');
el.setAttribute('src', src);
document.head.appendChild(el);
}
}
} // Create Worker
var worker,
tasks = [],
sequence = 0; // Worker will create only for first child process and
// Gost implementation libraries not yet loaded
if (!root.importScripts && !root.gostEngine) {
try {
worker = new Worker(baseUrl + 'gostEngine' + nameSuffix + '.js'); // Result of opertion
worker.onmessage = function (event) {
// Find task
var id = event.data.id;
for (var i = 0, n = tasks.length; i < n; i++) {
if (tasks[i].id === id) break;
}
if (i < n) {
var task = tasks[i];
tasks.splice(i, 1); // Reject if error or resolve with result
if (event.data.error) task.reject(new OperationError(event.data.error));else task.resolve(event.data.result);
}
}; // Worker error - reject all waiting tasks
worker.onerror = function (event) {
for (var i = 0, n = tasks.length; i < n; i++) {
tasks[i].reject(event.error);
}
tasks = [];
};
} catch (e) {
// Worker is't supported
worker = false;
}
}
if (!root.importScripts) {
// This procedure emulate load dependents as in Worker
root.importScripts = importScripts;
}
if (!worker) {
// Import main module
// Reason: we are already in worker process or Worker interface is not
// yet supported
// root.gostEngine || importScripts('gostEngine.js'); // SRV
root.gostEngine = require('./gostEngine'); // SRV
} // Executor for any method
function execute(algorithm, method, args) {
return new Promise(function (resolve, reject) {
try {
if (worker) {
var id = ++sequence;
tasks.push({
id: id,
resolve: resolve,
reject: reject
});
worker.postMessage({
id: id,
algorithm: algorithm,
method: method,
args: args
});
} else {
if (root.gostEngine) resolve(root.gostEngine.execute(algorithm, method, args));else reject(new OperationError('Module gostEngine not found'));
}
} catch (error) {
reject(error);
}
});
} // Self resolver
function call(callback) {
try {
callback();
} catch (e) {}
} // </editor-fold>
/*
* WebCrypto common class references
*
*/
// <editor-fold defaultstate="collapsed">
/**
* The Algorithm object is a dictionary object [WebIDL] which is used to
* specify an algorithm and any additional parameters required to fully
* specify the desired operation.<br>
* <pre>
* dictionary Algorithm {
* DOMString name;
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#algorithm-dictionary}
* @class Algorithm
* @param {DOMString} name The name of the registered algorithm to use.
*/
/**
* AlgorithmIdentifier - Algorithm or DOMString name of algorithm<br>
* <pre>
* typedef (Algorithm or DOMString) AlgorithmIdentifier;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#algorithm-dictionary}
* @class AlgorithmIdentifier
*/
/**
* The KeyAlgorithm interface represents information about the contents of a
* given Key object.
* <pre>
* interface KeyAlgorithm {
* readonly attribute DOMString name
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-algorithm-interface}
* @class KeyAlgorithm
* @param {DOMString} name The name of the algorithm used to generate the Key
*/
/**
* The type of a key. The recognized key type values are "public", "private"
* and "secret". Opaque keying material, including that used for symmetric
* algorithms, is represented by "secret", while keys used as part of asymmetric
* algorithms composed of public/private keypairs will be either "public" or "private".
* <pre>
* typedef DOMString KeyType;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class KeyType
*/
/**
* Sequence of operation type that may be performed using a key. The recognized
* key usage values are "encrypt", "decrypt", "sign", "verify", "deriveKey",
* "deriveBits", "wrapKey" and "unwrapKey".
* <pre>
* typedef DOMString[] KeyUsages;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class KeyUsages
*/
/**
* The Key object represents an opaque reference to keying material that is
* managed by the user agent.<br>
* This specification provides a uniform interface for many different kinds of
* keying material managed by the user agent. This may include keys that have
* been generated by the user agent, derived from other keys by the user agent,
* imported to the user agent through user actions or using this API,
* pre-provisioned within software or hardware to which the user agent has
* access or made available to the user agent in other ways. The term key refers
* broadly to any keying material including actual keys for cryptographic
* operations and secret values obtained within key derivation or exchange operations.<br>
* The Key object is not required to directly interface with the underlying key
* storage mechanism, and may instead simply be a reference for the user agent
* to understand how to obtain the keying material when needed, eg. when performing
* a cryptographic operation.
* <pre>
* interface Key {
* readonly attribute KeyType type;
* readonly attribute boolean extractable;
* readonly attribute KeyAlgorithm algorithm;
* readonly attribute KeyUsages usages;
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class Key
* @param {KeyType} type The type of a key. The recognized key type values are "public", "private" and "secret".
* @param {boolean} extractable Whether or not the raw keying material may be exported by the application.
* @param {KeyAlgorithm} algorithm The Algorithm used to generate the key.
* @param {KeyUsages} usages Key usage array: type of operation that may be performed using a key.
*/
/**
* The KeyPair interface represents an asymmetric key pair that is comprised of both public and private keys.
* <pre>
* interface KeyPair {
* readonly attribute Key publicKey;
* readonly attribute Key privateKey;
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#keypair}
* @class KeyPair
* @param {Key} privateKey Private key
* @param {Key} publicKey Public key
*/
/**
* Specifies a serialization format for a key. The recognized key format values are:
* <ul>
* <li>'raw' - An unformatted sequence of bytes. Intended for secret keys.</li>
* <li>'pkcs8' - The DER encoding of the PrivateKeyInfo structure from RFC 5208.</li>
* <li>'spki' - The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.</li>
* <li>'jwk' - The key is represented as JSON according to the JSON Web Key format.</li>
* </ul>
* <pre>
* typedef DOMString KeyFormat;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class KeyFormat
*/
/**
* Binary data
* <pre>
* typedef (ArrayBuffer or ArrayBufferView) CryptoOperationData;
* </pre>
* @class CryptoOperationData
*/
var CryptoOperationData = root.ArrayBuffer;
/**
* DER-encoded ArrayBuffer or PEM-encoded DOMString constains ASN.1 object<br>
* <pre>
* typedef (ArrayBuffer or DOMString) FormatedData;
* </pre>
* @class FormatedData
*/
// </editor-fold>
/**
* The gostCrypto provide general purpose cryptographic functionality for
* GOST standards including a cryptographically strong pseudo-random number
* generator seeded with truly random values.
*
* @namespace gostCrypto
*/
var gostCrypto = {};
/**
* The SubtleCrypto class provides low-level cryptographic primitives and algorithms.
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#subtlecrypto-interface}
*
* @class SubtleCrypto
*/
// <editor-fold>
function SubtleCrypto() {}
/**
* The encrypt method returns a new Promise object that will encrypt data
* using the specified algorithm identifier with the supplied Key.
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-encrypt}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST 28147-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
* <li><b>GOST 28147-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
* <li><b>GOST 28147-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
* <li><b>GOST 28147-CTR</b> "gammirovanie" (counter) mode</li>
* <li><b>GOST 28147-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
* <li><b>GOST R 34.12-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
* <li><b>GOST R 34.12-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
* <li><b>GOST R 34.12-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
* <li><b>GOST R 34.12-CTR</b> "gammirovanie" (counter) mode</li>
* <li><b>GOST R 34.12-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
* </ul>
* For more information see {@link GostCipher}
*
* @memberOf SubtleCrypto
* @method encrypt
* @instance
* @param {AlgorithmIdentifier} algorithm Algorithm identifier
* @param {Key} key Key object
* @param {CryptoOperationData} data Operation data
* @returns {Promise} Promise that resolves with {@link CryptoOperationData}
*/
SubtleCrypto.prototype.encrypt = function (algorithm, key, data) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.encrypt(algorithm, key, data);
algorithm = normalize(algorithm, 'encrypt');
return execute(algorithm, 'encrypt', [extractKey('encrypt', algorithm, key), data]);
});
}; // </editor-fold>
/**
* The decrypt method returns a new Promise object that will decrypt data
* using the specified algorithm identifier with the supplied Key.
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-decrypt}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST 28147-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
* <li><b>GOST 28147-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
* <li><b>GOST 28147-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
* <li><b>GOST 28147-CTR</b> "gammirovanie" (counter) mode</li>
* <li><b>GOST 28147-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
* <li><b>GOST R 34.12-ECB</b> "prostaya zamena" (ECB) mode (default)</li>
* <li><b>GOST R 34.12-CFB</b> "gammirovanie s obratnoj svyaziyu po shifrotekstu" (CFB) mode</li>
* <li><b>GOST R 34.12-OFB</b> "gammirovanie s obratnoj svyaziyu po vyhodu" (OFB) mode</li>
* <li><b>GOST R 34.12-CTR</b> "gammirovanie" (counter) mode</li>
* <li><b>GOST R 34.12-CBC</b> Cipher-Block-Chaining (CBC) mode</li>
* </ul>
* For additional modes see {@link GostCipher}
*
* @memberOf SubtleCrypto
* @method decrypt
* @instance
* @param {AlgorithmIdentifier} algorithm Algorithm identifier
* @param {Key} key Key object
* @param {CryptoOperationData} data Operation data
* @returns {Promise} Promise that resolves with {@link CryptoOperationData}
*/
SubtleCrypto.prototype.decrypt = function (algorithm, key, data) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.decrypt(algorithm, key, data);
algorithm = normalize(algorithm, 'decrypt');
return execute(algorithm, 'decrypt', [extractKey('decrypt', algorithm, key), data]);
});
}; // </editor-fold>
/**
* The sign method returns a new Promise object that will sign data using
* the specified algorithm identifier with the supplied Key.
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-sign}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.10-94</b> GOST Signature</li>
* <li><b>GOST R 34.10-94/GOST R 34.11-94</b> GOST Signature with Hash</li>
* <li><b>GOST R 34.10</b> ECGOST Signature</li>
* <li><b>GOST R 34.10/GOST R 34.11-94</b> ECGOST Signature with Old-Style Hash</li>
* <li><b>GOST R 34.10/GOST R 34.11</b> ECGOST Signature with Streebog Hash</li>
* <li><b>GOST 28147-MAC</b> MAC base on GOST 28147</li>
* <li><b>GOST R 34.12-MAC</b> MAC base on GOST R 43.12</li>
* <li><b>GOST R 34.11-HMAC</b> HMAC base on GOST 34.11</li>
* <li><b>SHA-HMAC</b> HMAC base on SHA</li>
* </ul>
* For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}
*
* @memberOf SubtleCrypto
* @method sign
* @instance
* @param {AlgorithmIdentifier} algorithm Algorithm identifier
* @param {Key} key Key object
* @param {CryptoOperationData} data Operation data
* @returns {Promise} Promise that resolves with {@link CryptoOperationData}
*/
SubtleCrypto.prototype.sign = function (algorithm, key, data) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.sign(algorithm, key, data);
algorithm = normalize(algorithm, 'sign');
var value = execute(algorithm, 'sign', [extractKey('sign', algorithm, key), data]).then(function (data) {
if (algorithm.procreator === 'SC' && algorithm.mode === 'SIGN') {
data = gostCrypto.asn1.GostSignature.encode(data);
}
return data;
});
return value;
});
}; // </editor-fold>
/**
* The verify method returns a new Promise object that will verify data
* using the specified algorithm identifier with the supplied Key.
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-verify}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.10-94</b> GOST Signature</li>
* <li><b>GOST R 34.10-94/GOST R 34.11-94</b> GOST Signature with Hash</li>
* <li><b>GOST R 34.10</b> ECGOST Signature</li>
* <li><b>GOST R 34.10/GOST R 34.11-94</b> ECGOST Signature with Old-Style Hash</li>
* <li><b>GOST R 34.10/GOST R 34.11</b> ECGOST Signature with Streebog Hash</li>
* <li><b>GOST 28147-MAC</b> MAC base on GOST 28147</li>
* <li><b>GOST R 34.12-MAC</b> MAC base on GOST R 34.12</li>
* <li><b>GOST R 34.11-HMAC</b> HMAC base on GOST 34.11</li>
* <li><b>SHA-HMAC</b> HMAC base on SHA</li>
* </ul>
* For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}
*
* @memberOf SubtleCrypto
* @method verify
* @instance
* @param {AlgorithmIdentifier} algorithm Algorithm identifier
* @param {Key} key Key object
* @param {CryptoOperationData} signature Signature data
* @param {CryptoOperationData} data Operation data
* @returns {Promise} Promise that resolves with boolean value of verification result
*/
SubtleCrypto.prototype.verify = function (algorithm, key, signature, data) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.verify(algorithm, key, signature, data);
algorithm = normalize(algorithm, 'verify');
if (algorithm.procreator === 'SC' && algorithm.mode === 'SIGN') {
var obj = gostCrypto.asn1.GostSignature.decode(signature);
signature = {
r: obj.r,
s: obj.s
};
}
return execute(algorithm, 'verify', [extractKey('verify', algorithm, key), signature, data]);
});
}; // </editor-fold>
/**
* The digest method returns a new Promise object that will digest data
* using the specified algorithm identifier.
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-digest}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.11-94</b> Old-Style GOST Hash</li>
* <li><b>GOST R 34.11</b> GOST Streebog Hash</li>
* <li><b>SHA</b> SHA Hash</li>
* </ul>
* For additional modes see {@link GostDigest}
*
* @memberOf SubtleCrypto
* @method digest
* @instance
* @param {AlgorithmIdentifier} algorithm Algorithm identifier
* @param {CryptoOperationData} data Operation data
* @returns {Promise} Promise that resolves with {@link CryptoOperationData}
*/
SubtleCrypto.prototype.digest = function (algorithm, data) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.digest(algorithm, data);
algorithm = normalize(algorithm, 'digest');
return execute(algorithm, 'digest', [data]);
});
}; // </editor-fold>
/**
* The generateKey method returns a new Promise object that will key(s) using
* the specified algorithm identifier. Key can be used in according with
* KeyUsages sequence. The recognized key usage values are "encrypt", "decrypt",
* "sign", "verify", "deriveKey", "deriveBits", "wrapKey" and "unwrapKey".
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-generateKey}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.10</b> ECGOST Key Pairs</li>
* <li><b>GOST 28147</b> Key for encryption GOST 28147 modes</li>
* <li><b>GOST 28147-KW</b> Key for wrapping GOST 28147 modes</li>
* <li><b>GOST R 34.12</b> Key for encryption GOST R 34.12 modes</li>
* <li><b>GOST R 34.12-KW</b> Key for wrapping GOST R 34.12 modes</li>
* <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
* </ul>
* For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}<br>
* Note: Generation key for GOST R 34.10-94 not supported.
*
* @memberOf SubtleCrypto
* @method generateKey
* @instance
* @param {AlgorithmIdentifier} algorithm Key algorithm identifier
* @param {boolean} extractable Whether or not the raw keying material may be exported by the application
* @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key
* @returns {Promise} Promise that resolves with {@link Key} or {@link KeyPair} in according to key algorithm
*/
SubtleCrypto.prototype.generateKey = function (algorithm, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.generateKey(algorithm, extractable, keyUsages);
var privateAlgorithm = algorithm.privateKey,
publicAlgorithm = algorithm.publicKey;
algorithm = normalize(algorithm, 'generateKey');
if (privateAlgorithm) privateAlgorithm = normalize(privateAlgorithm, 'generateKey');else privateAlgorithm = algorithm;
if (publicAlgorithm) publicAlgorithm = normalize(publicAlgorithm, 'generateKey');else publicAlgorithm = algorithm;
return execute(algorithm, 'generateKey', []).then(function (data) {
if (data.publicKey && data.privateKey) return convertKeyPair(publicAlgorithm, privateAlgorithm, extractable, keyUsages, data.publicKey, data.privateKey);else return convertKey(algorithm, extractable, keyUsages, data);
});
});
}; // </editor-fold>
/**
* The deriveKey method returns a new Promise object that will key(s) using
* the specified algorithm identifier. Key can be used in according with
* KeyUsage sequence. The recognized key usage values are "encrypt", "decrypt",
* "sign", "verify", "deriveKey", "deriveBits", "wrapKey" and "unwrapKey".
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-deriveKey}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.10-DH</b> ECDH Key Agreement mode</li>
* <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-PFXKDF</b> PFX Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-CPKDF</b> Password Based Key for CryptoPro Derivation Algorithm</li>
* <li><b>SHA-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
* <li><b>SHA-PFXKDF</b> PFX Key for Derivation Algorithm</li>
* </ul>
* For additional modes see {@link GostSign} and {@link GostDigest}
*
* @memberOf SubtleCrypto
* @method deriveKey
* @instance
* @param {AlgorithmIdentifier} algorithm Algorithm identifier
* @param {Key} baseKey Derivation key object
* @param {AlgorithmIdentifier} derivedKeyType Derived key algorithm identifier
* @param {boolean} extractable Whether or not the raw keying material may be exported by the application
* @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key
* @returns {Promise} Promise that resolves with {@link Key}
*/
SubtleCrypto.prototype.deriveKey = function (algorithm, baseKey, derivedKeyType, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.deriveKey(algorithm, baseKey, derivedKeyType, extractable, keyUsages);
algorithm = normalize(algorithm, 'deriveKey');
derivedKeyType = normalize(derivedKeyType, 'generateKey');
algorithm.keySize = derivedKeyType.keySize;
if (algorithm['public']) {
algorithm['public'].algorithm = normalize(algorithm['public'].algorithm);
algorithm['public'] = extractKey('deriveKey', algorithm, algorithm['public']);
}
return execute(algorithm, 'deriveKey', [extractKey('deriveKey', algorithm, baseKey)]).then(function (data) {
return convertKey(derivedKeyType, extractable, keyUsages, data);
});
});
}; // </editor-fold>
/**
* The deriveBits method returns length bits on baseKey using the
* specified algorithm identifier.
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-deriveBits}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.10-DH</b> ECDH Key Agreement mode</li>
* <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-PFXKDF</b> PFX Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-CPKDF</b> Password Based Key for CryptoPro Derivation Algorithm</li>
* <li><b>SHA-PBKDF2</b> Password Based Key for Derivation Algorithm</li>
* <li><b>SHA-PFXKDF</b> PFX Key for Derivation Algorithm</li>
* </ul>
* For additional modes see {@link GostSign} and {@link GostDigest}
*
* @memberOf SubtleCrypto
* @method deriveBits
* @instance
* @param {AlgorithmIdentifier} algorithm Algorithm identifier
* @param {Key} baseKey Derivation key object
* @param {number} length Length bits
* @returns {Promise} Promise that resolves with {@link CryptoOperationData}
*/
SubtleCrypto.prototype.deriveBits = function (algorithm, baseKey, length) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.deriveBits(algorithm, baseKey, length);
algorithm = normalize(algorithm, 'deriveBits');
if (algorithm['public']) algorithm['public'] = extractKey('deriveBits', algorithm, algorithm['public']);
return execute(algorithm, 'deriveBits', [extractKey('deriveBits', algorithm, baseKey), length]);
});
}; // </editor-fold>
/**
* The importKey method returns a new Promise object that will key(s) using
* the specified algorithm identifier. Key can be used in according with
* KeyUsage sequence. The recognized key usage values are "encrypt", "decrypt",
* "sign", "verify", "deriveKey", "deriveBits", "wrapKey" and "unwrapKey".<br><br>
* Parameter keyData contains data in defined format.
* The suppored key format values are:
* <ul>
* <li>'raw' - An unformatted sequence of bytes. Intended for secret keys.</li>
* <li>'pkcs8' - The DER encoding of the PrivateKeyInfo structure from RFC 5208.</li>
* <li>'spki' - The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.</li>
* </ul>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-importKey}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.10-94</b> GOST Private and Public keys</li>
* <li><b>GOST R 34.10</b> ECGOST Private and Public keys</li>
* <li><b>GOST 28147</b> Key for encryption GOST 28147 modes</li>
* <li><b>GOST 28147-KW</b> Key for key wrapping GOST 28147 modes</li>
* <li><b>GOST R 34.12</b> Key for encryption GOST 34.12 modes</li>
* <li><b>GOST R 34.12-KW</b> Key for key wrapping GOST 34.12 modes</li>
* <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
* </ul>
* For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}<br>
*
* @memberOf SubtleCrypto
* @method importKey
* @instance
* @param {KeyFormat} format Key format Format specifies a serialization format for a key
* @param {CryptoOperationData} keyData
* @param {AlgorithmIdentifier} algorithm Key algorithm identifier
* @param {boolean} extractable Whether or not the raw keying material may be exported by the application
* @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key
* @returns {Promise} Promise that resolves with {@link Key}
*/
SubtleCrypto.prototype.importKey = function (format, keyData, algorithm, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
{
var type;
return new Promise(call).then(function () {
if (checkNative(algorithm)) return rootCrypto.subtle.importKey(format, keyData, algorithm, extractable, keyUsages);
if (format === 'raw') {
algorithm = normalize(algorithm, 'importKey');
if (keyUsages && keyUsages.indexOf) {
var name = algorithm.name.toUpperCase().replace(/[\.\s]/g, '');
if (name.indexOf('3410') >= 0 && keyUsages.indexOf('sign') >= 0) type = 'private';else if (name.indexOf('3410') >= 0 && keyUsages.indexOf('verify') >= 0) type = 'public';
}
return keyData;
} else {
var key;
if (format === 'pkcs8') key = gostCrypto.asn1.GostPrivateKeyInfo.decode(keyData).object;else if (format === 'spki') key = gostCrypto.asn1.GostSubjectPublicKeyInfo.decode(keyData).object;else throw new NotSupportedError('Key format not supported');
algorithm = normalize(key.algorithm, 'importKey');
type = key.type;
if (extractable !== false) extractable = extractable || key.extractable;
if (keyUsages) {
for (var i = 0; i < keyUsages.length; i++) {
if (key.usages.indexOf(keyUsages[i]) < 0) throw DataError('Key usage not valid for this key');
}
} else keyUsages = key.usages;
var data = key.buffer,
keySize = algorithm.keySize,
dataLen = data.byteLength;
if (type === 'public' || keySize === dataLen) return data;else {
// Remove private key masks
if (dataLen % keySize > 0) throw new DataError('Invalid key size');
algorithm.mode = 'MASK';
algorithm.procreator = 'VN';
var chain = [];
for (var i = keySize; i < dataLen; i += keySize) {
chain.push(function (mask) {
return function (data) {
return execute(algorithm, 'unwrapKey', [mask, data]).then(function (data) {
var next = chain.pop();
if (next) return next(data);else {
delete algorithm.mode;
return data;
}
});
};
}(new Uint8Array(data, i, keySize)));
}
return chain.pop()(new Uint8Array(data, 0, keySize));
}
}
}).then(function (data) {
return convertKey(algorithm, extractable, keyUsages, data, type);
});
}; // </editor-fold>
/**
* The exportKey method returns a new Promise object that will key data in
* defined format. <br><br>
* The suppored key format values are:
* <ul>
* <li>'raw' - An unformatted sequence of bytes. Intended for secret keys.</li>
* <li>'pkcs8' - The DER encoding of the PrivateKeyInfo structure from RFC 5208.</li>
* <li>'spki' - The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.</li>
* </ul>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-exportKey}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST R 34.10-94</b> GOST Private and Public keys</li>
* <li><b>GOST R 34.10</b> ECGOST Private and Public keys</li>
* <li><b>GOST 28147</b> Key for encryption GOST 28147 modes</li>
* <li><b>GOST 28147-KW</b> Key for key wrapping GOST 28147 modes</li>
* <li><b>GOST R 34.12</b> Key for encryption GOST R 34.12 modes</li>
* <li><b>GOST R 34.12-KW</b> Key for key wrapping GOST R 34.12 modes</li>
* <li><b>GOST R 34.11-KDF</b> Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-PBKDF2</b> Import Password for Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-PFXKDF</b> Import PFX Key for Derivation Algorithm</li>
* <li><b>GOST R 34.11-CPKDF</b> Import Password Key for CryptoPro Derivation Algorithm</li>
* <li><b>SHA-PBKDF2</b> Import Password for Key for Derivation Algorithm</li>
* <li><b>SHA-PFXKDF</b> Import PFX Key for Derivation Algorithm</li>
* </ul>
* For additional modes see {@link GostSign}, {@link GostDigest} and {@link GostCipher}<br>
*
* @memberOf SubtleCrypto
* @method exportKey
* @instance
* @param {KeyFormat} format Format specifies a serialization format for a key
* @param {Key} key Key object
* @returns {Promise} Promise that resolves with {@link CryptoOperationData}
*/
SubtleCrypto.prototype.exportKey = function (format, key) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (key && checkNative(key.algorithm)) return rootCrypto.subtle.exportKey(format, key);
if (!key.extractable) throw new InvalidAccessError('Key not extractable');
var raw = extractKey(null, null, key);
if (format === 'raw') return raw;else if (format === 'pkcs8' && key.algorithm && key.algorithm.id) {
if (key.algorithm.procreator === 'VN') {
// Add masks for ViPNet
var algorithm = key.algorithm,
mask;
algorithm.mode = 'MASK';
return execute(algorithm, 'generateKey').then(function (data) {
mask = data;
return execute(algorithm, 'wrapKey', [mask, key.buffer]);
}).then(function (data) {
delete algorithm.mode;
var d = new Uint8Array(data.byteLength + mask.byteLength);
d.set(new Uint8Array(data, 0, data.byteLength));
d.set(new Uint8Array(mask, 0, mask.byteLength), data.byteLength);
var buffer = d.buffer;
buffer.enclosed = true;
return gostCrypto.asn1.GostPrivateKeyInfo.encode({
algorithm: algorithm,
buffer: buffer
});
});
} else return gostCrypto.asn1.GostPrivateKeyInfo.encode(key);
} else if (format === 'spki' && key.algorithm && key.algorithm.id) return gostCrypto.asn1.GostSubjectPublicKeyInfo.encode(key);else throw new NotSupportedError('Key format not supported');
});
}; // </editor-fold>
/**
* The wrapKey method returns a new Promise object that will wrapped key(s).
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-wrapKey}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST 28147-KW</b> Key Wrapping GOST 28147 modes</li>
* <li><b>GOST R 34.12-KW</b> Key Wrapping GOST R 34.12 modes</li>
* <li><b>GOST 28147-MASK</b> Key Mask GOST 28147 modes</li>
* <li><b>GOST R 34.12-MASK</b> Key Mask GOST R 34.12 modes</li>
* <li><b>GOST R 34.10-MASK</b> Key Mask GOST R 34.10 modes</li>
* </ul>
* For additional modes see {@link GostCipher}<br>
*
* @memberOf SubtleCrypto
* @method wrapKey
* @instance
* @param {KeyFormat} format Format specifies a serialization format for a key. Now suppored only 'raw' key format.
* @param {Key} key Key object
* @param {Key} wrappingKey Wrapping key object
* @param {AlgorithmIdentifier} wrapAlgorithm Algorithm identifier
* @returns {Promise} Promise that resolves with {@link CryptoOperationData}
*/
SubtleCrypto.prototype.wrapKey = function (format, key, wrappingKey, wrapAlgorithm) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(wrapAlgorithm)) return rootCrypto.subtle.wrapKey(format, key, wrappingKey, wrapAlgorithm);
wrapAlgorithm = normalize(wrapAlgorithm, 'wrapKey');
var keyData = extractKey(null, null, key);
if (wrapAlgorithm.procreator === 'SC' && key.type === 'private') keyData = swapBytes(keyData);
return execute(wrapAlgorithm, 'wrapKey', [extractKey('wrapKey', wrapAlgorithm, wrappingKey), keyData]).then(function (data) {
if (format === 'raw') return data;else throw new NotSupportedError('Key format not supported');
});
});
}; // </editor-fold>
/**
* The unwrapKey method returns a new Promise object that will unwrapped key(s).
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-unwrapKey}<br><br>
*
* Supported algorithm names:
* <ul>
* <li><b>GOST 28147-KW</b> Key Wrapping GOST 28147 modes</li>
* <li><b>GOST R 34.12-KW</b> Key Wrapping GOST R 34.12 modes</li>
* <li><b>GOST 28147-MASK</b> Key Mask GOST 28147 modes</li>
* <li><b>GOST R 34.12-MASK</b> Key Mask GOST R 34.12 modes</li>
* <li><b>GOST R 34.10-MASK</b> Key Mask GOST R 34.10 modes</li>
* </ul>
* For additional modes see {@link GostCipher}<br>
*
* @memberOf SubtleCrypto
* @method unwrapKey
* @instance
* @param {KeyFormat} format Format specifies a serialization format for a key. Now suppored only 'raw' key format.
* @param {CryptoOperationData} wrappedKey Wrapped key data
* @param {Key} unwrappingKey Unwrapping key object
* @param {AlgorithmIdentifier} unwrapAlgorithm Algorithm identifier
* @param {AlgorithmIdentifier} unwrappedKeyAlgorithm Key algorithm identifier
* @param {boolean} extractable Whether or not the raw keying material may be exported by the application
* @param {KeyUsages} keyUsages Key usage array: type of operation that may be performed using a key
* @returns {Promise} Promise that resolves with {@link Key}
*/
SubtleCrypto.prototype.unwrapKey = function (format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages) // <editor-fold defaultstate="collapsed">
{
return new Promise(call).then(function () {
if (checkNative(unwrapAlgorithm)) return rootCrypto.subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable, keyUsages);
unwrapAlgorithm = normalize(unwrapAlgorithm, 'unwrapKey');
unwrappedKeyAlgorithm = normalize(unwrappedKeyAlgorithm, 'importKey');
if (format !== 'raw') throw new NotSupportedError('Key format not supported');
return execute(unwrapAlgorithm, 'unwrapKey', [extractKey('unwrapKey', unwrapAlgorithm, unwrappingKey), wrappedKey]).then(function (data) {
var type;
if (unwrappedKeyAlgorithm && unwrappedKeyAlgorithm.name) {
var name = unwrappedKeyAlgorithm.name.toUpperCase().replace(/[\.\s]/g, '');
if (name.indexOf('3410') >= 0 && keyUsages.indexOf('sign') >= 0) type = 'private';else if (name.indexOf('3410') >= 0 && keyUsages.indexOf('verify') >= 0) type = 'public';
}
if (unwrapAlgorithm.procreator === 'SC' && type === 'private') data = swapBytes(data);
return convertKey(unwrappedKeyAlgorithm, extractable, keyUsages, data, type);
});
});
}; // </editor-fold>
/**
* The subtle attribute provides an instance of the SubtleCrypto
* interface which provides low-level cryptographic primitives and
* algorithms.
*
* @memberOf gostCrypto
* @type SubtleCrypto
*/
gostCrypto.subtle = new SubtleCrypto();
/**
* The getRandomValues method generates cryptographically random values.
*
* First try to use Web Crypto random genereator. Next make random
* bytes based on standart Math.random mixed with time and mouse pointer
*
* @memberOf gostCrypto
* @param {(CryptoOperationData)} array Destination buffer for random data
*/
gostCrypto.getRandomValues = function (array) // <editor-fold defaultstate="collapsed">
{
// Execute randomizer
GostRandom = GostRandom || root.GostRandom;
var randomSource = GostRandom ? new GostRandom() : rootCrypto;
if (randomSource.getRandomValues) randomSource.getRandomValues(array);else throw new NotSupportedError('Random generator not found');
}; // </editor-fold>
// </editor-fold>
return gostCrypto;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostEngine":112,"./gostRandom":114}],111:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file GOST R 34.11-94 / GOST R 34.11-12 implementation
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Converted to JavaScript from source https://www.streebog.net/
* Copyright (c) 2013, Alexey Degtyarev.
* All rights reserved.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostRandom', 'gostCipher'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostRandom'), require('./gostCipher'));
} else {
root.GostDigest = factory(root.GostRandom, root.GostCipher);
} // </editor-fold>
})(void 0, function (GostRandom, GostCipher) {
/*
* GOST R 34.11
* Common methods
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var rootCrypto = root.crypto || root.msCrypto;
var DataError = root.DataError || Error,
NotSupportedError = root.NotSupportedError || Error; // Copy len values from s[sOfs] to d[dOfs]
function arraycopy(s, sOfs, d, dOfs, len) {
for (var i = 0; i < len; i++) {
d[dOfs + i] = s[sOfs + i];
}
} // Swap bytes in buffer
function swap(s) {
var src = new Uint8Array(s),
dst = new Uint8Array(src.length);
for (var i = 0, n = src.length; i < n; i++) {
dst[n - i - 1] = src[i];
}
return dst.buffer;
} // Convert BASE64 string to Uint8Array
// for decompression of constants and precalc values
function b64decode(s) {
// s = s.replace(/[^A-Za-z0-9\+\/]/g, '');
var n = s.length,
k = n * 3 + 1 >> 2,
r = new Uint8Array(k);
for (var m3, m4, u24 = 0, j = 0, i = 0; i < n; i++) {
m4 = i & 3;
var c = s.charCodeAt(i);
c = c > 64 && c < 91 ? c - 65 : c > 96 && c < 123 ? c - 71 : c > 47 && c < 58 ? c + 4 : c === 43 ? 62 : c === 47 ? 63 : 0;
u24 |= c << 18 - 6 * m4;
if (m4 === 3 || n - i === 1) {
for (m3 = 0; m3 < 3 && j < k; m3++, j++) {
r[j] = u24 >>> (16 >>> m3 & 24) & 255;
}
u24 = 0;
}
}
return r.buffer;
} // Random seed
function getSeed(length) {
GostRandom = GostRandom || root.GostRandom;
var randomSource = GostRandom ? new (GostRandom || root.GostRandom)() : rootCrypto;
if (randomSource.getRandomValues) {
var d = new Uint8Array(Math.ceil(length / 8));
randomSource.getRandomValues(d);
return d;
} else throw new NotSupportedError('Random generator not found');
} // Check buffer
function buffer(d) {
if (d instanceof ArrayBuffer) return d;else if (d && d.buffer && d.buffer instanceof ArrayBuffer) return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ? d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;else throw new DataError('ArrayBuffer or ArrayBufferView required');
} // </editor-fold>
/**
* Algorithm name GOST R 34.11 or GOST R 34.11-12<br><br>
*
* http://tools.ietf.org/html/rfc6986
*
* The digest method returns digest data in according to GOST R 4311-2012.<br>
* Size of digest also defines in algorithm name.
* <ul>
* <li>GOST R 34.11-256-12 - 256 bits digest</li>
* <li>GOST R 34.11-512-12 - 512 bits digest</li>
* </ul>
*
* @memberOf GostDigest
* @method digest
* @instance
* @param {(ArrayBuffer|TypedArray)} data Data
* @returns {ArrayBuffer} Digest of data
*/
var digest2012 = function () // <editor-fold defaultstate="collapsed">
{
// Constants
var buffer0 = new Int32Array(16); // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var buffer512 = new Int32Array(16); // [512, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
buffer512[0] = 512; // Constant C
var C = function (s) {
var h = new Int32Array(b64decode(s)),
r = new Array(12);
for (var i = 0; i < 12; i++) {
r[i] = new Int32Array(h.buffer, i * 64, 16);
}
return r;
}('B0Wm8lllgN0jTXTMNnR2BRXTYKQIKkKiAWlnkpHgfEv8xIV1jbhOcRbQRS5DdmovH3xlwIEvy+vp2soe2lsIsbebsSFwBHnmVs3L1xui3VXKpwrbwmG1XFiZ1hJrF7WaMQG1Fg9e1WGYKyMKcur+89e1cA9GneNPGi+dqYq1o2+yCroK9ZYemTHbeoZD9LbCCdtiYDc6ycGxnjWQ5A/i03t7KbEUderyix+cUl9e8QY1hD1qKPw5Cscvzius3HT1LtHjhLy+DCLxN+iToepTNL4DUpMzE7fYddYD7YIs16k/NV5orRxynX08XDN+hY5I3eRxXaDhSPnSZhXos98f71f+bHz9WBdg9WPqqX6iVnoWGicjtwD/36P1OiVHF82/vf8PgNc1njVKEIYWHxwVf2MjqWwMQT+amUdHraxr6ktufWRGekBo+jVPkDZyxXG/tsa+wmYf8gq0t5oct6b6z8aO8Jq0mn8YbKRCUfnEZi3AOTB6O8Okb9nTOh2urk+uk9QUOk1WhojzSjyiTEUXNQQFSiiDaUcGNyyCLcWrkgnJk3oZMz5H08mHv+bHxp45VAkkv/6GrFHsxaruFg7H9B7nAr/UDX+k' + '2ahRWTXCrDYvxKXRK43RaZAGm5LLK4n0msTbTTtEtIke3jaccfi3TkFBbgwCqucDp8mTTUJbH5vbWiODUURhcmAqH8uS3DgOVJwHppqKK3uxzrLbC0QKgIQJDeC3Vdk8JEKJJRs6fTreXxbs2JpMlJsiMRZUWo837ZxFmPvHtHTDtjsV0fqYNvRSdjswbB56SzNprwJn558DYTMbiuH/H9t4iv8c50GJ8/PkskjlKjhSbwWApt6+qxst84HNpMprXdhvwEpZot6Ybkd9Hc2678q5SOrvcR2KeWaEFCGAASBhB6vru2v62JT+WmPNxgIw+4nI79CezXsg1xvxSpK8SJkbstnVF/T6UijhiKqkHeeGzJEYne+AXZufITDUEiD4dx3fvDI8pM16sUkEsIAT0roxFvFn5443'); // Precalc Ax
var Ax = function (s) {
return new Int32Array(b64decode(s));
}('5vh+XFtxH9Alg3eACST6FshJ4H6FLqSoW0aGoY8GwWoLMumi13tBbqvaN6RngVxm9heWqBpoZnb13AtwY5GVS0hi84235kvx/1ximmi9hcXLgn2m/NdXlWbTba9pufCJNWyfdEg9g7B8vOyxI4yZoTanAqwxxHCNnrao0C+839aLGfpR5bOuN5zPtUCKEn0LvAx4tQggj1rlM+OEIojs7c7Cx9N3wV/S7HgXtlBdD165TMLAgzaHHYwgXbTLCwStdjyFWyigiS9YjRt59v8yVz/s9p5DEZM+D8DTn4A6GMnuAQom9fOtgxDv6PRBGXmmXc2hDH3pOhBKG+4dEkjpLFO/8tshhHM5tPUMz6aiPQlftLyc2EeYzeiKLYsHHFb5f3dxaVp1apzF8C5xoLoevKZj+atCFeZyLrGeIt5fu3gNuc4PJZS6FIJSDmOXZk2ELwMeagII6phcfyFEob5r8Ho3yxzRY2Lbg+COK0sxHGTPcEebq5YOMoVrqYa53ucetUeMh3r1bOm4/kKIX2HW/RvdAVaWYjjIYiFXkj74qS78l/9CEUR2+J19NQhWRSzrTJDJsOCnElYjCFAt+8sBbC16A/qnpkhF' + '9G6LOL/GxKu9vvj91HfeujqsTOvIB5t58JyxBeiHnQwn+moQrIpYy4lg58FAHQzqGm+BHko1aSiQxPsHc9GW/0NQGi9gnQqf96UW4MY/N5Yc5KazuNqSUhMkdSw44IqbpahkczvsFU8r8SRXVUmzP9dm2xVEDcXHp9F5455Ct5La3xUaYZl/04agNF7AJxQjONVRe22pOaRlGPB3EEADtAJ5HZClrqLdiNJniZxKXQqTD2bfCihlwk7p1CBFCbCLMlU4kWaFKSpBKQe/xTOoQrJ+K2JUTcZzbFMERWKV4Ada9AbpU1GQih8vO2vBI2Fvw3sJ3FJV5cY5Z9Ezsf5oRCmIOcfw5xHiQJuH9xlk+aLpOK3D20sHGQwLTkf5w+v0VTTVdtNriENGEKBa64sC2CDDzfWCMvJRbeGEDb7Cseeg6N4GsPodCHuFS1QNNDM7QuKaZ7zKW3/YpgiKxDfdDsY7s6nZQ+2BIXFNvV5lo7FnYe3nte6haSQx98jVc6v21R/GheGjZxpeBjzUBBDJLSg6uY8ssEACj+vAbLLy95AX1k8Rb6HTPOBzWfGpnuSqeE7WjHTNwAZuKhnVxztC2ocStBYccEXD' + 'NxWC5O2TIW2s45BBSTn2/H7F8SGGIjt8wLCUBCusFvv510U3mlJ+v3N8Py6jtoFoM+e42brSeMqpoyo0wi/+u+SBY8z+370NjllAJG6lpnBRxu9LhCrR5CK60GUnnFCM2RSIwhhgjO4xnqVJH3zaF9OU4SgTTJxgCUv0MnLV47Ob9hKlpKrXkcy72kPSb/0PNN4fPJRq0lBPW1RomV7ha9+fr2/qj3eUJkjqWHDdCSu/x+Vtcdl8Z93msv9PIdVJPCdrRjroYAORdntPr4bHH2ihPng11LmgtowRXwMMn9QUHdLJFlggAZg9j33dUySsZKpwP8wXUlTCyYmUjgK0Jj5edtafRsLeUHRvA1h9gARF2z2CknLx5WBYSgKbVgvz+65Ypz/83GKhWl5ObK1M6EupblXOH7jMCPl0eq6CslPBAhRM9/tHG58EKJjz6442BosnrfLv+3rtypf+jApevneOBRP099jPMCwlAcMri/eNkt38F1xVTfhlxX9GBS9f6vMwG6Ky9CSqaLfsu9YNhpmPDzUBBHVMAAAAAAAAAADxLjFNNNDM7HEFIr4GGCO1rygNmTDABcGX/VziXWk8ZRmkHMYzzJoV' + 'lYRBcvjHnrjcVDK3k3aEqZQ2wTokkM9YgCsT8zLI71nEQq45fO1PXPoc2O/jq42C8uWslU0pP9Fq2CPokHobfU0iSfg88EO2A8ud2Hn58z3eLS8nNtgmdCpDpB+JHuLfb5iZnRtsEzrUrUbNPfQ2+rs131AmmCXAlk/cqoE+bYXrQbBTfuWlxAVAunWLFghHpBrkO+e7RK/juMQp0GcXl4GZk7vun765rpqN0eyXVCHzVyzdkX5uMWOT19rir/jOR6IgEjfcUzijI0PeyQPuNXn8VsSompHmAbKASNxXUeASlvVk5Lfbe3X3GINRWXoS222VUr3OLjMenbsjHXQwj1INcpP90yLZ4gpEYQwwRnf+7uLStOrUJcow/e4ggAZ1YerKSkcBWhPnSv4UhyZOMCzIg7J78RmlFmTPWbP2gtyoEap8HnivWx1WJvtkjcOytz6RF99bzjTQX3zwarVvXf0lfwrNEycYV03I5nbFKp4HOaflLriqmlSGVT4PPNmjVv9IrqqSe36+dWUlrY4th30ObPn/28hBOx7MoxRQyplpE74w6YPoQK1REAmVbqccsbW2ui20NU5Eab3KTiWgBRWvUoHKD3Hh' + 'dEWYy40OK/JZP5sxKqhjt++zim4ppPxja2qjoEwtSp09lesO5r8x46KRw5YVVL/VGBacju+by/URXWi8nU4oRrqHXxj6z3Qg0e38uLbiPr2wBzby8eNkroTZKc5libb+cLei9tpPclUOclPXXG1JKQTyOj1XQVmnCoBp6gssEI5J0HPFa7EaEYqrehk55P/XzQlaCw44rO/J+2A2WXn1SJK95pfWfzQix4kz4QUUvGHhwdm5dcm1StImYWDPG82AmkSS7Xj9hnGzzKsqiBqXk3LOv2Z/4dCI1tRbXZhalCfIEagFjD9V3mX1tDGWtQYZ90+WsdZwbkOFnR6Ly0PTNlqrioXM+j2E+ce/mcKV/P2iH9Wh3ktjD82z73Y7i0VtgD9Z+Hz3w4WyfHO+XzGRPJjjrGYzsEghv2FnTCa4+BgP+8mVxMEwyKqghiAQdhqYYFfzQiEBFqr2PHYMBlTMNS3bRcxmfZBCvPRalkvUA4Jo6KDD7zxvPae9ktJp/3O8KQriAgHtIoe33jTN6IWBj9kB7qfdYQWb1vonMhmgNVPVbxrodMzOyeoxJFwug/VUcDRVXaB75JnOJtKsVue+9/0WGFelBU44' + 'ag59pFJ0NtFb2Go4HN6f8sr3dWIxdwwysJqu2eJ5yNBd7xCRxgZ02xEQRqJRXlBFI1Ns5HKYAvzFDLz39bY8+nOhaIfNFx8DfSlBr9nyjb0/Xj60Wk87nYTu/jYbZ3FAPbjj0+cHYnEaOij58g/SSH68fHW0nnYndOXyk8frVlwY3PWeT0eLpAxu9E+prctSxpmBLZjax2B4iwbcbkadDvxl+Op1IexOMKX3IZ6OC1Ur7D9lvKV7a93QSWm68bdemZBM2+OU6lcUsgHR5upA9ruwwIJBKErdUPIEY7+PHf/o1/k7k8usuE2Mto5HfIbowd0bOZImjj98WqESCdYvyy89mKvbNcmuZxNpViv9X/UVweFsNs7igB1+su3485sX2pTTfbAN/gGHe8PsdguK2suEld/hU65EBaJHc7e0ELMShXt4PDKr3463cNBoElE7U2c5udLj5mVYTVficbJkaNeJx4/JhJclqTW7+n0a4QKLFTej36ZBiNDNXZvDeN56Ssgsmk2Az7dCd38bg722IHLSiDodM711XnotS6tqj0H02qtruxyV2ZBc/+f9jTG2g6pkIhGbOB/ArvuEQgIsSaD5CMZjAzrj' + 'pCivCASTiCat5Bw0GopTx65xIe535qhdxH9cSiWSnoy1OOmqVc3YYwY3eqna2OspoYroe7MnmJVu39pqNeSEFGt9nRmCUJSn1Bz6VaTobL/lyu3J6kLFnKNsNRwOb8F5UYHk3m+rv4n/8MUwGE0X1J1B6xWEBFiSHA1SUCjXOWHxeOwYDKiFapoFcQGO+BHNQJGifD7178wZrxUjn2Mp0jR0UO/5HrmQ4RtKB43Sd1m5Vh3l/GATMZEvH1otqZPAFlTctluiGRo+Ld4JimuZ64pm1x4PguP+jFGtt9VaCNdFM+UPiUH/fwLm3We9SFns4Giqul321S/CSCbj/0p1pWw5Bw2IrN34ZIZUjEaRpG/Rvr0mE1x8DLMPkwOPFTNKgtmEn8G/mmmcMguoVCD65PpSgkOv+QdnntTWz+loowi4Jf1YLESxR5t2kbxe3LO7x+phkEj+ZRYQY6YfgXryM0fVOGg0CaaTY8LOmExt7TAqn9/YbIHZHXseOwYDKmaUZmCJ6/vZ/YMKWY7mc3UgewdEmhQK/ElfLKilcbZZMjQfmG+KRbvC+zgapKBQs3LCVCOjrdgfrzoXJzwLi4a7bP6DJY3IabWi' + 'KHkCv9HJgPH1qUvWazg3r4iACnmyyroSVVBDEAg7DUzfNpQOB7nusgTRp85nkLLFYSQT//EltNwm8SuXxSwST4YII1GmLyis75NjL5k35ec1B7BSKTob5ucsMK5XCpxw01hgQa4UJeDeRXSz151MxJK6IoBAxWha8AsMpdyMJxy+Eofx9pxabvOeMX+x4NyGSV0RQCDsNC1pm0B+PxjNS9yjqdRq1RUoDR0U8nmJaSQAAAAAAAAAAFk+t1+hlsYeLk54FgsRa9htSuewWIh/juZf0BOHLj4Gem3bu9MOxOKsl/yJyq7xsQnMszweGdvhifPqxGLuGGR3cM9JqoetxlbFfsplV/bWA5U92m1s+5o2ko2IRFbgfB7rjzeVn2CNMdYXnE6qqSNvrDrX5cAmYkMEn6ZTmRRWq9NmncBSuO6vAsFTp8IKKzzLA243I8AHk8nCPZDhyizDO8ZeL27X00z/VjOXWCSeselOZDJdaqY34W01lHJCCnn45mG+Yj94UhTZBALHRBNILvH98MiWWxP2m8XsFgmpDogpKBTlkr5OGYtUKhB9cszAD8vrr+cbG0nIRCIrcD4lZBZNqEDp1SDGUT4f9Plm' + 'usMgP5EM6Kvy7dHCYcR+8IFMuUWs02Hzlf64lEo5IQVcnPAsFiLWrZcYZfP3cXjpvYe6K5vwofREQAWyWWVdCe11vkgkf7wLdZYSLhfP9Cq0SwkXhel6FZZrhU4nVdqf7uCDkkkTR5EyQypGI8ZSuahGW0etPkN0+LRfJBKxXoskF/bweGRLo/shYv5/3aURS7vMJ52kbcEBc+C90CSidiIgjFmivKCKj8SQbbg2803kuQ10OmZn6nFHteBwX0bvJ4LLKhUIsDnsBl719FsefSG1sYPP0FsQ2+czwGApXHefpzZyOUwBfs9VMhGGwxyB2HIOGg1Fp+07j5l6Pd+JWDr8ecft+ysu6aQZhkPvDs5fCc32e04tN09qa+n6NN8Etq3UcDihI/mNIk0KBX6qocliSLhcG/eo4/2XYDCaLrULKm5bo1GCDetCxOH+p1cilI1YKZodg3N/z5zIZLrUUaVbT7XUtypQCL9Tgc49eZdGptjV5C0E5dIrgPx+MIeWV7aed7VzVKA5aUQdgJfQtDMwyvvz4vDP4o533eC+jMNisS4lnElPRqbOcm+529HKQeJCwe7RTbp2Ay/0eqMPsEWyaKk6zeTM' + 'r38L6IRUnQgEg1SzwUaCY5JUNcLIDv7S7k438n/f+6cWejOSDGDxTfsSO1LqA+WESgyrU/27kAed6vY4D3iKGctI7FWPDLMqtZ3Estb+9+Dc28oi9PPsthHfWBNUmpxA4z/e31aKztOgwcgSQyLpwwela4FY+m0NdyeVebHh893ZsYt0QirABLjsLZ//q8KU9Kz4qC11kU97v2mx7ytoeMT2L69Iesfhds6AnMZ+XQxnEdiPkuTBTGJ7mdkkPe3+I0qlw9+2i1GQmx8VJi2/bU9m6gVLYry1GuLPWlKqaui+oFP70M4BSO1oCMDmYxTJQ/4WzRWoJxDNBJIxoGlw9ue8imyXzEywM3zoNfyzucBl3vJYfMeA81IhTt5BMrtQlfFeQ5D0k9+HCDliXdLg8UExPBr7i2avkXIK8FGyEbxHfUJ+1O6lcy47TO72474lgmJ4NOsLzEOcA+PdeOckyCh3MorZhn35FLUZReJDsPJXSw+I9+uX4oi2+piapJQ6GcTwaMsWhYZQ7mQJrxH6733zF9XATqukelZ8VJi0xqm2u/uAT0IYjjzCK887xc0L0EM26qo5dxPwL6wb7DMTLCUG26fw00iN' + '1+Zda/LDGh5eubIWH/gg9YQuBlDEbg+fcWvrHZ6EMAGpM3WMqzFe1D/kFP2ieSJlJ8nxcB7wCTJzpMHKcKdxvpQYS6bnaz0OQNgp/4wUyH4PvsP6x3Z0yzYWqWNKapVyjxORGcJe+Tf1Re1NWuo/nugCSZZQujh7ZDfnvQtYLiLmVZ+J4FPiYYCtUuMFKI38bcVaI+NLmTXeFOD1GtCtCcY5BXimWYZeltdhcQlIfLHi1ss6IRVgAgHpFeV3n67RrbAhP2p33LeYgLduuaGmq12fjSSGRM+b/V5FNsVmJljxxrn+m6y9/erNY0G+mXnE76ciFwhAVXZRB3Hs2I5UPsK6UctnHwQ9CtSCrHGvWHn+eHoEXNrJNrI4rzOOBJrtvYZsyUly7iZhXabrvYECkDKV/dCLLBcR+DQEYHO/CurzCZMpdY/8QhyusT59z6k0uiMHSBGIgysk785Ch0zmXA5X1h+w6doas9G61vmbNDzAdXsciTxFgitRDbhAOpKXXHaYwfHbYUo+DQEY1eaMtNYPSI6FXLTPrpYeDfPLM9k6jlWrFKAO10IXAyhiN4nBg4tt0ZyUYpKJX+997Ts668/LuOZOSjFJ' + 'Bkx+ZC9lw9w9Kz4qTFpj2lvT80CpIQxHtHTRV6FhWTGsWTTaHehyZm7jZRF693ZbyG7TZxawXESbpohcIB1JxbkFOHqINGxFExByxLq53f+/SUYep1GvmdUpd7wc4FuhsPeF5GAn21JUbTC6bld4jDBa1wdlD1auyYfGgmEv8pWlq4lE9fvFcX7VKOdZ8kTKjdy7zix9uIiqFUq+Mo2xuh5hm+mT7OiLCfK9nugTtxd0AapLKF0csyGFjxQxlcruSMOBhBOY0bj8t1DTsvmIiTmoapmNHOG5H4iODORzRlp4mVaDdpeHFgLPKtfuI0G/hccTtbPxoU7/kW/hK0Vn53waAjC30QV1DJj8yF7Km6Wj5/cg2p4GrWpgMaK7sfQ4lz50lH7X0mAs9GY5GMD/ml9Qp/NoZ44kNNmDtKRJ1M1orxt1VZK1h388PQIubeobq/xfW0USH2sNcektKVU1dN/99RBtTwPYCBuoe5+MGcbbfqGjrAmBu7vKEq1mFy36eXBDZgEIKccXkyZ3e/9fnAAAAAAAAAAA6yR2pMkG1xVyTdQvBzjfb7dS7mU43bZfN/+8hj31O6OO+oT8tcFX5unrXHMnJZaq' + 'GwvavyU1xDmG4SyHKk1OIJlpoovOPgh6+vsut52cS1UFakFWttksslo65qXevqKWIqOwJqgpJYBTyFs7Nq0VgbEekAEXuHWDxR86Sj/laTDgGeHtzzYhveyBHSWR/LoYRFt9TE1SSh2o2mBp3K7wBVj1zHIwneMp1MBiWWt/9XDOIq0DOdWfmFkc2ZdHAk34i5DFqgMYe1T2Y9J/w1bQ8NhYnpE1tW7VNTCWUdPWehwS+WchzSZzLtKMHD1EGjasSSqUYWQHf2ktHXPcb19RS28KcPQNaNiKYLSzDsoerEHTZQnYM4WYfQs9l0kGMPaonszJCpbEZXeiDuLFrQGofOSatV4OcKPepEKcoYJka6Dal7RG25Yvaszth9TX9t4nKrgYXTelPEafJdzv4VvLpsGcbvn+o+tTp2SjkxvYhM4v0lkLgXwQ9FaiGm2AdDkz5XOgu3nvDQ8VXAygldweI2wsT8aU1DfkEDZN9iMFMpHdMt/Hg2xCZwMmPzKZvO9uZvjNauV7b52MNa4rW+IWWTGzwuISkPh/k70gJ7+RUANpRg6QIg0bVimeJ2+uGdMoY5KMPFOiQy9wgv746Rue0LxveSw+7UD3' + 'TEDVN9LeU9t16L+uX8KyYk2pwNKlQf0KTo//4Dz9EmQmIOSVaW+n4+Hw9Ai4qY9s0aojD92m2cLH0BCd0cYoj4p50E90h9WFRpRXm6NxC6I4QX98+oNPaB1HpNsKUAflIGya8UYKZD+hKN33NL1HEoFERwZytyMt8uCGzAIQUpMYLeWNvIkrV8qh+bD4kx37a4kkR8wuWun53RGFBCCkO0vlvraKJD7WVYQlXxnI1l07Z0BOYz+gBqaNtnZsRyof94rHmrTJfiHDU0QuEICq7JpPnblXgucUBbp7yCybMiAxpUZl+LZeT7G2Ufd1R/TUi/oNhXukZoKFqWxaoWqYu5kPrvkI63nJoV43okf0pi12hX3NXSd0HvjFC4AKGCC8vmXcsgH3orRmbRuYb5Qm50zJIb9TxOZIlUEKD5PZykIgzcyqZHuk70KaQGCJChhxDE6k9psys4vM2jYt3jVM05bcI7x8Wy+pwwm7aKqFGrPSYTGnNkjgEwIdxSlB/E2yzVrat3BL5IqneWXZhO1x5jI4b9YXNLuk6C1t1TirckVcIUfqYXe0sV2hq3DPCRzorJB/znK4vf9XyF39lyJ4qKTkTGprb5QN' + 'OFGZW08f3+RiV4zK7XG8ntmIK7DAHSwKkXudXRE8UDuiwx4RqHZDxuRjySOjmcHO9xaGxX6odtyHtKlz4JbVCa8NVn2dOlgUtAwqP1ncxvQ2AviEldEh3dPh3T2YNkhK+UXnGqRmiOV1GFR+sqWR9ZNmWHRQwB2JnqgQGGWMBltPVAgMvEYDoy0DhMZRN7893DJQeOyGHirqMKj8eVc/9yFNIDDKBQy2ZfAyK4AWwwxpvpbdGyRwh9uV7pmB4WG40fwYFNnKBfiCDtK7zA3nKWPXYFBDDxTHO8yw6KCdOg+OQHZNVz9UojnRdcHhYXe9EvWjfHNPH0urN8EvH9/CbVZIsWc5XNDxbATtFTe/QqftlxYdFDBAZX1sZ9qrcrgH7Bf6h7pO6Dzfr3nLAwT7wXM/BgVxvEY+eNYcEofpiifQfPSOd7StobnCYlNskN0m4kSbWGCAFgWPwJrX+UH8+/rYzqlL5G0Oo0PyiwYI65+bEmvQSRc0e5qSh0rnaZwiGwF8QsTmnuA6TFxyDuOSVktun14+o5naa6NT9FrYPTXn/uCQTBskJSLQCYMlh+ldhCmAwA8UMOLGs8Cghh4okwh0M6QZ1yny' + 'NB89rdQtbG/uCj+u+7Kljkruc8SQ3TGDqrcttbGhajSpKgQGXiOP33tLNaFoa2/MaiO/bvSmlWwZHLlrhRrTUlXVmNTW3jUayWBN5fKufvMcpsKjqYHhct4vlVGtelOYMCWq/1bI9hYVUh2dHihg2VBv4xz6RQc6GJxV8StkewsBgOyarn6oWXzsi0AFDBBeI1DlGYv5QQTvitM0VcwN1wenvuFtZ3+S5eMluQ3naZdaBhWRom5jerYR7xYYIItGCfTfPrepgaseuweK6H2swLeRA4y2XiMfD9ONRXSwVmBn7fcCweqOvrpfS+CDEjjN48R3ws7+vlwNzkhsNUwb0oxds2QWwxkQJuqe0adicyQDnSmz74Ll658o/ILL8q4CqKronPBdJ4ZDGqz6J3SwKM9HH54xt6k4WBvQuOOSLsi8eBmbQAvvBpD7cce/QvhiHzvrEEYDBJloPnpHtVrY3piPQmOmldGQ2AjHKm5jhFMGJ1J7wxnXy+uwRGbXKZeu5n4MCuJljHwU0vEHsFbIgHEiwywwQAuMinrhH9Xaztug3ts46YoOdK0Qk1TcxhWmC+kaF/ZVzBmN3V/+uL2xSb/lMCiviQrt' + '1lum9bStemp5VvCIKZcifhDoZlUys1L5DlNh39rO/jnOx/MEn8kBYf9itWFnf18ul1zPJtIlh/BR7w+GVDuvYy8eQe8Qy/KPUnImNbu5SoiujbrnM0TwTUEHadNmiP2as6uU3jS7uWaAExeSjfGqm6VkoPDFETxU8THUvr2xoRd/caLz6o71tUCHhUnI9lXDfvFOaUTwXezURmPc9VE32PKs/Q1SM0T8AAAAAAAAAABfvG5ZjvVRWhbPNC7xqoUysDa9bds5XI0TdU/m3TG3Ervfp3otbJCUiefIrDpYKzA8aw4JzfpFncSuBYnH4mUhSXNad39f1GjK/WRWHSybGNoVAgMvn8nhiGckNpQmg2k3ghQeO6+JhJy11TEkcEvp19tKbxrT0jOm+YlDKpPZv501OauKDuOwU/LKrxXH4tFuGSg8dkMPFT3r4pNjhO3EXjyCwyCL+QMzuINMuUoT/WRw3rEuaGtVNZ/RN3pTxDZhyqV5AvNZdQQ6l1KC5Zp5/X9wSCaDEpzFLukTaZzNeCi5/w59rI0dVFV0TnignUPLfYjMs1IzQUS9EhtKE8+6TUnNJf26ThE+dssgjAYILz/2J7oieKB2' + 'wolX8gT7supFPf6B5G1n45TB5pU9p2IbLINoXP9JF2TzLBGX/E3spSsk1r2SLmj2sit4RJrFET9I87bt0SF8MS6erXW+tVrWF0/YtF/ULWtO1OSWEjir+pLmtO7+vrXQRqDXMgvvgghHIDuopZEqUST3W/jmnj6W8LE4JBPPCU7+4ln7yQH3dydqcksJHNt9vfj1Ae51R19ZmzwiTeyGkW2EAY+Zwer+dJi45BzbOazgWV5xIXxbtyqkOic8UMCv9QtD7D9UO26Djj4hYnNPcMCUkttFB/9Ycr/qn9/C7mcRaIrPnM36oBqBkNhqmDa5esvZO8YVx5XHMyw6KGCAyoY0RelO6H1Q9pZqX9DW3oXprYFPltXaHHCiL7aePqPVCmn2jVgrZEC4Qo7Jwu51f2BKSeOsjfEsW4b5CwwQyyPh2bLrjwLz7ik5E5TT0iVEyOChf1zQ1qq1jMal96JurYGT+wgjjwLC1caPRlsvn4H8/5zSiP26xXcFkVfzWdxHHSYuOQf/SSv7WCIz5ZrFV92yvOJC+LZzJXe3Ykjgls9vmcSm2D2nTMEUfkHreVcB9IuvdpEqkzc+8p0kmywKGenhYyK2+GIv' + 'VTaZQEd1f3qfTVbVpHsLM4IlZ0ZqoRdMuPUFfesIL7LMSMEL9EdfUzcwiNQnXew6lo9DJRgK7RAXPSMs9wFhUa5O0J+Ub8wT/UtHQcRTmHMbWz8N2ZM3ZS/8sJZ7ZEBS4CN20gqJhAyjrjpwMpsY10GcvSM13oUm+v6/EVt8MZkDlwdPhaqbDcWK1PtINrlwvsYL4/xBBKge/zbcS3CHchMf3DPthFO2CETjPjQXZNMP8RtuqzjNOWQ1Hwp3YbhaO1aU9QnPug4whXCEuHJF0Eevs70il6488rpcL29rVUp0vcR2H09w4c/fxkRx7cRe5hB4TB3ArxZ6yinWPBE/KC3tQRd2qFmvrF8hHpmj1e7UhPlJqH7zOzzjbKWW4BPk0SDwmDqdQyxrxARk3Fl1Y2nV9eXRlWyemulfBDaYuyTJ7MjaZqTvRNaVCMilsurGxAwiNcBQO4A4wZO6jGUhAxzux11GvJ6P0zEBGTdRWtHY4uVohuylD7E3EI1XecmRcJ87aQXKQgZP61CDFoDK7+xFavMkG9I4WNZzr+GBq74kL1Tnytm/jAIR8YENzBn9kLxNuw9DxgqVGERqnaB2HaG/y/E/VwEq' + 'K95PiWHhcrUnuFOoT3MkgbCx5kPfH0thGMw4Qlw5rGjSt/fXvzfYITEDhkowFMcgFKokY3Kr+lxuYA21TrrFdDlHZXQEA6PzCcIV8Lxx5iMqWLlH6YfwRXtM3xi0d73Ylwm165Bsb+BzCDwmgGDZC/7cQA5B+QN+KElIxuRL6bhyjsroCAZb+wYzDp4XSSsaWVCFYWnnKU665PT85sQ2T8p7z5XjDnRJfX/RhqM+lsJSg2EQ2FrWkE36oQIbTNMSkTq7dYclRPrdRuy5FA8VGD1lmmsehpEUwj8sq9cZEJrXE/4GLdRoNtCmBlay+8HcIhxaed2QlJbv0m28obFJNQ537aAjXk/Jy/05W2to9rkN4OrvpvTUxAQi/x8ahTLn+Wm4Xt7WqpR/biAHrvKPPzrQYjuBqTj+ZiTui3qtoae2gujdyFZge6eMxW8oHiowx5slekX6oI1bQXTgZCsws19ji/9+rgJUS8mvnAwF+AjOWTCK+YtGro/FjanMVcOIgDSWx2dtDrHzPKrh5w3XurtiAjJuorS/1QIPhyAYccudXKdUqbcSzoQWadh96DxWimGEeF62c59CC7pssHQeK/EtW2Dqwc5H' + 'dqw19xKDaRwsa7fZ/s7bX/zNsY9MNRqDH3nAEsMWBYLwq62uYqdMt+GlgByC7wb8Z6IYRfLLI1dRFGZfXfBNnb9A/S10J4ZYoDk9P7cxg9oFpAnRkuOwF6n7KM8LQGX5JamiKUK/PXzbdeInA0Y+ArMm4QxatdBs55aOgpWmLea5c/OzY26tQt9XHTgZwwzl7lSbcinXy8USmSr9ZeLRRvjvTpBWsChktwQeE0Aw4ovALt0q2tUJZ5MrSvSK6V0Hb+b7e8bcR4Qjmqy3VfYWZkAaS+29uAfWSF6o04mvYwWkG8IgrbSxPXU7MriXKfIRmX5YS7MyICkdaDGTztocf/9atsDJn4GOFrvV4n9n46GlnTTuJdIzzZj4roU7VKLZbfcK+ssQXnl5XS6ZubukJY5De2dEM0F4AYb2zohmgvDr8JKjuzR70rzX+mLxjR1VrdnX0BHFVx4L0+Rxsb3/3qpsL4CO6v70XuV9MfbIgKT1D6R/8ET8oBrdycNR9bWV6nZkbTNS+SIAAAAAAAAAAIWQnxb1jr6mRilFc6rxLMwKVRK/Odt9Lnjb2Fcx3SbVKc++CGwta0ghi102WDoPmxUs0q36zXis' + 'g6ORiOLHlbzDudplX3+Sap7LoBssHYnDB7X4UJ8vqep+6NbJJpQNzza2fhqvO27KhgeYWXAkJav7eEnf0xqzaUx8V8yTKlHi2WQTpg6KJ/8mPqVmxxWmcWxx/DRDdtyJSk9ZUoRjevja8xTpiyC88lcnaMFKuWaHEIjbfGguyLuIcHX5U3pqYi56RljzAsKiYZEW2+WCCE2ofd4BgybnCdzAGnecaZfo7cOcPax9UMimCjOhoHiowMGoK+RSs4uXP3Rr6hNKiOmiKMy+uv2aJ6vq2U4GjHwE9IlSsXgiflBc9Iyw+wSZWWAX4BVt5Iq9RDi08qc9NTGMUormSf9YhbUV75JN/Pt2DGYcIS6SVjS0kxlcxZp5hpzaUZoh0ZA+MpSBBbW+XC0ZSs6M1F8umEONTKI4Epzbm2+pyr7+OdSBsmAJ7wuMQd7R6/aRpY4VTm2mTZ7mSB9UsG+OzxP9iknYXh0ByeH1r8gmURwJTuP2mKMwde5nrVrHgi7sTbJDjdR8KMGZ2nWJ9oM32xzoks3ON8V8Id2jUwWX3lA8VGBqQvKqVD/3k11yen5zYhup4jKHUwdFnfFWoZ4Pwt/kd8Yd07TNnCJ9' + '5Yd/A5hqNBuUnrKkFcb07WIGEZRgKJNAY4DnWuhOEbCL53K21tDxb1CSkJHVls9t6GeV7D6e4N98+SdIK1gUMshqPhTuwm20cRnNp42swPbkAYnNEAy265KtvDoCj9/3sqAXwtLTUpwgDav40FyNazSnj5ui93c347RxnY8jHwFFvkI8L1u3wfceVf79iOVdaFMDK1nz7m5ls+nE/wc6qncqwzma5evsh4Ful/hCp1sRDi2y4EhKSzMSd8s92N7dvVEMrHnrn6U1IXlVKpH1x4qwqWhG4GptQ8foC0vwszoIybNUaxYe5TnxwjXrqZC+wb7yN2YGx7IsIJIzYUVpqusBUjtvwyialGlTq5Nazt0nKDj2PhM0DosEVeyhK6BSd6GyxJeP+KKlUSLKE+VAhiJ2E1hi0/HN243f3gi3bP5dHhLInkoXig5WgWsDlphn7l95lTMD7Vmv7XSLq3jXHW2Sny35PlPu9dio+Lp5jCr2GbFpjjnPa5Xdry90kQTi7CqcgOCIZCfOXI/YgluV6sTg2Zk6xgJxRpnDpRcwdvk9GxUfUKKfQp7VBeorx1lGNGZaz9x/S5hhsftTKSNC98chwAgOhkEw' + 'hpPNFpb9e3SHJzGScTaxS9NEbIpjoXIbZpo16KZoDkrKtljyOVCaFqTl3k70Loq5N6dDXug/CNkTTmI54mx/loJ5Gjwt9nSIP27wCoMpFjyOWn5C/etlkVyq7kx5gd21GfI0eFrx6A0lXd3j7Zi9cFCJijKpnMysKMpFGdpOZlauWYgPTLMdIg2XmPo31tsmMvlo8LT/zRqgDwlkTyWFRfo61RdeJN5y9GxUfF2yRhVxPoD7/w9+IHhDzytz0qr6vRfqNq7fYrT9ERus0W+Sz0q6p9vHLWfgs0FrXa1J+tO8oxaySRSoixXRUAaK7PkU4nwd6+Me/EBP5Ix1m+2iI37c/RQbUix4TlBw8XwmaBzmlsrBWBXzvDXSpks7tIGngAz/Kf59/fYe2frD1bqksGwmY6ke9ZnRA8EZkTRAQ0H3rU3tafIFVM2dlkm2G9aryMO95+rbE2jRMYmfsCr7ZR0Y41Lh+ufx2jkjWu98psGhu/XgqO5PepE3eAXPmgseMThxYYC/jlvZ+DrL2zzlgAJ15RXTi4l+Ry0/IfD7vMYtlG63ho6jlbo8JI0hlC4J5yI2Rb/eOYP/ZP65AuQbscl3QWMNENlX' + 'w8sXIrWNTsyieuxxnK4MO5n+y1GkjBX7FGWsgm0nMyvhvQR6116/AXn3M6+UGWDFZy7JbEGjxHXCf+umUkaE82Tv0P1144c07Z5gBAdDrhj7jimTue8UTThFPrEMYlqBaXhIB0I1XBJIz0LOFKbunhysH9YGMS3Oe4LWukeS6budFBx7H4caB1YWuA3BHEouuEnBmPIfp3d8qRgByNmlBrE0jkh+wnOtQbINHph7OkR0YKtVo8+744TmKANFdvIKG4fRbYl6YXMP4n3v5F1SWIPN5rjKPb63DCNkftAdERl6Nio+oFkjhLYfQPPxiT8QddRX0UQEcdxFWNo0I3A1uNymEWWH/CBDjZtn08mrJtArC1yI7g4lF2/nejgqtdqQJpzEctnY/jFjxB5G+qjLibervHcWQvUvfR3khS8SbzmoxrowJDOboGAFB9fO6IjIj+6Cxhogr65XokSJJteAEfyl5yg2pFjwByvOu49LTL1Je75K820koTyv6Zu3aVV9EvqevQWntanowEuqW4Nr20JzFI+sO3kFkIOEgShRwSHlV9NQbFWw/XL/mWrLTz1hPtoMjmTi3APwhoNW5rlJ6QTq1yq7Cw/8' + 'F6S1E1lncGrjyOFvBNU2f/hPMAKNr1cMGEbI/L06IjJbgSD39sqRCNRvojHs6j6mM02UdFM0ByVYQDlmworSSb7W86eanyH1aMy0g6X+li3QhXUbV+ExWv7QAj3lL9GOSw5bXyDmrd8aMy3pbrGrTKPOEPV7ZcYEEI97qNYsPNerB6OhEHPY4WsNrRKRvtVs8vNmQzUywJcuVXcmss7g1AAAAAAAAAAAywKkdt6bUCnk4y/Ui556wnNLZe4shPdeblOGvM1+EK8BtPyE58vKP8/oc1xlkF/VNhO/2g/0wuYRO4csMef26C/hi6JVBSrr6XS3LrxIoeQKvFZBuJ2Xm7RqpeYiArZuROwmsMS7/4emkDtbJ6UDx39oAZD8meZHl6hKOqcajZzdEu3hYDfqfMVUJR3dDchOiMVMfZVr4xNNkWlgSGYrXbCAcsyZCbmStd5ZYsXJfFGBuAOtGbY3ybL1l9lKgjDsCwiqxV9WXaTxMn/SAXKD1q2YkZ54815jarlRlnZ1H1Mk6SFnClN3T7n9PRwV1G1IkvZhlPvaSF9aNdxzEQFbN97T9HBUd6k9wAoOs4HNDY27iNgJxl/kNhYQSZe+rLpV' + 'IbcKyVaTsoxZ9MXiJUEYdtXbXrULIfSZVdehnPVcCW+pcka0w/hRn4VS1IeivTg1VGNdGBKXw1Ajwu/chRg78p9h+W7MDJN5U0iTo53cj+1e3wtZqgpUy6wsbRqfOJRc1667oNiqfecqv6AMCcXvKNhMxk889y+/IAP2TbFYeLOnJMffwG7J+AafMj9ogIaCzClqzVHQHJQFXiuuXMDFw2Jw4sIdYwG2O4QnIDgiGcDS8JAOhGq4JFL8byd6F0XSxpU8jOlNiw/gCfj+MJV1PmVbLHmSKE0LmEo31UNH38Tqta6/iAjipZo/0sCQzFa6nKDg//hM0DhMJZXkr63hYt9nCPSzvGMCv2IPI31U68qTQp0QHBGCYAl9T9CM3dTajC+bVy5g7O9winx/GMS0Hzow26Tf6dP/QAbxmn+w8Htfa/fdTcGe9B9tBkcycW6P+fvMhmpknTMwjI3lZ3REZIlxsPlyoCks1hpHJD9ht9jv64UR1MgnZpYctr5A0UejqrNfJfe4Et52FU5AcEQynVE9drZOVwaT80eax9L5Cqibiy5EdwechSl+uZ09haxpfjfmLfx9QMN3byWk7pOeW+BFyFDdj7Wt' + 'hu1bpxH/GVLpHQvZz2FrNTfgqyVuQI/7lgf2wDECWnoLAvXhFtI8nfPYSGv7UGUMYhz/J8QIdfV9QMtx+l/TSm2qZhbaopBin181SSPshOLshHw9xQfDswJaNmgEPOIFqL+ebE2sCxn6gIvi6b67lLW5nFJ3x0+jeNm8lfA5e8zjMuUM260mJMdPzhKTMnl+Fyns6y6nCavC1rn2mVTR+F2JjL+6uFUahZp2+xfditsb6FiGNi9/tfZBP4/xNs2K0xEPpbu341wKL+7VFMxNEegwEO3Nfxq5oedd5V9C1YHu3kpVwTshtvL1U1/5ThSADMG0bRiIdh684V/bZSmROy0l6JdacYHCcYF/HOLXpVQuUsXLXFMSS/n3pr7vnCgdnnIufSHy9W7OFw2bgdyn5g6bggUctJQbHnEvYjxJ1zMh5Fz6Qvn33MuOen+Lug9gjpiDGgEPtkZHTM8NjolbI6mShVhPsnqVjMK1cgUzVENC1bjphO/zpQEtGzQCHnGMV6Ziaq50GAv/GfwG49gTEjW6nU1qfG3+ydRMF4+G7WVQZSPmoC5SiAN3LVwGIpOJiwH0/gtpHsD42r2K7YJZkUxOOuyYW2e+' + 'sQ3wgn+/lqlqaSea1Pja4eeGidzT1f8ugS4aKx+lU9H7rZDW66DKGBrFQ7I0MQ45FgT33yy5eCemJBxpURifAnU1E8zqr3xeZPKln8hMTvokfSseSJ9fWttk1xirR0xIefSnofInCkAVc9qDKpvrrjSXhnloYhxyUUg40qIwIwTwr2U3/XL2hR0GAj46a0S6Z4WIw85u3XNmqJP3zHCs/9TSTim17anfOFYyFHDqamwHw0GMDlpKgyvLsi9WNbrNBLRs0Ah42QoG7lq4DEQ7DzshH0h2yPnlCVjDiRLu3pjRSznNv4sBWTl7KSBy9Bvgh8BAkxPhaN6tJumIR8qjn04UDIScZ4W71f9VHbfz2FOgykbRXVykDc1gIMeH/jRvhLdtzxXD+1fe/aD8oSHkzkuNe2CWAS09msZCrSmKLGQIddi9EPCvFLNXxup7g3SsTWMh2JpFFjLtqWcJxxmyP/dsJLvzKLwGxmLVJpEsCPI84l7EeJKzZrl4KD9vTzm9wIyPnp1oM/1PORewnnn0N1k94G+ywIwQ1oh4QbHRS9oZsm7uMhOdsLSUh2Z12T4vglk3dxmHwFiQ6ax4PUZhdfGCfgP/bIcJ' + 'lF3AqDU+uH9FFvllirW5Jj+Vc5h+sCDvuFUzC21RSDEq5qkbVCvLQWMx5BPGFgR5QI+OgYDTEaDv81FhwyVQOtBmIvm9lXDViHbZog1LjUmlUzE1VzoMi+Fo02TfkcQh9BsJ5/UKL48SsJsPJMGhLdpJzCypWT3EH1w0Vj5Xpr9U0U82qFaLgq983+BD9kGa6momhclD+Lzl3L+01+kdK7J63d55nQUga0Q8rtbmq217rpHJ9hvoRT64aKx8rlFjEce2UyLjMqTSPBSRuamS0I+1mC4DEcfKcKxkKODJ1NiJW8KWD1X8xXZCPpDsje/Xb/BQft6ecmc9z0XweozC6kqgYFSUH1yxWBD7W7De/Zxe/qHjvJrGk27dS0rcgAPrdBgI+OixDdIUXsG3KIWaIii8n3NQFylEJwoGQk69zNOXKu30Mxwr9gWZd+QKZqiGJVAwKkqBLtbdio2gpwN3R8UV+HqXDpt7MCPqqWAaxXi346o6c/utpg+2mTEequWXAAAAAAAAAAAxDvGdYgS09CKTcaZE22RVDeyvWRqWB5JcpJeLuKYklhwrGQo4dTU2QaKVtYLNYCwyedzBZCYnfcGhlKqfdkJx' + 'E52AOybf0KGuUcTUQegwFtgT+kStZd/BrAvyvEXU0hMjvmqSRsUV2UnXTQiSPc84nQUDISfQZucvf97/Xk1jx6R+KgFVJH0HmbFv8S+ov+1GYdQ5jJcqr9/Qu8ijP5VC3KeWlKUdBsuwIOu2faHnJboPBWNpbao05PGkgNX3bKfEOONOlRDq95OegSQ7ZPL8je+uRgctJc8sCPOjWG/wTtelY3WzzzpWIMlHzkDnhlBD+KPdhvGCKVaLeV6sammHgAMBHx27Il31NhLT9xReAxifddowDew8lXDbnDcgyfO7Ih5Xa3PbuHL2UkDk9TbdRDviUYiryKriH/442bNXqP1Dym7n5PEXyqNhS4mkfuz+NOcy4cZinoN0LEMbmbHUzzoWr4PC1mqq5agESZDpHCYnHXZMo71fkcS3TD9YEPl8bdBF+EGixn8a/Rn+YzFPyPlXI42YnOmnCQddUwbujlX8VAKqSPoOSPpWPJAjvrRl376rylI/dmyHfSLYvOHuzE0784XgReO+u2mzYRVzPhDqrWcg/UMots6xDnHl3Cq9zETvZzfgt1I/FY6kErCNmJx0xS22zmGb61mZK5Rd6Ios78oJd29M' + 'o71rjVt+N4TrRz2xy12JMMP7osKbSqB0nCgYFSXOF2toMxHy0MQ45F/Tute+hLcf/G7RWuX6gJs2zbARbF7+dymRhEdSCVjIopBwuVlgRghTEg66pgzBAToMBHx01ohpaR4KxtLaSWhz20l05utHUXqDiv30BZnJWkrNM7TiH5lgRslPwDSX8OarkujRy46iM1TH9WY4VvHZPuFwr3uuTWFr0nvCKuZ8krOaEDl6g3CryLMwS46YkL+WcodjCwKyW2fWB7b8bhXQMcOXzlU/5ha6WwGwBrUlqJut5ilucMhqH1Jdd9NDW24QNXBXPfoLZg77Khf8lat2Mnqel2NL9kutnWRiRYv18YMMrtvD90jFyPVCZpEx/5UEShzcSLDLiSli3zz4uGawueII6TDBNaFPs/BhGnZ8jSYF8hwWATbWtxki/sxUnjcIlDilkH2LC12jjlgD1JxaW8yc6m88vO2uJG07c//l0rh+D94i7c5eVKuxyoGF7B3n+I/oBWG5rV4ahwE1oIwvKtvWZc7MdleAtaeC9YNYPtyKLu3kez/J2Vw1Br7nD4O+ER1sTgXupgO5CVk2dBAQPIG0gJ/eXSxptgJ9DHdK' + 'OZCA19XIeVMJ1B4WSHQGtM3WOxgmUF5f+Z3C9JsCmOic0FQKlDy2f7yoS3+JHxfFcj0ds7eN8qZ4qm5x5ztPLhQz5pmgcWcNhPIb5FRiB4KY3zMntNIPL/BJ3OLTdp5c22xgGZZW63pkh0ayB4tHgzLNI1mNy63PHqSVW/DH2oXpoUNAG51Gtf2Spdm77CG4yBOMeQ4Ljhsu4AuabXulYvhXEriTt/H86yj+2AvqlJ1WSmXrikDqTGyZiOhHSigjRTWJixIdjy2r2MAyMazL9Loukcq5hny9eWC+Pe+OJjoMEal3YC/W8MtQ4a0WyTUn6uIulANf/YkoZtEvXeLOGv8bGEGrm/OQn5M53oz+DUOWRyfIxIoL91JFAsaqrlMcm5xe86wQtBNPovpJQqsypT8WWmLlURIrx0FI2nbm49eSSEDl5GSyp9NyrkPWl4TaIztyoQXhGoakigSRSUGmOLS2hSXJ3nhl3eq6rKbPgAIKl3PCULa9iMKE/7tevTOTi6DfRyyPak4q72y3TZUcMkJ5g3IqMY1Bc/fN/784m7IHTAr5OCwCbIpqDwskOgNab9rlPF+Ikx/Gi5iWflOKw0T/WccaqOY5' + '4vzgzkOekimiDN4kedjNQBnon6LI69jp9Ea7z/OYJwxDs1M+IoTkVdgvDc2OlFBGUQZvErJs6CDnOVeva8VCbQgezlpAwW+gOxk9T8W/q3t/5mSI3xdNQg6YFO9wWATYgTeshXw518axczJE4YWoIWlcP4lvEfhn9s8GV+Pv9SQaq/J20Clj1S2jZk51uR5eAom9mBB30iiQwf199BNgjzxVN7b9k6kXqhIQfjkZouAGhtq1MJlreNqmsFWe44Juw04v91YIWodtU1ikT/9BN/xYdZWzWUisfKUJXMfV9n77FH9si3VKwL/rJquR3az5aJbvxWekkXPKmjHhHnxcM7vkQYaxMxWpDdt5O2iav+RwtKArp/ogjuR6OntzB/lRjOzVvhSjaCLu7Um5I7FE2Rdwi024s9wxYIghnydl/tOz+o/c8fJ6CZELLTH8pgmbD1LEo3jtbcxQzL9eutmBNGvVghF/ZipPlM6aUNT92d8rJbz7RSB1JmfEK2YfSfy/SSQg/HIyWd0DQ23UGMK7PB9uRRf4crORoIVjvGmvH2jUPqS67ruGtgHK0EwItWkUrJTKywmAyZhUw9hzmjc4ZCb+xcAtusrC' + '3qnXeL4NOz4ED2ctIO65UOWw6jd7spBF8wqxNsu0JWBiAZwHNxIs++hrkwwTKC+hzBzrVC7lN0tTj9KKohs6CBthIjrYnArBNsJEdK0lFJ96I9Pp90ydBr4h9ueZaMXtz1+GgDYnjHf3BdYb61qcME0rR9FS3OCNX557/cI07Pgkd3hYPc0Y6oZ7pnxEFdWqTOGXnVppiZkAAAAAAAAAAOxk9CEzxpbxtXxVacFrEXHBx5JvRn+Ir2VNlv4PPi6XFfk21ajEDhm4pyxSqfGulalRfaoh2xncWNJxBPoY7pRZGKFI8q2HgFzdFina9lfEgnTBUWT7bPrR+xPbxuBW8n1v2RDPYJ9qtj84vdmpqk09n+f69SbAA3S7xwaHFJne32MHNLa4Uio60+0DzQrCb/reryCDwCPUwA1CI07K4buFOMuoXNdulsQCJQ5uJFjrR7w0EwJqXQWv16cfEUJypJeN94TMP2LjuW38HqFEx4Ehss85FZbIrjGOTo2VCRbzzpVWzD6S5WM4WlCb3X0QRzWBKaC156+j5vOH42NwK3ngdV1WU+lAAXvpA6X/+fQSErU8LJDoDHUzB/MVhX7E24+vuGoMYdMe' + '2eXdgYYhOVJ3+KrSn9Yi4iW9qBQ1eHH+dXEXSo+h8MoTf+xgmF1lYTBEnsGdvH/npUDU3UH0zyzcIGrgrnrpFluRHNDi2lWosjBfkPlHEx00S/nsvVLGt10XxmXSQz7QGCJP7sBesf2eWemShEtkV5pWjr+kpd0Ho8YOaHFtpFR+LLTE16IkVoexdjBMoLy+QTrupjLzNn2ZFeNrvGdmO0DwPuo6Rl9pHC0ow+CwCK1OaCoFSh5bsQXFt2EoW9BE4b+NGltcKRXywGF6wwFMdLf16PHRHMNZY8tMSz+nRe+dGoRGnInfa+M2MIJLK/s91fR09uYO76L1jGuD+y1OGEZ25F8K3zQRIHgfdR0jobq9Ypszgap+0a4dd1MZ9xuw/tHIDaMumoRVCQg/koJRcCmsAWNVV6cOp8lpRVGDHQSOZWgmBNS6ChH2UfiIKrdJ133JbvZ5PYrvJ5n1KwQtzUju8LB6hzDJIvGi7Q1Uc5JhQvHTL9CXx0pnTShq8OLhgP18yXSMvtJxfnBnr09JmpOCkKns0duziOOykzRN0XInNBWMJQ+j1g'); //==
// Variables
var sigma, N, h; // 64bit tools
function get8(x, i) {
return x[i >> 2] >> ((i & 3) << 3) & 0xff;
} // 512bit tools
function add512(x, y) {
var CF = 0,
w0,
w1;
for (var i = 0; i < 16; i++) {
w0 = (x[i] & 0xffff) + (y[i] & 0xffff) + (CF || 0);
w1 = (x[i] >>> 16) + (y[i] >>> 16) + (w0 >>> 16);
x[i] = w0 & 0xffff | w1 << 16;
CF = w1 >>> 16;
}
}
function get512(d) {
return new Int32Array(d.buffer, d.byteOffset, 16);
}
function copy512(r, d) {
for (var i = 0; i < 16; i++) {
r[i] = d[i];
}
}
function new512() {
return new Int32Array(16);
} // Core private algorithms
function xor512(x, y) {
for (var i = 0; i < 16; i++) {
x[i] = x[i] ^ y[i];
}
}
var r = new512();
function XLPS(x, y) {
copy512(r, x);
xor512(r, y);
for (var i = 0; i < 8; i++) {
var z0,
z1,
k = get8(r, i) << 1;
z0 = Ax[k];
z1 = Ax[k + 1];
for (var j = 1; j < 8; j++) {
k = (j << 9) + (get8(r, (j << 3) + i) << 1);
z0 = z0 ^ Ax[k];
z1 = z1 ^ Ax[k + 1];
}
x[i << 1] = z0;
x[(i << 1) + 1] = z1;
}
}
var data = new512(),
Ki = new512();
function g(h, N, m) {
var i;
copy512(data, h);
XLPS(data, N);
/* Starting E() */
copy512(Ki, data);
XLPS(data, m);
for (i = 0; i < 11; i++) {
XLPS(Ki, C[i]);
XLPS(data, Ki);
}
XLPS(Ki, C[11]);
xor512(data, Ki);
/* E() done */
xor512(h, data);
xor512(h, m);
} // Stages
function stage2(d) {
var m = get512(d);
g(h, N, m);
add512(N, buffer512);
add512(sigma, m);
}
function stage3(d) {
var n = d.length;
if (n > 63) return;
var b0 = new Int32Array(16);
b0[0] = n << 3;
var b = new Uint8Array(64);
for (var i = 0; i < n; i++) {
b[i] = d[i];
}
b[n] = 0x01;
var m = get512(b),
m0 = get512(b0);
g(h, N, m);
add512(N, m0);
add512(sigma, m);
g(h, buffer0, N);
g(h, buffer0, sigma);
}
return function (data) {
// Cleanup
sigma = new512();
N = new512(); // Initial vector
h = new512();
for (var i = 0; i < 16; i++) {
if (this.bitLength === 256) h[i] = 0x01010101;
} // Make data
var d = new Uint8Array(buffer(data));
var n = d.length;
var r = n % 64,
q = (n - r) / 64;
for (var i = 0; i < q; i++) {
stage2.call(this, new Uint8Array(d.buffer, i * 64, 64));
}
stage3.call(this, new Uint8Array(d.buffer, q * 64, r));
var digest;
if (this.bitLength === 256) {
digest = new Int32Array(8);
for (var i = 0; i < 8; i++) {
digest[i] = h[8 + i];
}
} else {
digest = new Int32Array(16);
for (var i = 0; i < 16; i++) {
digest[i] = h[i];
}
} // Swap hash for SignalCom
if (this.procreator === 'SC' || this.procreator === 'VN') return swap(digest.buffer);else return digest.buffer;
};
} // </editor-fold>
();
/**
* Algorithm name GOST R 34.11-94<br><br>
*
* http://tools.ietf.org/html/rfc5831
*
* The digest method returns digest data in according to GOST R 34.11-94.
* @memberOf GostDigest
* @method digest
* @instance
* @param {(ArrayBuffer|TypedArray)} data Data
* @returns {ArrayBuffer} Digest of data
*/
var digest94 = function () // <editor-fold defaultstate="collapsed">
{
var C, H, M, Sum; // (i + 1 + 4(k - 1)) = 8i + k i = 0-3, k = 1-8
function P(d) {
var K = new Uint8Array(32);
for (var k = 0; k < 8; k++) {
K[4 * k] = d[k];
K[1 + 4 * k] = d[8 + k];
K[2 + 4 * k] = d[16 + k];
K[3 + 4 * k] = d[24 + k];
}
return K;
} //A (x) = (x0 ^ x1) || x3 || x2 || x1
function A(d) {
var a = new Uint8Array(8);
for (var j = 0; j < 8; j++) {
a[j] = d[j] ^ d[j + 8];
}
arraycopy(d, 8, d, 0, 24);
arraycopy(a, 0, d, 24, 8);
return d;
} // (in:) n16||..||n1 ==> (out:) n1^n2^n3^n4^n13^n16||n16||..||n2
function fw(d) {
var wS = new Uint16Array(d.buffer, 0, 16);
var wS15 = wS[0] ^ wS[1] ^ wS[2] ^ wS[3] ^ wS[12] ^ wS[15];
arraycopy(wS, 1, wS, 0, 15);
wS[15] = wS15;
} //Encrypt function, ECB mode
function encrypt(key, s, sOff, d, dOff) {
var t = new Uint8Array(8);
arraycopy(d, dOff, t, 0, 8);
var r = new Uint8Array(this.cipher.encrypt(key, t));
arraycopy(r, 0, s, sOff, 8);
} // block processing
function process(d, dOff) {
var S = new Uint8Array(32),
U = new Uint8Array(32),
V = new Uint8Array(32),
W = new Uint8Array(32);
arraycopy(d, dOff, M, 0, 32); //key step 1
// H = h3 || h2 || h1 || h0
// S = s3 || s2 || s1 || s0
arraycopy(H, 0, U, 0, 32);
arraycopy(M, 0, V, 0, 32);
for (var j = 0; j < 32; j++) {
W[j] = U[j] ^ V[j];
} // Encrypt GOST 28147-ECB
encrypt.call(this, P(W), S, 0, H, 0); // s0 = EK0 [h0]
//keys step 2,3,4
for (var i = 1; i < 4; i++) {
var tmpA = A(U);
for (var j = 0; j < 32; j++) {
U[j] = tmpA[j] ^ C[i][j];
}
V = A(A(V));
for (var j = 0; j < 32; j++) {
W[j] = U[j] ^ V[j];
} // Encrypt GOST 28147-ECB
encrypt.call(this, P(W), S, i * 8, H, i * 8); // si = EKi [hi]
} // x(M, H) = y61(H^y(M^y12(S)))
for (var n = 0; n < 12; n++) {
fw(S);
}
for (var n = 0; n < 32; n++) {
S[n] = S[n] ^ M[n];
}
fw(S);
for (var n = 0; n < 32; n++) {
S[n] = H[n] ^ S[n];
}
for (var n = 0; n < 61; n++) {
fw(S);
}
arraycopy(S, 0, H, 0, H.length);
} // 256 bitsblock modul -> (Sum + a mod (2^256))
function summing(d) {
var carry = 0;
for (var i = 0; i < Sum.length; i++) {
var sum = (Sum[i] & 0xff) + (d[i] & 0xff) + carry;
Sum[i] = sum;
carry = sum >>> 8;
}
} // reset the chaining variables to the IV values.
var C2 = new Uint8Array([0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0xFF]);
return function (data) {
// Reset buffers
H = new Uint8Array(32);
M = new Uint8Array(32);
Sum = new Uint8Array(32); // Reset IV value
C = new Array(4);
for (var i = 0; i < 4; i++) {
C[i] = new Uint8Array(32);
}
arraycopy(C2, 0, C[2], 0, C2.length); // Make data
var d = new Uint8Array(buffer(data));
var n = d.length;
var r = n % 32,
q = (n - r) / 32; // Proccess full blocks
for (var i = 0; i < q; i++) {
var b = new Uint8Array(d.buffer, i * 32, 32);
summing.call(this, b); // calc sum M
process.call(this, b, 0);
} // load d the remadder with padding zero;
if (r > 0) {
var b = new Uint8Array(d.buffer, q * 32),
c = new Uint8Array(32);
arraycopy(b, 0, c, 0, r);
summing.call(this, c); // calc sum M
process.call(this, c, 0);
} // get length into L (byteCount * 8 = bitCount) in little endian.
var L = new Uint8Array(32),
n8 = n * 8,
k = 0;
while (n8 > 0) {
L[k++] = n8 & 0xff;
n8 = Math.floor(n8 / 256);
}
process.call(this, L, 0);
process.call(this, Sum, 0);
var h = H.buffer; // Swap hash for SignalCom
if (this.procreator === 'SC') h = swap(h);
return h;
};
} // </editor-fold>
();
/**
* Algorithm name SHA-1<br><br>
*
* https://tools.ietf.org/html/rfc3174
*
* The digest method returns digest data in according to SHA-1.<br>
*
* @memberOf GostDigest
* @method digest
* @instance
* @param {(ArrayBuffer|TypedArray)} data Data
* @returns {ArrayBuffer} Digest of data
*/
var digestSHA1 = function () // <editor-fold defaultstate="collapsed">
{
// Create a buffer for each 80 word block.
var state,
block = new Uint32Array(80);
function common(a, e, w, k, f) {
return f + e + w + k + (a << 5 | a >>> 27) >>> 0;
}
function f1(a, b, c, d, e, w) {
return common(a, e, w, 0x5A827999, d ^ b & (c ^ d));
}
function f2(a, b, c, d, e, w) {
return common(a, e, w, 0x6ED9EBA1, b ^ c ^ d);
}
function f3(a, b, c, d, e, w) {
return common(a, e, w, 0x8F1BBCDC, b & c | d & (b | c));
}
function f4(a, b, c, d, e, w) {
return common(a, e, w, 0xCA62C1D6, b ^ c ^ d);
}
function cycle(state, block) {
var a = state[0],
b = state[1],
c = state[2],
d = state[3],
e = state[4]; // Partially unroll loops so we don't have to shift variables.
var fn = f1;
for (var i = 0; i < 80; i += 5) {
if (i === 20) {
fn = f2;
} else if (i === 40) {
fn = f3;
} else if (i === 60) {
fn = f4;
}
e = fn(a, b, c, d, e, block[i]);
b = (b << 30 | b >>> 2) >>> 0;
d = fn(e, a, b, c, d, block[i + 1]);
a = (a << 30 | a >>> 2) >>> 0;
c = fn(d, e, a, b, c, block[i + 2]);
e = (e << 30 | e >>> 2) >>> 0;
b = fn(c, d, e, a, b, block[i + 3]);
d = (d << 30 | d >>> 2) >>> 0;
a = fn(b, c, d, e, a, block[i + 4]);
c = (c << 30 | c >>> 2) >>> 0;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
} // Swap bytes for 32bits word
function swap32(b) {
return (b & 0xff) << 24 | (b & 0xff00) << 8 | b >> 8 & 0xff00 | b >> 24 & 0xff;
} // input is a Uint8Array bitstream of the data
return function (data) {
var d = new Uint8Array(buffer(data)),
dlen = d.length; // Pad the input string length.
var len = dlen + 9;
if (len % 64) {
len += 64 - len % 64;
}
state = new Uint32Array(5);
state[0] = 0x67452301;
state[1] = 0xefcdab89;
state[2] = 0x98badcfe;
state[3] = 0x10325476;
state[4] = 0xc3d2e1f0;
for (var ofs = 0; ofs < len; ofs += 64) {
// Copy input to block and write padding as needed
for (var i = 0; i < 64; i++) {
var b = 0,
o = ofs + i;
if (o < dlen) {
b = d[o];
} else if (o === dlen) {
b = 0x80;
} else {
// Write original bit length as a 64bit big-endian integer to the end.
var x = len - o - 1;
if (x >= 0 && x < 4) {
b = dlen << 3 >>> x * 8 & 0xff;
}
} // Interpret the input bytes as big-endian per the spec
if (i % 4 === 0) {
block[i >> 2] = b << 24;
} else {
block[i >> 2] |= b << (3 - i % 4) * 8;
}
} // Extend the block
for (var i = 16; i < 80; i++) {
var w = block[i - 3] ^ block[i - 8] ^ block[i - 14] ^ block[i - 16];
block[i] = w << 1 | w >>> 31;
}
cycle(state, block);
} // Swap the bytes around since they are big endian internally
for (var i = 0; i < 5; i++) {
state[i] = swap32(state[i]);
}
return state.buffer;
};
} // </editor-fold>
();
/**
* Algorithm name GOST R 34.11-HMAC<br><br>
*
* HMAC with the specified hash function.
* @memberOf GostDigest
* @method sign
* @instance
* @param {ArrayBuffer} key The key for HMAC.
* @param {Hash} data Data
*/
function signHMAC(key, data) // <editor-fold defaultstate="collapsed">
{
// GOST R 34.11-94 - B=32b, L=32b
// GOST R 34.11-256 - B=64b, L=32b
// GOST R 34.11-512 - B=64b, L=64b
var b = this.digest === digest94 ? 32 : 64,
l = this.bitLength / 8,
k = buffer(key),
d = buffer(data),
k0;
if (k.byteLength === b) k0 = new Uint8Array(k);else {
var k0 = new Uint8Array(b);
if (k.byteLength > b) {
k0.set(new Uint8Array(this.digest(k)));
} else {
k0.set(new Uint8Array(k));
}
}
var s0 = new Uint8Array(b + d.byteLength),
s1 = new Uint8Array(b + l);
for (var i = 0; i < b; i++) {
s0[i] = k0[i] ^ 0x36;
s1[i] = k0[i] ^ 0x5C;
}
s0.set(new Uint8Array(d), b);
s1.set(new Uint8Array(this.digest(s0)), b);
return this.digest(s1);
} // </editor-fold>
/**
* Algorithm name GOST R 34.11-HMAC<br><br>
*
* Verify HMAC based on GOST R 34.11 hash
*
* @memberOf GostDigest
* @method verify
* @instance
* @param {(ArrayBuffer|TypedArray)} key Key which used for HMAC generation
* @param {(ArrayBuffer|TypedArray)} signature generated HMAC
* @param {(ArrayBuffer|TypedArray)} data Data
* @returns {boolean} HMAC verified = true
*/
function verifyHMAC(key, signature, data) // <editor-fold defaultstate="collapsed">
{
var hmac = new Uint8Array(this.sign(key, data)),
test = new Uint8Array(signature);
if (hmac.length !== test.length) return false;
for (var i = 0, n = hmac.length; i < n; i++) {
if (hmac[i] !== test[i]) return false;
}
return true;
} // </editor-fold>
/**
* Algorithm name GOST R 34.11-KDF<br><br>
*
* Simple generate key 256/512 bit random seed for derivation algorithms
*
* @memberOf GostDigest
* @method generateKey
* @instance
* @returns {ArrayBuffer} Generated key
*/
function generateKey() // <editor-fold defaultstate="collapsed">
{
return getSeed(this.bitLength).buffer;
} // </editor-fold>
/**
* Algorithm name GOST R 34.11-PFXKDF<br><br>
*
* Derive bits from password (PKCS12 mode)
* <ul>
* <li>algorithm.salt - random value, salt</li>
* <li>algorithm.iterations - number of iterations</li>
* </ul>
* @memberOf GostDigest
* @method deriveBits
* @instance
* @param {ArrayBuffer} baseKey - password after UTF-8 decoding
* @param {number} length output bit-length
* @returns {ArrayBuffer} result
*/
function deriveBitsPFXKDF(baseKey, length) // <editor-fold defaultstate="collapsed">
{
if (length % 8 > 0) throw new DataError('Length must multiple of 8');
var u = this.bitLength / 8,
v = this.digest === digest94 ? 32 : 64,
n = length / 8,
r = this.iterations; // 1. Construct a string, D (the "diversifier"), by concatenating v/8
// copies of ID.
var ID = this.diversifier,
D = new Uint8Array(v);
for (var i = 0; i < v; i++) {
D[i] = ID;
} // 2. Concatenate copies of the salt together to create a string S of
// length v(ceiling(s/v)) bits (the final copy of the salt may be
// truncated to create S). Note that if the salt is the empty
// string, then so is S.
var S0 = new Uint8Array(buffer(this.salt)),
s = S0.length,
slen = v * Math.ceil(s / v),
S = new Uint8Array(slen);
for (var i = 0; i < slen; i++) {
S[i] = S0[i % s];
} // 3. Concatenate copies of the password together to create a string P
// of length v(ceiling(p/v)) bits (the final copy of the password
// may be truncated to create P). Note that if the password is the
// empty string, then so is P.
var P0 = new Uint8Array(buffer(baseKey)),
p = P0.length,
plen = v * Math.ceil(p / v),
P = new Uint8Array(plen);
for (var i = 0; i < plen; i++) {
P[i] = P0[i % p];
} // 4. Set I=S||P to be the concatenation of S and P.
var I = new Uint8Array(slen + plen);
arraycopy(S, 0, I, 0, slen);
arraycopy(P, 0, I, slen, plen); // 5. Set c=ceiling(n/u).
var c = Math.ceil(n / u); // 6. For i=1, 2, ..., c, do the following:
var A = new Uint8Array(c * u);
for (var i = 0; i < c; i++) {
// A. Set A2=H^r(D||I). (i.e., the r-th hash of D||1,
// H(H(H(... H(D||I))))
var H = new Uint8Array(v + slen + plen);
arraycopy(D, 0, H, 0, v);
arraycopy(I, 0, H, v, slen + plen);
for (var j = 0; j < r; j++) {
H = new Uint8Array(this.digest(H));
}
arraycopy(H, 0, A, i * u, u); // B. Concatenate copies of Ai to create a string B of length v
// bits (the final copy of Ai may be truncated to create B).
var B = new Uint8Array(v);
for (var j = 0; j < v; j++) {
B[j] = H[j % u];
} // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit
// blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by
// setting I_j=(I_j+B+1) mod 2^v for each j.
var k = (slen + plen) / v;
for (j = 0; j < k; j++) {
var cf = 1,
w;
for (var l = v - 1; l >= 0; --l) {
w = I[v * j + l] + B[l] + cf;
cf = w >>> 8;
I[v * j + l] = w & 0xff;
}
}
} // 7. Concatenate A_1, A_2, ..., A_c together to form a pseudorandom
// bit string, A.
// 8. Use the first n bits of A as the output of this entire process.
var R = new Uint8Array(n);
arraycopy(A, 0, R, 0, n);
return R.buffer;
} // </editor-fold>
/**
* Algorithm name GOST R 34.11-KDF<br><br>
*
* Derive bits for KEK deversification in 34.10-2012 algorithm
* KDF(KEK, UKM, label) = HMAC256 (KEK, 0x01|label|0x00|UKM|0x01|0x00)
* Default label = 0x26|0xBD|0xB8|0x78
*
* @memberOf GostDigest
* @method deriveBits
* @instance
* @param {(ArrayBuffer|TypedArray)} baseKey base key for deriviation
* @param {number} length output bit-length
* @returns {ArrayBuffer} result
*/
function deriveBitsKDF(baseKey, length) // <editor-fold defaultstate="collapsed">
{
if (length % 8 > 0) throw new DataError('Length must be multiple of 8');
var rlen = length / 8,
label,
context = new Uint8Array(buffer(this.context)),
blen = this.bitLength / 8,
n = Math.ceil(rlen / blen);
if (this.label) label = new Uint8Array(buffer(this.label));else label = new Uint8Array([0x26, 0xBD, 0xB8, 0x78]);
var result = new Uint8Array(rlen);
for (var i = 0; i < n; i++) {
var data = new Uint8Array(label.length + context.length + 4);
data[0] = i + 1;
data.set(label, 1);
data[label.length + 1] = 0x00;
data.set(context, label.length + 2);
data[data.length - 2] = length >>> 8;
data[data.length - 1] = length & 0xff;
result.set(new Uint8Array(signHMAC.call(this, baseKey, data), 0, i < n - 1 ? blen : rlen - i * blen), i * blen);
}
return result.buffer;
} // </editor-fold>
/**
* Algorithm name GOST R 34.11-PBKDF1<br><br>
*
* Derive bits from password
* <ul>
* <li>algorithm.salt - random value, salt</li>
* <li>algorithm.iterations - number of iterations</li>
* </ul>
* @memberOf GostDigest
* @method deriveBits
* @instance
* @param {ArrayBuffer} baseKey - password after UTF-8 decoding
* @param {number} length output bit-length
* @returns {ArrayBuffer} result
*/
function deriveBitsPBKDF1(baseKey, length) // <editor-fold defaultstate="collapsed">
{
if (length < this.bitLength / 2 || length % 8 > 0) throw new DataError('Length must be more than ' + this.bitLength / 2 + ' bits and multiple of 8');
var hLen = this.bitLength / 8,
dkLen = length / 8,
c = this.iterations,
P = new Uint8Array(buffer(baseKey)),
S = new Uint8Array(buffer(this.salt)),
slen = S.length,
plen = P.length,
T = new Uint8Array(plen + slen),
DK = new Uint8Array(dkLen);
if (dkLen > hLen) throw new DataError('Invalid parameters: Length value');
arraycopy(P, 0, T, 0, plen);
arraycopy(S, 0, T, plen, slen);
for (var i = 0; i < c; i++) {
T = new Uint8Array(this.digest(T));
}
arraycopy(T, 0, DK, 0, dkLen);
return DK.buffer;
} // </editor-fold>
/**
* Algorithm name GOST R 34.11-PBKDF2<br><br>
*
* Derive bits from password
* <ul>
* <li>algorithm.salt - random value, salt</li>
* <li>algorithm.iterations - number of iterations</li>
* </ul>
* @memberOf GostDigest
* @method deriveBits
* @instance
* @param {ArrayBuffer} baseKey - password after UTF-8 decoding
* @param {number} length output bit-length
* @returns {ArrayBuffer} result
*/
function deriveBitsPBKDF2(baseKey, length) // <editor-fold defaultstate="collapsed">
{
var diversifier = this.diversifier || 1; // For PKCS12 MAC required 3*length
length = length * diversifier;
if (length < this.bitLength / 2 || length % 8 > 0) throw new DataError('Length must be more than ' + this.bitLength / 2 + ' bits and multiple of 8');
var hLen = this.bitLength / 8,
dkLen = length / 8,
c = this.iterations,
P = new Uint8Array(buffer(baseKey)),
S = new Uint8Array(buffer(this.salt));
var slen = S.byteLength,
data = new Uint8Array(slen + 4);
arraycopy(S, 0, data, 0, slen);
if (dkLen > (0xffffffff - 1) * 32) throw new DataError('Invalid parameters: Length value');
var n = Math.ceil(dkLen / hLen),
DK = new Uint8Array(dkLen);
for (var i = 1; i <= n; i++) {
data[slen] = i >>> 24 & 0xff;
data[slen + 1] = i >>> 16 & 0xff;
data[slen + 2] = i >>> 8 & 0xff;
data[slen + 3] = i & 0xff;
var U = new Uint8Array(signHMAC.call(this, P, data)),
Z = U;
for (var j = 1; j < c; j++) {
U = new Uint8Array(signHMAC.call(this, P, U));
for (var k = 0; k < hLen; k++) {
Z[k] = U[k] ^ Z[k];
}
}
var ofs = (i - 1) * hLen;
arraycopy(Z, 0, DK, ofs, Math.min(hLen, dkLen - ofs));
}
if (diversifier > 1) {
var rLen = dkLen / diversifier,
R = new Uint8Array(rLen);
arraycopy(DK, dkLen - rLen, R, 0, rLen);
return R.buffer;
} else return DK.buffer;
} // </editor-fold>
/**
* Algorithm name GOST R 34.11-CPKDF<br><br>
*
* Derive bits from password. CryptoPro algorithm
* <ul>
* <li>algorithm.salt - random value, salt</li>
* <li>algorithm.iterations - number of iterations</li>
* </ul>
* @memberOf GostDigest
* @method deriveBits
* @instance
* @param {ArrayBuffer} baseKey - password after UTF-8 decoding
* @param {number} length output bit-length
* @returns {ArrayBuffer} result
*/
function deriveBitsCP(baseKey, length) {
if (length > this.bitLength || length % 8 > 0) throw new DataError('Length can\'t be more than ' + this.bitLength + ' bits and multiple of 8'); // GOST R 34.11-94 - B=32b, L=32b
// GOST R 34.11-256 - B=64b, L=32b
// GOST R 34.11-512 - B=64b, L=64b
var b = this.digest === digest94 ? 32 : 64,
l = this.bitLength / 8,
p = baseKey && baseKey.byteLength > 0 ? new Uint8Array(buffer(baseKey)) : false,
plen = p ? p.length : 0,
iterations = this.iterations,
salt = new Uint8Array(buffer(this.salt)),
slen = salt.length,
d = new Uint8Array(slen + plen);
arraycopy(salt, 0, d, 0, slen);
if (p) arraycopy(p, 0, d, slen, plen);
var h = new Uint8Array(this.digest(d)),
k = new Uint8Array(b),
s0 = new Uint8Array(b),
s1 = new Uint8Array(b);
var c = 'DENEFH028.760246785.IUEFHWUIO.EF';
for (var i = 0; i < c.length; i++) {
k[i] = c.charCodeAt(i);
}
d = new Uint8Array(2 * (b + l));
for (var j = 0; j < iterations; j++) {
for (var i = 0; i < b; i++) {
s0[i] = k[i] ^ 0x36;
s1[i] = k[i] ^ 0x5C;
k[i] = 0;
}
arraycopy(s0, 0, d, 0, b);
arraycopy(h, 0, d, b, l);
arraycopy(s1, 0, d, b + l, b);
arraycopy(h, 0, d, b + l + b, l);
arraycopy(new Uint8Array(this.digest(d)), 0, k, 0, l);
}
for (var i = 0; i < l; i++) {
s0[i] = k[i] ^ 0x36;
s1[i] = k[i] ^ 0x5C;
k[i] = 0;
}
d = new Uint8Array(2 * l + slen + plen);
arraycopy(s0, 0, d, 0, l);
arraycopy(salt, 0, d, l, slen);
arraycopy(s1, 0, d, l + slen, l);
if (p) arraycopy(p, 0, d, l + slen + l, plen);
h = this.digest(this.digest(d));
if (length === this.bitLength) return h;else {
var rlen = length / 8,
r = new Uint8Array(rlen);
arraycopy(h, 0, r, 0, rlen);
return r.buffer;
}
}
/**
* Algorithm name GOST R 34.11-KDF or GOST R 34.11-PBKDF2 or other<br><br>
*
* Derive key from derive bits subset
*
* @memberOf GostDigest
* @method deriveKey
* @instance
* @param {ArrayBuffer} baseKey
* @returns {ArrayBuffer}
*/
function deriveKey(baseKey) // <editor-fold defaultstate="collapsed">
{
return this.deriveBits(baseKey, this.keySize * 8);
} // </editor-fold>
/**
* GOST R 34.11 Algorithm<br><br>
*
* References: {@link http://tools.ietf.org/html/rfc6986} and {@link http://tools.ietf.org/html/rfc5831}<br><br>
*
* Normalized algorithm identifier common parameters:
*
* <ul>
* <li><b>name</b> Algorithm name 'GOST R 34.11'</li>
* <li><b>version</b> Algorithm version
* <ul>
* <li><b>1994</b> old-style 256 bits digest based on GOST 28147-89</li>
* <li><b>2012</b> 256 ro 512 bits digest algorithm "Streebog" GOST R 34.11-2012 (default)</li>
* </ul>
* </li>
* <li><b>length</b> Digest length
* <ul>
* <li><b>256</b> 256 bits digest</li>
* <li><b>512</b> 512 bits digest, valid only for algorithm "Streebog"</li>
* </ul>
* </li>
* <li><b>mode</b> Algorithm mode
* <ul>
* <li><b>HASH</b> simple digest mode (default)</li>
* <li><b>HMAC</b> HMAC algorithm based on GOST R 34.11</li>
* <li><b>KDF</b> Derive bits for KEK deversification</li>
* <li><b>PBKDF2</b> Password based key dirivation algorithms PBKDF2 (based on HMAC)</li>
* <li><b>PFXKDF</b> Password based PFX key dirivation algorithms</li>
* <li><b>CPKDF</b> CpyptoPro Password based key dirivation algorithms</li>
* </ul>
* </li>
* <li><b>sBox</b> Paramset sBox for GOST 28147-89. Used only if version = 1994</li>
* </ul>
*
* Supported algorithms, modes and parameters:
*
* <ul>
* <li>Digest HASH mode (default)</li>
* <li>Sign/Verify HMAC modes parameters depends on version and length
* <ul>
* <li><b>version: 1994</b> HMAC parameters (B = 32, L = 32)</li>
* <li><b>version: 2012, length: 256</b> HMAC parameters (B = 64, L = 32)</li>
* <li><b>version: 2012, length: 512</b> HMAC parameters (B = 64, L = 64)</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey KDF mode
* <ul>
* <li><b>context</b> {@link CryptoOperationData} Context of the key derivation</li>
* <li><b>label</b> {@link CryptoOperationData} Label that identifies the purpose for the derived keying material</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey PBKDF2 mode
* <ul>
* <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
* <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
* <li><b>diversifier</b> Deversifier, ID=1 - key material for performing encryption or decryption, ID=3 - integrity key for MACing</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey PFXKDF mode
* <ul>
* <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
* <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
* <li><b>diversifier</b> Deversifier, ID=1 - key material for performing encryption or decryption,
* ID=2 - IV (Initial Value) for encryption or decryption, ID=3 - integrity key for MACing</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey CPKDF mode
* <ul>
* <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
* <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
* </ul>
* </li>
* </ul>
*
* @class GostDigest
* @param {AlgorithmIdentifier} algorithm WebCryptoAPI algorithm identifier
*/
function GostDigest(algorithm) // <editor-fold defaultstate="collapsed">
{
algorithm = algorithm || {};
this.name = (algorithm.name || 'GOST R 34.10') + '-' + (algorithm.version || 2012) % 100 + ((algorithm.version || 2012) > 1 ? '-' + (algorithm.length || 256) : '') + ((algorithm.mode || 'HASH') !== 'HASH' ? '-' + algorithm.mode : '') + (algorithm.procreator ? '/' + algorithm.procreator : '') + (typeof algorithm.sBox === 'string' ? '/' + algorithm.sBox : ''); // Algorithm procreator
this.procreator = algorithm.procreator; // Bit length
this.bitLength = algorithm.length || 256;
switch (algorithm.version || 2012) {
case 1:
// SHA-1
this.digest = digestSHA1;
this.bitLength = 160;
break;
case 1994:
this.digest = digest94; // Define chiper algorithm
this.sBox = (algorithm.sBox || (algorithm.procreator === 'SC' ? 'D-SC' : 'D-A')).toUpperCase();
if (!GostCipher) GostCipher = root.GostCipher;
if (!GostCipher) throw new NotSupportedError('Object GostCipher not found');
this.cipher = new GostCipher({
name: 'GOST 28147',
block: 'ECB',
sBox: this.sBox,
procreator: this.procreator
});
break;
case 2012:
this.digest = digest2012;
break;
default:
throw new NotSupportedError('Algorithm version ' + algorithm.version + ' not supported');
} // Key size
this.keySize = algorithm.keySize || (algorithm.version <= 2 ? this.bitLength / 8 : 32);
switch (algorithm.mode || 'HASH') {
case 'HASH':
break;
case 'HMAC':
this.sign = signHMAC;
this.verify = verifyHMAC;
this.generateKey = generateKey;
break;
case 'KDF':
this.deriveKey = deriveKey;
this.deriveBits = deriveBitsKDF;
this.label = algorithm.label;
this.context = algorithm.context;
break;
case 'PBKDF2':
this.deriveKey = deriveKey;
this.deriveBits = deriveBitsPBKDF2;
this.generateKey = generateKey;
this.salt = algorithm.salt;
this.iterations = algorithm.iterations || 2000;
this.diversifier = algorithm.diversifier || 1;
break;
case 'PFXKDF':
this.deriveKey = deriveKey;
this.deriveBits = deriveBitsPFXKDF;
this.generateKey = generateKey;
this.salt = algorithm.salt;
this.iterations = algorithm.iterations || 2000;
this.diversifier = algorithm.diversifier || 1;
break;
case 'CPKDF':
this.deriveKey = deriveKey;
this.deriveBits = deriveBitsCP;
this.generateKey = generateKey;
this.salt = algorithm.salt;
this.iterations = algorithm.iterations || 2000;
break;
default:
throw new NotSupportedError('Algorithm mode ' + algorithm.mode + ' not supported');
}
} // </editor-fold>
return GostDigest;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostCipher":108,"./gostRandom":114}],112:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file GOST 34.10-2012 signature function with 1024/512 bits digest
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostRandom', 'gostCipher', 'gostDigest', 'gostSign'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostRandom'), require('./gostCipher'), require('./gostDigest'), require('./gostSign'));
} else {
if (typeof importScripts !== 'undefined') {
if (!(root.GostRandom && root.GostCipher && root.GostDigest && root.GostSign)) importScripts('gostRandom.js', 'gostCipher.js', 'gostDigest.js', 'gostSign.js');
}
root.gostEngine = factory(root.GostRandom, root.GostCipher, root.GostDigest, root.GostSign);
} // </editor-fold>
})(void 0, function (GostRandom, GostCipher, GostDigest, GostSign) {
/*
* Engine definition base on normalized algorithm identifier
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this; // Define engine
function defineEngine(method, algorithm) {
if (!algorithm) throw new (root.SyntaxError || Error)('Algorithm not defined');
if (!algorithm.name) throw new (root.SyntaxError || Error)('Algorithm name not defined');
var name = algorithm.name,
mode = algorithm.mode;
if ((name === 'GOST 28147' || name === 'GOST R 34.12' || name === 'RC2') && (method === 'generateKey' || mode === 'MAC' && (method === 'sign' || method === 'verify') || (mode === 'KW' || mode === 'MASK') && (method === 'wrapKey' || method === 'unwrapKey') || (!mode || mode === 'ES') && (method === 'encrypt' || method === 'decrypt'))) {
return 'GostCipher';
} else if ((name === 'GOST R 34.11' || name === 'SHA') && (method === 'digest' || mode === 'HMAC' && (method === 'sign' || method === 'verify' || method === 'generateKey') || (mode === 'KDF' || mode === 'PBKDF2' || mode === 'PFXKDF' || mode === 'CPKDF') && (method === 'deriveKey' || method === 'deriveBits' || method === 'generateKey'))) {
return 'GostDigest';
} else if (name === 'GOST R 34.10' && (method === 'generateKey' || (!mode || mode === 'SIGN') && (method === 'sign' || method === 'verify') || mode === 'MASK' && (method === 'wrapKey' || method === 'unwrapKey') || mode === 'DH' && (method === 'deriveKey' || method === 'deriveBits'))) {
return 'GostSign';
} else throw new (root.NotSupportedError || Error)('Algorithm ' + name + '-' + mode + ' is not valid for ' + method);
} // </editor-fold>
/**
* Object implements dedicated Web Workers and provide a simple way to create
* and run GOST cryptographic algorithms in background thread.
*
* Object provide interface to GOST low-level cryptogric classes:
* <ul>
* <li>GostCipher - implementation of GOST 28147, GOST R 34.12, GOST R 34.13 Encryption algorithms. Reference {@link http://tools.ietf.org/html/rfc5830}</li>
* <li>GostDigest - implementation of GOST R 34.11 Hash Function algorithms. References {@link http://tools.ietf.org/html/rfc5831} and {@link http://tools.ietf.org/html/rfc6986}</li>
* <li>GostSign - implementation of GOST R 34.10 Digital Signature algorithms. References {@link http://tools.ietf.org/html/rfc5832} and {@link http://tools.ietf.org/html/rfc7091}</li>
* </ul>
* @namespace gostEngine
*/
var gostEngine = {
/**
* gostEngine.execute(algorithm, method, args) Entry point to execution
* all low-level GOST cryptographic methods
*
* <ul>
* <li>Determine the appropriate engine for a given execution method</li>
* <li>Create cipher object for determineted engine</li>
* <li>Execute method of cipher with given args</li>
* </ul>
*
* @memberOf gostEngine
* @param {AlgorithmIndentifier} algorithm Algorithm identifier
* @param {string} method Crypto method for execution
* @param {Array} args Method arguments (keys, data, additional parameters)
* @returns {(CryptoOperationData|Key|KeyPair|boolean)} Result of method execution
*/
execute: function execute(algorithm, method, args) // <editor-fold defaultstate="collapsed">
{
// Define engine for GOST algorithms
var engine = defineEngine(method, algorithm); // Create cipher
var cipher = this['get' + engine](algorithm); // Execute method
return cipher[method].apply(cipher, args);
},
// </editor-fold>
/**
* gostEngine.getGostCipher(algorithm) returns GOST 28147 / GOST R 34.12 cipher instance<br><br>
*
* GOST 28147-89 / GOST R 34.12-15 Encryption Algorithm<br><br>
* When keys and initialization vectors are converted to/from byte arrays,
* little-endian byte order is assumed.<br><br>
*
* Normalized algorithm identifier common parameters:
*
* <ul>
* <li><b>name</b> Algorithm name 'GOST 28147' or 'GOST R 34.12'</li>
* <li><b>version</b> Algorithm version, number
* <ul>
* <li><b>1989</b> Current version of standard</li>
* <li><b>2015</b> New draft version of standard</li>
* </ul>
* </li>
* <li><b>length</b> Block length
* <ul>
* <li><b>64</b> 64 bits length (default)</li>
* <li><b>128</b> 128 bits length (only for version 2015)</li>
* </ul>
* </li>
* <li><b>mode</b> Algorithm mode, string
* <ul>
* <li><b>ES</b> Encryption mode (default)</li>
* <li><b>MAC</b> "imitovstavka" (MAC) mode</li>
* <li><b>KW</b> Key wrapping mode</li>
* <li><b>MASK</b> Key mask mode</li>
* </ul>
* </li>
* <li><b>sBox</b> Paramset sBox for GOST 28147-89, string. Used only if version = 1989</li>
* </ul>
*
* Supported algorithms, modes and parameters:
*
* <ul>
* <li>Encript/Decrypt mode (ES)
* <ul>
* <li><b>block</b> Block mode, string. Default ECB</li>
* <li><b>keyMeshing</b> Key meshing mode, string. Default NO</li>
* <li><b>padding</b> Padding mode, string. Default NO for CFB and CTR modes, or ZERO for others</li>
* <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
* </ul>
* </li>
* <li>Sign/Verify mode (MAC)
* <ul>
* <li><b>macLength</b> Length of mac in bits (default - 32 bits)</li>
* <li><b>iv</b> {@link CryptoOperationData} Initial vector with length of block. Default - zero block</li>
* </ul>
* </li>
* <li>Wrap/Unwrap key mode (KW)
* <ul>
* <li><b>keyWrapping</b> Mode of keywrapping, string. Default NO - standard GOST key wrapping</li>
* <li><b>ukm</b> {@link CryptoOperationData} User key material. Default - random generated value</li>
* </ul>
* </li>
* <li>Wrap/Unwrap key mode (MASK)</li>
* </ul>
*
* Supported paramters values:
*
* <ul>
* <li>Block modes (parameter 'block')
* <ul>
* <li><b>ECB</b> "prostaya zamena" (ECB) mode (default)</li>
* <li><b>CFB</b> "gammirovanie s obratnoj svyaziyu" (64-bit CFB) mode</li>
* <li><b>CTR</b> "gammirovanie" (counter) mode</li>
* <li><b>CBC</b> Cipher-Block-Chaining (CBC) mode</li>
* </ul>
* </li>
* <li>Key meshing modes (parameter 'keyMeshing')
* <ul>
* <li><b>NO</b> No key wrapping (default)</li>
* <li><b>CP</b> CryptoPor Key key meshing</li>
* </ul>
* </li>
* <li>Padding modes (parameter 'padding')
* <ul>
* <li><b>NO</b> No padding only for CFB and CTR modes</li>
* <li><b>PKCS5</b> PKCS#5 padding mode</li>
* <li><b>ZERO</b> Zero bits padding mode</li>
* <li><b>RANDOM</b> Random bits padding mode</li>
* </ul>
* </li>
* <li>Wrapping key modes (parameter 'keyWrapping')
* <ul>
* <li><b>NO</b> Ref. rfc4357 6.1 GOST 28147-89 Key wrapping</li>
* <li><b>CP</b> CryptoPro Key wrapping mode</li>
* <li><b>SC</b> SignalCom Key wrapping mode</li>
* </ul>
* </li>
* </ul>
*
* @memberOf gostEngine
* @param {AlgorithmIndentifier} algorithm Algorithm identifier
* @returns {GostCipher} Instance of GostCipher
*/
getGostCipher: function getGostCipher(algorithm) // <editor-fold defaultstate="collapsed">
{
return new (GostCipher || (GostCipher = root.GostCipher))(algorithm);
},
// </editor-fold>
/**
* gostEngine.getGostDigest(algorithm) returns GOST R 34.11 cipher instance<br><br>
*
* Normalized algorithm identifier common parameters:
*
* <ul>
* <li><b>name</b> Algorithm name 'GOST R 34.11'</li>
* <li><b>version</b> Algorithm version
* <ul>
* <li><b>1994</b> old-style 256 bits digest based on GOST 28147-89</li>
* <li><b>2012</b> 256 ro 512 bits digest algorithm "Streebog" GOST R 34.11-2012 (default)</li>
* </ul>
* </li>
* <li><b>length</b> Digest length
* <ul>
* <li><b>256</b> 256 bits digest</li>
* <li><b>512</b> 512 bits digest, valid only for algorithm "Streebog"</li>
* </ul>
* </li>
* <li><b>mode</b> Algorithm mode
* <ul>
* <li><b>HASH</b> simple digest mode (default)</li>
* <li><b>HMAC</b> HMAC algorithm based on GOST R 34.11</li>
* <li><b>KDF</b> Derive bits for KEK deversification</li>
* <li><b>PBKDF2</b> Password based key dirivation algorithms PBKDF2 (based on HMAC)</li>
* <li><b>PFXKDF</b> PFX key dirivation algorithms PFXKDF</li>
* <li><b>CPKDF</b> CryptoPro Password based key dirivation algorithms</li>
* </ul>
* </li>
* <li><b>sBox</b> Paramset sBox for GOST 28147-89. Used only if version = 1994</li>
* </ul>
*
* Supported algorithms, modes and parameters:
*
* <ul>
* <li>Digest HASH mode (default)</li>
* <li>Sign/Verify HMAC modes parameters depends on version and length
* <ul>
* <li><b>version: 1994</b> HMAC parameters (B = 32, L = 32)</li>
* <li><b>version: 2012, length: 256</b> HMAC parameters (B = 64, L = 32)</li>
* <li><b>version: 2012, length: 512</b> HMAC parameters (B = 64, L = 64)</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey KDF mode
* <ul>
* <li><b>context</b> {@link CryptoOperationData} Context of the key derivation</li>
* <li><b>label</b> {@link CryptoOperationData} Label that identifies the purpose for the derived keying material</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey PBKDF2 mode
* <ul>
* <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
* <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey PFXKDF mode
* <ul>
* <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
* <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
* <li><b>diversifier</b> Deversifier, ID=1 - key material for performing encryption or decryption,
* ID=2 - IV (Initial Value) for encryption or decryption, ID=3 - integrity key for MACing</li>
* </ul>
* </li>
* <li>DeriveBits/DeriveKey CPKDF mode
* <ul>
* <li><b>salt</b> {@link CryptoOperationData} Random salt as input for HMAC algorithm</li>
* <li><b>iterations</b> Iteration count. GOST recomended value 1000 (default) or 2000</li>
* </ul>
* </li>
* </ul>
*
* @memberOf gostEngine
* @param {AlgorithmIndentifier} algorithm Algorithm identifier
* @returns {GostDigest} Instance of GostDigest
*/
getGostDigest: function getGostDigest(algorithm) // <editor-fold defaultstate="collapsed">
{
return new (GostDigest || (GostDigest = root.GostDigest))(algorithm);
},
// </editor-fold>
/**
* gostEngine.getGostSign(algorithm) returns GOST R 34.10 cipher instance<br><br>
*
* Normalized algorithm identifier common parameters:
*
* <ul>
* <li><b>name</b> Algorithm name 'GOST R 34.10'</li>
* <li><b>version</b> Algorithm version
* <ul>
* <li><b>1994</b> - Old-style GOST R 34.10-94 ExpMod algorithm with GOST R 34.11-94 hash</li>
* <li><b>2001</b> - GOST R 34.10-2001 Eliptic curve algorithm with old GOST R 34.11-94 hash</li>
* <li><b>2012</b> - GOST R 34.10-2012 Eliptic curve algorithm with GOST R 34.11-12 hash, default mode</li>
* </ul>
* </li>
* <li><b>length</b> Length of hash and signature. Key length == hash length for EC algorithms and 2 * hash length for ExpMod algorithm
* <ul>
* <li><b>GOST R 34.10-256</b> - 256 bits digest, default mode</li>
* <li><b>GOST R 34.10-512</b> - 512 bits digest only for GOST R 34.11-2012 hash</li>
* </ul>
* </li>
* <li><b>mode</b> Algorithm mode
* <ul>
* <li><b>SIGN</b> Digital signature mode (default)</li>
* <li><b>DH</b> Diffie-Hellman key generation and key agreement mode</li>
* <li><b>MASK</b> Key mask mode</li>
* </ul>
* </li>
* <li><b>sBox</b> Paramset sBox for GOST 34.11-94. Used only if version = 1994 or 2001</li>
* </ul>
*
* Supported algorithms, modes and parameters:
*
* <ul>
* <li>Sign/Verify mode (SIGN)</li>
* <li>Wrap/Unwrap mode (MASK)</li>
* <li>DeriveKey/DeriveBits mode (DH)
* <ul>
* <li>{@link CryptoOperationData} <b>ukm</b> User key material. Default - random generated value</li>
* <li>{@link CryptoOperationData} <b>public</b> The peer's EC public key data</li>
* </ul>
* </li>
* <li>GenerateKey mode (SIGN and DH and MASK) version = 1994
* <ul>
* <li><b>namedParam</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
* </ul>
* Additional parameters, if namedParam not specified
* <ul>
* <li><b>modulusLength</b> Bit length of p (512 or 1024 bits). Default = 1024</li>
* <li><b>p</b> {@link CryptoOperationData} Modulus, prime number, 2^(t-1)<p<2^t</li>
* <li><b>q</b> {@link CryptoOperationData} Order of cyclic group, prime number, 2^254<q<2^256, q is a factor of p-1</li>
* <li><b>a</b> {@link CryptoOperationData} Generator, integer, 1<a<p-1, at that aq (mod p) = 1</li>
* </ul>
* </li>
* <li>GenerateKey mode (SIGN and DH and MASK) version = 2001 or 2012
* <ul>
* <li><b>namedCurve</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
* </ul>
* Additional EC parameters, if namedCurve not specified
* <ul>
* <li><b>p</b> {@link CryptoOperationData} Prime number - elliptic curve modulus</li>
* <li><b>a</b> {@link CryptoOperationData} Coefficients a of the elliptic curve E</li>
* <li><b>b</b> {@link CryptoOperationData} Coefficients b of the elliptic curve E</li>
* <li><b>q</b> {@link CryptoOperationData} Prime number - order of cyclic group</li>
* <li><b>x</b> {@link CryptoOperationData} Base point p x-coordinate</li>
* <li><b>y</b> {@link CryptoOperationData} Base point p y-coordinate</li>
* </ul>
* </li>
* </ul>
*
* @memberOf gostEngine
* @param {AlgorithmIndentifier} algorithm Algorithm identifier
* @returns {GostSign} Instance of GostSign
*/
getGostSign: function getGostSign(algorithm) // <editor-fold defaultstate="collapsed">
{
return new (GostSign || (GostSign = root.GostSign))(algorithm);
} // </editor-fold>
};
/*
* Worker method execution
*
*/
// <editor-fold defaultstate="collapsed">
// Worker for gostCripto method execution
if (root.importScripts) {
/**
* Method called when {@link SubtleCrypto} calls its own postMessage()
* method with data parameter: algorithm, method and arg.<br>
* Call method execute and postMessage() results to onmessage event handler
* in the main process.<br>
* If error occured onerror event handler executed in main process.
*
* @memberOf gostEngine
* @name onmessage
* @param {MessageEvent} event Message event with data {algorithm, method, args}
*/
root.onmessage = function (event) {
try {
postMessage({
id: event.data.id,
result: gostEngine.execute(event.data.algorithm, event.data.method, event.data.args)
});
} catch (e) {
postMessage({
id: event.data.id,
error: e.message
});
}
};
} else {
// Load dependens
var baseUrl = '',
nameSuffix = ''; // Try to define from DOM model
if (typeof document !== 'undefined') {
(function () {
var regs = /^(.*)gostCrypto(.*)\.js$/i;
var list = document.querySelectorAll('script');
for (var i = 0, n = list.length; i < n; i++) {
var value = list[i].getAttribute('src');
var test = regs.exec(value);
if (test) {
baseUrl = test[1];
nameSuffix = test[2];
}
}
})();
} // Local importScripts procedure for include dependens
var importScripts = function importScripts() {
for (var i = 0, n = arguments.length; i < n; i++) {
var name = arguments[i].split('.'),
src = baseUrl + name[0] + nameSuffix + '.' + name[1];
var el = document.querySelector('script[src="' + src + '"]');
if (!el) {
el = document.createElement('script');
el.setAttribute('src', src);
document.head.appendChild(el);
}
}
}; // Import engines
if (!GostRandom) importScripts('gostRandom.js');
if (!GostCipher) importScripts('gostCipher.js');
if (!GostDigest) importScripts('gostDigest.js');
if (!GostSign) importScripts('gostSign.js');
} // </editor-fold>
return gostEngine;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostCipher":108,"./gostDigest":111,"./gostRandom":114,"./gostSign":116}],113:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file Key and Certificate Store methods
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostCrypto', 'gostASN1', 'gostCert', 'gostCMS'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostCrypto'), require('./gostASN1'), require('./gostCert'), require('./gostCMS'));
} else {
root.GostKeys = factory(root.gostCrypto, root.GostASN1, root.GostCert, root.GostCMS);
} // </editor-fold>
})(void 0, function (gostCrypto) {
/*
* Common tools and methods
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var Promise = root.Promise;
var Object = root.Object;
var CryptoOperationData = root.ArrayBuffer;
var Date = root.Date;
var subtle = gostCrypto.subtle;
var asn1 = gostCrypto.asn1;
var coding = gostCrypto.coding;
var providers = gostCrypto.security.providers;
var cert = gostCrypto.cert;
var cms = gostCrypto.cms; // Expand javascript object
function expand() {
var r = {};
for (var i = 0, n = arguments.length; i < n; i++) {
var item = arguments[i];
if (_typeof(item) === 'object') for (var name in item) {
if (item.hasOwnProperty(name)) r[name] = item[name];
}
}
return r;
}
function defineProperty(object, name, descriptor, enumerable) {
if (_typeof(descriptor) !== 'object') descriptor = {
value: descriptor
};
if (enumerable !== undefined) descriptor.enumerable = enumerable;
Object.defineProperty(object, name, descriptor);
}
function defineProperties(object, properties, enumerable) {
for (var name in properties) {
defineProperty(object, name, properties[name], enumerable);
}
} // Extend javascript class
function extend(Super, Class, propertiesObject, propertiesClass) {
// If constructor not defined
if (typeof Class !== 'function') {
propertiesClass = propertiesObject;
propertiesObject = Class;
Class = function Class() {
Super.apply(this, arguments);
};
} // Create prototype properties
Class.prototype = Object.create(Super.prototype, {
constructor: {
value: Class
},
superclass: {
value: Super.prototype
}
});
if (propertiesObject) defineProperties(Class.prototype, propertiesObject, true); // Inherites super class properties
if (Super !== Object) for (var name in Super) {
Class[name] = Super[name];
}
Class["super"] = Super;
if (propertiesClass) defineProperties(Class, propertiesClass, true);
return Class;
} // Get random values
function getSeed(length) {
var seed = new Uint8Array(length);
gostCrypto.getRandomValues(seed);
return seed.buffer;
} // Self resolver
function call(callback) {
try {
callback();
} catch (e) {}
} // Get buffer
function buffer(d) {
if (d instanceof CryptoOperationData) return d;else if (d && d.buffer && d.buffer instanceof CryptoOperationData) return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ? d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;else throw new DataError('CryptoOperationData required');
} // Today date + n days with time
function now(n) {
var date = new Date();
if (n) date.setDate(date.getDate() + n);
return date;
} // Today date + n days
function today(n) {
var date = now(n);
date.setHours(0, 0, 0, 0);
return date;
} // Check the buffers to equal
function equalBuffers(r1, r2) {
var s1 = new Uint8Array(r1),
s2 = new Uint8Array(r2);
if (s1.length !== s2.length) return false;
for (var i = 0, n = s1.length; i < n; i++) {
if (s1[i] !== s2[i]) return false;
}
return true;
} // Generate new alias
function generateUUID() {
var r = new Uint8Array(getSeed(16)),
s = '';
for (var i = 0; i < 16; i++) {
s += ('00' + r[i].toString(16)).slice(-2);
}
return s.substr(0, 8) + '-' + s.substr(8, 4) + '-4' + s.substr(13, 3) + '-9' + s.substr(17, 3) + '-' + s.substr(20, 12);
} // Return get32 from buffer
function get32(buffer, offset) {
var r = new Uint8Array(buffer, offset, 4);
return r[3] << 24 | r[2] << 16 | r[1] << 8 | r[0];
}
function set32(buffer, offset, _int) {
var r = new Uint8Array(buffer, offset, 4);
r[3] = _int >>> 24;
r[2] = _int >>> 16 & 0xff;
r[1] = _int >>> 8 & 0xff;
r[0] = _int & 0xff;
return r;
} // Salt size
function saltSize(algorithm) {
switch (algorithm.id) {
case 'pbeWithSHAAnd40BitRC2-CBC':
case 'pbeWithSHAAnd128BitRC2-CBC':
return 8;
case 'pbeUnknownGost':
return 16;
case 'sha1':
return 20;
default:
return 32;
}
} // Password to bytes
function passwordData(derivation, password) {
if (!password) return new CryptoOperationData(0);
if (derivation.name.indexOf('CPKDF') >= 0) {
// CryptoPro store password
var r = [];
for (var i = 0; i < password.length; i++) {
var c = password.charCodeAt(i);
r.push(c & 0xff);
r.push(c >>> 8 & 0xff);
r.push(0);
r.push(0);
}
return new Uint8Array(r).buffer;
} else if (derivation.name.indexOf('PFXKDF') >= 0) // PKCS#12 unicode password
return coding.Chars.decode(password + '\0', 'unicode');else // PKCS#5 password mode
return coding.Chars.decode(password, 'utf8');
} // </editor-fold>
/**
* Key and Certificate Store methods
*
* @class GostKeys
*/
function GostKeys() {}
/**
* Key templates
* <ul>
* <li>providerName - provider name for key encryption, default 'CP-01'</li>
* <li>days - validity of the key in days, default 7305</li>
* </ul>
*
* @memberOf GostKeys
* @instance
*/
var options = {
// <editor-fold defaultstate="collapsed">
providerName: 'CP-01',
days: 7305 // </editor-fold>
};
GostKeys.prototype.options = options;
/**
* A class for private keys in PKCS #8 format
*
* @class GostKeys.PKCS8
* @extends GostASN1.PrivateKeyInfo
* @param {(FormatedData|GostASN1.PrivateKeyInfo)} keyInfo
*/
function PKCS8(keyInfo) {
asn1.PrivateKeyInfo.call(this, keyInfo);
}
extend(asn1.PrivateKeyInfo, PKCS8, {
/**
* Get the private key
*
* @memberOf GostKeys.PKCS8
* @instance
* @returns {Promise} Promise to return the {@link Key}
*/
getPrivateKey: function getPrivateKey() // <editor-fold defaultstate="collapsed">
{
var keyUsages = this.privateKeyAlgorithm.id === 'rsaEncryption' ? ['sign'] : ['sign', 'deriveKey', 'deriveBits'];
return subtle.importKey('pkcs8', this.encode(), this.privateKeyAlgorithm, 'true', keyUsages);
},
// </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.PKCS8
* @instance
* @param {Key} privateKey The Private Key
* @returns {Promise} Promise to return the self object after set the key
*/
setPrivateKey: function setPrivateKey(privateKey) // <editor-fold defaultstate="collapsed">
{
var self = this;
return subtle.exportKey('pkcs8', privateKey).then(function (keyInfo) {
asn1.PrivateKeyInfo.call(self, keyInfo);
return self;
});
},
// </editor-fold>
/**
* Generate private key and return certification request
*
* @memberOf GostKeys.PKCS8
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm identifier
* @returns {Promise} Promise to return the {@link GostCert.Request} after key generation
*/
generate: function generate(req, keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request)) req = new cert.Request(req); // Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
asn1.PrivateKeyInfo.call(self, key);
;
return req;
});
} // </editor-fold>
});
/**
* A class for private keys in PKCS #8 format
*
* @memberOf GostKeys
* @type GostKeys.PKCS8
*/
GostKeys.prototype.PKCS8 = PKCS8;
/**
* A class for PKCS #5 and PKCS #12 password-encrypted private keys in PKCS #8 format
*
* @class GostKeys.PKCS8Encrypted
* @extends GostASN1.EncryptedPrivateKeyInfo
* @param {(FormatedData|GostASN1.EncryptedPrivateKeyInfo)} encryptedKey
*/
function PKCS8Encrypted(encryptedKey) {
asn1.EncryptedPrivateKeyInfo.call(this, encryptedKey);
}
extend(asn1.EncryptedPrivateKeyInfo, PKCS8Encrypted, {
/**
* Get the private key info
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @returns {Promise} Promise to return decrypted {@link GostKeys.PKCS8}
*/
getKey: function getKey(keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
engine;
return new Promise(call).then(function () {
engine = new cms.EncryptedDataContentInfo({
contentType: 'encryptedData',
version: 0,
encryptedContentInfo: {
contentType: 'data',
contentEncryptionAlgorithm: self.encryptionAlgorithm,
encryptedContent: self.encryptedData
}
});
return engine.getEnclosed(keyPassword);
}).then(function (contentInfo) {
// Create key object
return PKCS8.decode(contentInfo.content);
});
},
// </editor-fold>
/**
* Get the private key
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @returns {Promise} Promise to return decrypted {@link Key}
*/
getPrivateKey: function getPrivateKey(keyPassword) // <editor-fold defaultstate="collapsed">
{
return this.getKey(keyPassword).then(function (keyInfo) {
return keyInfo.getPrivateKey();
});
},
// </editor-fold>
/**
* Sets and encrypt the private key info
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(FormatedData|GostKeys.PKCS8)} keyInfo The private key info
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for encryption
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return self object after set key
*/
setKey: function setKey(keyInfo, keyPassword, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this,
engine;
return new Promise(call).then(function () {
keyInfo = new PKCS8(keyInfo);
engine = new cms.EncryptedDataContentInfo();
return engine.encloseContent(keyInfo.encode(), keyPassword, encryptionAlgorithm || options.providerName);
}).then(function () {
self.encryptionAlgorithm = engine.encryptedContentInfo.contentEncryptionAlgorithm;
self.encryptedData = engine.encryptedContentInfo.encryptedContent;
return self;
});
},
// </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {Key} privateKey The private key
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return self object after set key
*/
setPrivateKey: function setPrivateKey(privateKey, keyPassword, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new PKCS8().setPrivateKey(privateKey).then(function (keyInfo) {
return self.setKey(keyInfo, keyPassword, encryptionAlgorithm);
});
},
// </editor-fold>
/**
* Generate private key and return certification request
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return {@link GostCert.Request}
*/
generate: function generate(req, keyPassword, keyAlgorithm, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request)) req = new cert.Request(req); // Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
return self.setKey(key, keyPassword, encryptionAlgorithm);
}).then(function () {
return req;
});
} // </editor-fold>
});
/**
* A class for PKCS #5 and PKCS #12 password-encrypted private keys in PKCS #8 format
*
* @memberOf GostKeys
* @type GostKeys.PKCS8Encrypted
*/
GostKeys.prototype.PKCS8Encrypted = PKCS8Encrypted;
/**
* A class for password-encrypted private keys in SignalCom container<br><br>
*
* The container file list:
* <ul>
* <li>mk.db3 - master key data</li>
* <li>masks.db3 - encrypted or decrypted masks</li>
* <li>kek.opq - wrapped key encryption key</li>
* <li>rand.opq - wrapped random data</li>
* </ul>
*
* @class GostKeys.SignalComKeyContainer
* @param {SignalComKeyContainer} container
*/
function SignalComKeyContainer(container) // <editor-fold defaultstate="collapsed">
{
if (container) {
var self = this;
['mk.db3', 'masks.db3', 'kek.opq', 'rand.opq'].forEach(function (name) {
self[name] = container[name];
});
}
} // </editor-fold>
extend(Object, SignalComKeyContainer, {
/**
* Get password-based encryption key
*
* @memberOf GostKeys.SignalComKeyContainer
* @instance
* @param {string} keyPassword
* @returns {Promise} Promise to return {@link Key}
*/
getEncryptionKey: function getEncryptionKey(keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
wrapping = providers['SC-01'].wrapping,
encryption = providers['SC-01'].encryption,
derivation = providers['SC-01'].derivation,
masks = self['masks.db3'],
mk = self['mk.db3'],
kek = self['kek.opq']; // Decrypt key
return new Promise(call).then(function () {
if (!masks || !mk || !kek) throw new Error('Not enougth key container files'); // Check for encrypted key
if (masks.byteLength > 32) {
if (keyPassword) {
// Extract password based encryption mask
return subtle.importKey('raw', coding.Chars.decode(keyPassword, 'utf8'), derivation, false, ['deriveKey', 'deriveBits']).then(function (integrityKey) {
return subtle.deriveKey(expand(derivation, {
salt: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])
}), integrityKey, encryption, false, ['decrypt']);
}).then(function (encryptionKey) {
var encrypted = new cms.EncryptedDataContentInfo(masks);
return encrypted.getEnclosed(encryptionKey);
}).then(function (digested) {
return digested.verify();
}).then(function (data) {
return data.content;
});
} else throw new Error('Key password is required');
} else if (keyPassword) throw new Error('Key password is not required');
return masks;
}).then(function (decrypedMasks) {
// Combine masks
masks = decrypedMasks;
var mkm = new Uint8Array(mk.byteLength + masks.byteLength);
mkm.set(new Uint8Array(mk), 0);
mkm.set(new Uint8Array(masks), mk.byteLength); // Import master key
return subtle.importKey('raw', mkm.buffer, wrapping, false, ['unwrapKey']);
}).then(function (unwrappingKey) {
// Unwrap kek
return subtle.unwrapKey('raw', kek, unwrappingKey, wrapping, encryption, false, ['wrapKey', 'unwrapKey']);
});
},
// </editor-fold>
/**
* Generate encryption key and container files
*
* @memberOf GostKeys.SignalComKeyContainer
* @instance
* @param {string} keyPassword
* @returns {Promise} Promise to return {@link Key}
*/
generateContainer: function generateContainer(keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
wrapping = providers['SC-01'].wrapping,
encryption = providers['SC-01'].encryption,
derivation = providers['SC-01'].derivation,
digest = providers['SC-01'].digest,
encryptionKey,
wrappingKey;
return new Promise(call).then(function () {
// Generate wrapping key
return subtle.generateKey(wrapping, true, ['wrapKey']);
}).then(function (key) {
wrappingKey = key; // Split masks
var len = wrappingKey.buffer.byteLength;
self['mk.db3'] = new Uint8Array(new Uint8Array(wrappingKey.buffer, 0, len - 32)).buffer;
var masks = new Uint8Array(new Uint8Array(wrappingKey.buffer, len - 32, 32)).buffer;
if (keyPassword) {
// Encrypt masks
var encrypted = new cms.EncryptedDataContentInfo(),
digested = new cms.DigestedDataContentInfo(); // Digest data
return digested.encloseContent(masks, digest).then(function () {
digested = {
// Double wrapping - SignalCom mistake
contentType: 'digestedData',
content: digested.encode()
};
return subtle.importKey('raw', coding.Chars.decode(keyPassword, 'utf8'), derivation, false, ['deriveKey', 'deriveBits']);
}).then(function (integrityKey) {
return subtle.deriveKey(expand(derivation, {
salt: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])
}), integrityKey, encryption, false, ['encrypt']);
}).then(function (encryptionKey) {
// Encrypt data with password
return encrypted.encloseContent(digested, encryptionKey, encryption);
}).then(function () {
return encrypted.encode();
});
}
return masks;
}).then(function (masks) {
self['masks.db3'] = masks; // Generate encryption key
return subtle.generateKey(encryption, false, ['wrapKey', 'unwrapKey']);
}).then(function (key) {
encryptionKey = key; // Wrap encryption key
return subtle.wrapKey('raw', key, wrappingKey, wrapping);
}).then(function (data) {
self['kek.opq'] = data; // Generate random seed
return subtle.generateKey(encryption, false, ['wrapKey', 'unwrapKey']);
}).then(function (key) {
// Wrap random seed
return subtle.wrapKey('raw', key, wrappingKey, wrapping);
}).then(function (data) {
self['rand.opq'] = data;
return encryptionKey;
});
} // </editor-fold>
});
/**
* A class for password-encrypted private keys in SignalCom container
*
* @memberOf GostKeys
* @type GostKeys.SignalComKeyContainer
*/
GostKeys.prototype.SignalComKeyContainer = SignalComKeyContainer;
/**
* A class for password-encrypted SignalCom private keys
*
* @class GostKeys.SignalComPrivateKeyInfo
* @extends GostASN1.GostWrappedPrivateKey
* @extends GostKeys.SignalComKeyContainer
* @param {GostASN1.PrivateKeyInfo} keyInfo
* @param {GostKeys.SignalComKeyContainer} container
*/
function SignalComPrivateKeyInfo(keyInfo, container) // <editor-fold defaultstate="collapsed">
{
asn1.GostWrappedPrivateKey.call(this, keyInfo);
SignalComKeyContainer.call(this, container);
} // </editor-fold>
extend(asn1.GostWrappedPrivateKey, SignalComPrivateKeyInfo, {
/**
* Get the private key info
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @param {string} keyPassword The password for decryption
* @returns {Promise} Promise to return {@link GostKeys.PKCS8}
*/
getKey: function getKey(keyPassword) // <editor-fold defaultstate="collapsed">
{
return this.getPrivateKey(keyPassword).then(function (privateKey) {
return new PKCS8().setPrivateKey(privateKey);
});
},
// </editor-fold>
/**
* Get the private key
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {string} keyPassword The password for decryption
* @returns {Promise} Promise to return the {@link Key}
*/
getPrivateKey: function getPrivateKey(keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
wrapping = providers['SC-01'].wrapping,
publicKeyData; // Decrypt key
return new Promise(call).then(function () {
// Get password key
return self.getEncryptionKey(keyPassword, true);
}).then(function (encryptionKey) {
// Unwrap private key
return subtle.unwrapKey('raw', self.privateKeyWrapped, encryptionKey, wrapping, self.privateKeyAlgorithm, true, ['sign', 'deriveKey', 'deriveBits']);
}).then(function (privateKey) {
publicKeyData = self.attributes && self.attributes['id-sc-gostR3410-2001-publicKey']; // Generate key pair
if (publicKeyData) return subtle.generateKey(expand(privateKey.algorithm, {
ukm: privateKey.buffer
}), privateKey.extractable, privateKey.usages);else return {
privateKey: privateKey
};
}).then(function (keyPair) {
// Compare public key
if (publicKeyData && !equalBuffers(keyPair.publicKey.buffer, publicKeyData)) throw new Error('Check public key failed');
return keyPair.privateKey;
});
},
// </editor-fold>
/**
* Sets and encrypt the private key info
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {(FormatedData|GostKeys.PKCS8)} keyInfo The private key info
* @param {string} keyPassword The password for encryption
* @returns {Promise} Promise to return self object after set the key
*/
setKey: function setKey(keyInfo, keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new PKCS8(keyInfo).getPrivateKey().then(function (privateKey) {
return self.setPrivateKey(privateKey, keyPassword);
});
},
// </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {Key} privateKey The private key
* @param {string} keyPassword The secret key encryption
* @returns {Promise} Promise to return self object after set the key
*/
setPrivateKey: function setPrivateKey(privateKey, keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
wrapping = providers['SC-01'].wrapping,
wrappedData;
return new Promise(call).then(function () {
// Get or generate encryption key
return self.getEncryptionKey(keyPassword)['catch'](function () {
return self.generateContainer(keyPassword);
});
}).then(function (encryptionKey) {
// Encrypt key buffer
return subtle.wrapKey('raw', privateKey, encryptionKey, wrapping);
}).then(function (data) {
wrappedData = data; // Generate public key
return subtle.generateKey(expand(privateKey.algorithm, {
ukm: privateKey.buffer
}), true, ['sign', 'verify']);
}).then(function (keyPair) {
self.object = {
version: 0,
privateKeyAlgorithm: privateKey.algorithm,
privateKeyWrapped: wrappedData,
attributes: {
'id-sc-gostR3410-2001-publicKey': keyPair.publicKey.buffer
}
};
return self;
});
},
// </editor-fold>
/**
* Change key password
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {string} oldKeyPassword Old key password
* @param {string} newKeyPassword New key password
* @returns {Promise} Promise to return self object after change password
*/
changePassword: function changePassword(oldKeyPassword, newKeyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this;
return self.getPrivateKey(oldKeyPassword).then(function (privateKey) {
return self.setPrivateKey(privateKey, newKeyPassword);
});
},
// </editor-fold>
/**
* Generate private key, certificate and return certification request
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm
* @returns {Promise} Promise to return {@link GostCert.Request}
*/
generate: function generate(req, keyPassword, keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this,
keyInfo;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request)) req = new cert.Request(req); // Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
keyInfo = key;
return self.setKey(keyInfo, keyPassword);
}).then(function () {
return req;
});
} // </editor-fold>
});
defineProperties(SignalComPrivateKeyInfo.prototype, SignalComKeyContainer.prototype);
/**
* A class for password-encrypted SignalCom private keys
*
* @memberOf GostKeys
* @type GostKeys.SignalComPrivateKeyInfo
*/
GostKeys.prototype.SignalComPrivateKeyInfo = SignalComPrivateKeyInfo;
/**
* A class for password-encrypted private keys in CryptoPro container
*
* The container file list:
* <ul>
* <li>header - container header @link GostASN1.GostKeyContainer</li>
* <li>name - container name @link GostASN1.GostKeyContainerName</li>
* <li>primary - private keys data @link GostASN1.GostPrivateKeys</li>
* <li>masks - private key masks @link GostASN1.GostPrivateMasks</li>
* <li>primary2 - reserve of private keys data @link GostASN1.GostPrivateKeys</li>
* <li>masks2 - reserve of private key masks @link GostASN1.GostPrivateMasks</li>
* </ul>
*
* @class GostKeys.CryptoProKeyContainer
* @param {Object} container
*/
function CryptoProKeyContainer(container) // <editor-fold defaultstate="collapsed">
{
if (container) {
this.header = asn1.GostKeyContainer.decode(container.header);
this.name = asn1.GostKeyContainerName.decode(container.name);
this.primary = asn1.GostPrivateKeys.decode(container.primary);
this.masks = asn1.GostPrivateMasks.decode(container.masks);
if (container.primary2 && container.masks2) {
this.primary2 = asn1.GostPrivateKeys.decode(container.primary2);
this.masks2 = asn1.GostPrivateMasks.decode(container.masks2);
}
}
} // </editor-fold>
extend(Object, CryptoProKeyContainer, function () {
// <editor-fold defaultstate="collapsed">
// True if 512 bit
function isKeySize512(algorithm) {
return algorithm.name.indexOf('-512') >= 0 || algorithm.length === 512;
} // Test version 2012
function isVersion2012(algorithm) {
return !(algorithm.name.indexOf('-94') >= 0 || algorithm.name.indexOf('-2001') >= 0 || algorithm.version === 1994 || algorithm.version === 2001);
} // Derive password key
function derivePasswordKey(algorithm, password, salt) {
var hash = isVersion2012(algorithm) ? 'GOST R 34.11-256' : 'GOST R 34.11-94/' + (algorithm.sBox || 'D-A'),
derivation = {
name: 'CPKDF',
hash: hash,
salt: salt,
iterations: password ? 2000 : 2
}; // Import password
return subtle.importKey('raw', passwordData(derivation, password), derivation, false, ['deriveKey', 'deriveBits']).then(function (baseKey) {
// Derive key
return subtle.deriveKey(derivation, baseKey, 'GOST 28147', false, ['sign', 'verify', 'encrypt', 'decrypt']);
});
} // Compute password MAC
function computePasswordMAC(algorithm, password, salt) {
var mac = expand({
name: 'GOST 28147-MAC'
}, algorithm.encParams); // Derive password
return derivePasswordKey(algorithm, password, salt).then(function (macKey) {
// Mac for 16 zero bytes
return subtle.sign(mac, macKey, new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
});
} // var lastBuffer;
// Compute container MAC
function computeContainerMAC(algorithm, content) {
var mac = expand({
name: 'GOST 28147-MAC'
}, algorithm.encParams),
keyData = new Uint8Array([// 32 zero bytes
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
return subtle.importKey('raw', keyData, mac, false, ['sign']).then(function (macKey) {
// var buffer = new Uint8Array(content.encode());
// console.log(coding.Hex.encode(buffer));
// if (lastBuffer && lastBuffer.length === buffer.length) {
// for (var i = 0; i < buffer.length; i++)
// if (lastBuffer[i] !== buffer[i])
// console.log('diff at ' + i);
// } else
// console.log('diff length');
// lastBuffer = buffer;
// Mac for content
return subtle.sign(mac, macKey, content.encode());
});
} // Compute mask MAC
function computeMaskMAC(algorithm, mask, status) {
// Import mask as key for MAC
var mac = expand({
name: 'GOST 28147-MAC'
}, algorithm.encParams),
keyData = mask.byteLength === 64 ? new Uint8Array(new Uint8Array(mask, 32, 32)).buffer : mask;
return subtle.importKey('raw', keyData, mac, false, ['sign']).then(function (macKey) {
// Verify MAC for maskStatus
return subtle.sign(mac, macKey, status);
});
} // Generate mask
function generateMasks(algorithm) {
var wrapAlgorithm = expand(algorithm, {
mode: 'MASK'
}),
mask,
status = getSeed(12);
wrapAlgorithm.name = wrapAlgorithm.name.replace('-DH', '');
return subtle.generateKey(wrapAlgorithm, true, ['wrapKey', 'unwrapKey']).then(function (key) {
return subtle.exportKey('raw', key);
}).then(function (data) {
mask = data;
return computeMaskMAC(algorithm, mask, status);
}).then(function (hmac) {
return new asn1.GostPrivateMasks({
mask: mask,
randomStatus: status,
hmacRandom: hmac
});
});
} // Compute FP
function computeFP(privateKey) {
// Generate key pair with predefined ukm for check public key
return subtle.generateKey(expand(privateKey.algorithm, {
ukm: privateKey.buffer
}), true, ['sign', 'verify']).then(function (keyPair) {
return new Uint8Array(new Uint8Array(keyPair.publicKey.buffer, 0, 8)).buffer;
});
} // Unwrap private key
function unwrapKey(algorithm, encryptionKey, key, mask, fp) {
var encryption = {
name: 'GOST 28147-ECB',
sBox: algorithm.encParams && algorithm.encParams.sBox
},
unwrapAlgorithm = expand(algorithm, {
mode: 'MASK'
}),
privateKey;
unwrapAlgorithm.name = unwrapAlgorithm.name.replace('-DH', '');
var wrappedKey; // Encrypt ukm data for private key
return subtle.decrypt(encryption, encryptionKey, key).then(function (data) {
wrappedKey = data; // Import mask key
return subtle.importKey('raw', mask, unwrapAlgorithm, 'false', ['sign', 'unwrapKey']);
}).then(function (unwrappingKey) {
// Unwrap private key
return subtle.unwrapKey('raw', wrappedKey, unwrappingKey, unwrapAlgorithm, algorithm, 'true', ['sign']);
}).then(function (key) {
privateKey = key;
return computeFP(privateKey);
}).then(function (computedFP) {
// Check public key buffer
if (!equalBuffers(computedFP, fp)) throw new Error('Incorrect fp');
return privateKey;
});
} // Wrap private key
function wrapKey(algorithm, encryptionKey, privateKey, mask) {
var encryption = {
name: 'GOST 28147-ECB',
sBox: algorithm.encParams && algorithm.encParams.sBox
},
wrapAlgorithm = expand(algorithm, {
mode: 'MASK'
});
wrapAlgorithm.name = wrapAlgorithm.name.replace('-DH', ''); // Import mask key
return subtle.importKey('raw', mask, wrapAlgorithm, false, ['sign', 'wrapKey']).then(function (wrappingKey) {
// Wrap private key
return subtle.wrapKey('raw', privateKey, wrappingKey, wrapAlgorithm);
}).then(function (wrappedKey) {
// Encrypt key
return subtle.encrypt(encryption, encryptionKey, wrappedKey);
});
} // Decrypt private key
function decryptKey(content, primary, masks, keyPassword, secondary) {
var algorithm = content.primaryPrivateKeyParameters.privateKeyAlgorithm;
return new Promise(call).then(function () {
// Check format
if (primary.hmacKey) throw new Error('Old key format');
if (masks.randomStatus.byteLength < 12) throw new Error("Invalid random status length"); // Import mask as key for MAC
return computeMaskMAC(algorithm, masks.mask, masks.randomStatus);
}).then(function (hmac) {
if (!equalBuffers(hmac, masks.hmacRandom)) throw new Error("Imita for mask is invalid"); // Derive key
return derivePasswordKey(algorithm, keyPassword, new Uint8Array(masks.randomStatus, 0, 12));
}).then(function (encryptionKey) {
// Unwrap keys
return secondary && primary.secondaryKey ? unwrapKey(content.secondaryPrivateKeyParameters.privateKeyAlgorithm, encryptionKey, primary.secondaryKey, masks.mask, content.secondaryFP) : unwrapKey(algorithm, encryptionKey, primary.primaryKey, masks.mask, content.primaryFP);
});
} // Encrypt private key
function encryptKey(algorithm, primary, masks, keyPassword, secondary, privateKey) {
// Derive key
return derivePasswordKey(algorithm, keyPassword, new Uint8Array(masks.randomStatus, 0, 12)).then(function (encryptionKey) {
// Wrap keys
return wrapKey(algorithm, encryptionKey, privateKey, masks.mask);
}).then(function (encryptedKey) {
if (!primary) primary = new asn1.GostPrivateKeys();
if (secondary) {
primary.secondaryKey = encryptedKey;
} else {
primary.primaryKey = encryptedKey;
}
return primary;
});
} // </editor-fold>
return {
/**
* Get the private key info
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {string} keyPassword The password for decryption
* @param {boolean} secondary True if required secondary key
* @returns {Promise} Promise to return {@link GostKeys.PKCS8}
*/
getKey: function getKey(keyPassword, secondary) // <editor-fold defaultstate="collapsed">
{
return this.getPrivateKey(keyPassword, secondary).then(function (privateKey) {
return new PKCS8().setPrivateKey(privateKey);
});
},
// </editor-fold>
/**
* Get the private key
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {string} keyPassword Rhe password for decryption
* @param {boolean} secondary True if required secondary key
* @returns {Promise} Promise to return the {@link Key}
*/
getPrivateKey: function getPrivateKey(keyPassword, secondary) // <editor-fold defaultstate="collapsed">
{
var self = this,
content = self.header.keyContainerContent; // Decrypt key
return decryptKey(content, self.primary, self.masks, keyPassword, secondary)['catch'](function (e) {
if (self.primary2 && self.masks2) return decryptKey(content, self.primary2, self.masks2, keyPassword, secondary);else throw e;
});
},
// </editor-fold>
/**
* Get the certificate from the key container
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {boolean} secondary True for set secondary certificate
* @returns {Promise} Promise to return {@link GostCert.X509}
*/
getCertificate: function getCertificate(secondary) // <editor-fold defaultstate="collapsed">
{
var self = this,
content = self.header.keyContainerContent;
return new Promise(call).then(function () {
if (secondary) return new cert.X509(content.secondaryCertificate);else return new cert.X509(content.primaryCertificate);
});
},
// </editor-fold>
/**
* Get the container name
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @returns {string} Container name
*/
getContainerName: function getContainerName() // <editor-fold defaultstate="collapsed">
{
return this.name.containerName;
},
// </editor-fold>
/**
* Sets and encrypt the private key info
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {(FormatedData|GostKeys.PKCS8)} keyInfo The private key info
* @param {string} keyPassword The assword for encryption
* @param {boolean} secondary True for set secondary key
* @param {number} days Validity days. Default 7305 days (20 years)
* @returns {Promise} Promise to return self object after set key
*/
setKey: function setKey(keyInfo, keyPassword, secondary, days) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new PKCS8(keyInfo).getPrivateKey().then(function (privateKey) {
return self.setPrivateKey(privateKey, keyPassword, secondary, days);
});
},
// </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {Key} privateKey The private key
* @param {string} keyPassword The secret key encryption
* @param {boolean} secondary True for set secondary key
* @param {number} days Validity days. Default 7305 days (20 years)
* @returns {Promise} Promise to return self object after set key
*/
setPrivateKey: function setPrivateKey(privateKey, keyPassword, secondary, days) // <editor-fold defaultstate="collapsed">
{
var self = this,
content,
algorithm;
return new Promise(call).then(function () {
self.header = self.header || new asn1.GostKeyContainer({
keyContainerContent: {
containerAlgoritmIdentifier: {
algorithm: 'id-CryptoPro-GostPrivateKeys-V2-Full'
},
attributes: ['kccaReservePrimary', 'kccaPrimaryKeyAbsent'],
extensions: {
keyValidity: {
notAfter: now(days || options.days)
}
}
}
});
content = self.header.keyContainerContent; // Set private key
var keyParameters = secondary ? content.secondaryPrivateKeyParameters : content.primaryPrivateKeyParameters;
if (!keyParameters) {
algorithm = expand(privateKey.algorithm, {
sBox: "D-A",
encParams: {
block: "CFB",
sBox: "E-A",
keyMeshing: "CP"
}
});
keyParameters = {
attributes: ["pkaExportable", "pkaExchange", "pkaDhAllowed"],
privateKeyAlgorithm: algorithm
};
if (secondary) {
if (!content.primaryPrivateKeyParameters) throw new Error('Primary key must be defined first');
content.secondaryPrivateKeyParameters = keyParameters;
} else {
content.primaryPrivateKeyParameters = keyParameters;
var absent = content.attributes.indexOf('kccaPrimaryKeyAbsent');
if (absent >= 0) content.attributes.splice(absent, 1);
}
} else algorithm = keyParameters.privateKeyAlgorithm; // Generate masks
var promises = [];
[0, 1].forEach(function (i) {
var name = 'masks' + (i > 0 ? '2' : '');
if (!self[name]) promises.push(generateMasks(algorithm).then(function (masks) {
self[name] = masks;
}));
});
return Promise.all(promises);
}).then(function () {
// Encrypt key
var promises = [];
[0, 1].forEach(function (i) {
var name = 'primary' + (i > 0 ? '2' : ''),
maskname = 'masks' + (i > 0 ? '2' : '');
promises.push(encryptKey(algorithm, self[name], self[maskname], keyPassword, secondary, privateKey).then(function (primary) {
self[name] = primary;
}));
});
return Promise.all(promises);
}).then(function () {
// Compute FP for a private key
return computeFP(privateKey).then(function (FP) {
if (secondary) content.secondaryFP = FP;else content.primaryFP = FP;
});
}).then(function () {
// Compute password MAC
var softPassword = content.attributes.indexOf('kccaSoftPassword');
if (keyPassword) {
if (softPassword < 0) content.attributes.push('kccaSoftPassword');
return computePasswordMAC(algorithm, keyPassword, content.primaryFP);
} else {
if (softPassword >= 0) content.attributes.splice(softPassword, 1);
}
}).then(function (hmac) {
if (hmac) content.hmacPassword = hmac; // Calculate container MAC
return computeContainerMAC(algorithm, content);
}).then(function (hmac) {
self.header.hmacKeyContainerContent = hmac;
return self;
});
},
// </editor-fold>
/**
* Set the certificate to the key container
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {(FormatedData|GostCert.X509)} certificate The certificate
* @param {boolean} secondary True for set secondary certificate
* @param {number} days Validity days. Default 7305 days (20 years)
* @returns {Promise} Promise to return self object after set certificate
*/
setCertificate: function setCertificate(certificate, secondary, days) // <editor-fold defaultstate="collapsed">
{
var self = this,
content,
algorithm;
return new Promise(call).then(function () {
self.header = self.header || new asn1.GostKeyContainer({
keyContainerContent: {
containerAlgoritmIdentifier: {
algorithm: 'id-CryptoPro-GostPrivateKeys-V2-Full'
},
attributes: ['kccaReservePrimary', 'kccaPrimaryKeyAbsent'],
extensions: {
keyValidity: {
notAfter: now(days || options.days)
}
}
}
});
content = self.header.keyContainerContent;
certificate = new cert.X509(certificate);
algorithm = content.primaryPrivateKeyParameters && content.primaryPrivateKeyParameters.privateKeyAlgorithm || expand(certificate.subjectPublicKeyInfo.algorithm, {
sBox: "D-A",
encParams: {
block: "CFB",
sBox: "E-A",
keyMeshing: "CP"
}
});
return certificate.getPublicKey();
}).then(function (publicKey) {
if (secondary) {
if (content.secondaryFP && !equalBuffers(content.secondaryFP, new Uint8Array(publicKey.buffer, 0, content.secondaryFP.byteLength))) throw new Error('The public key of the certificate does not match the private key');
content.secondaryCertificate = certificate;
} else {
if (content.primaryFP && !equalBuffers(content.primaryFP, new Uint8Array(publicKey.buffer, 0, content.primaryFP.byteLength))) throw new Error('The public key of the certificate does not match the private key');
content.primaryCertificate = certificate;
} // Calculate container MAC
return computeContainerMAC(algorithm, content);
}).then(function (hmac) {
self.header.hmacKeyContainerContent = hmac;
return self;
});
},
// </editor-fold>
/**
* Set the container name
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {string} name Container name
*/
setContainerName: function setContainerName(name) // <editor-fold defaultstate="collapsed">
{
this.name = new asn1.GostKeyContainerName({
containerName: name
});
},
// </editor-fold>
/**
* Verify key container with password
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {string} keyPassword the secret key or password for decryption
* @returns {Promise} Promise to return self object after verify
*/
verify: function verify(keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
content,
algorithm;
return new Promise(call).then(function () {
content = self.header.keyContainerContent;
algorithm = content.primaryPrivateKeyParameters.privateKeyAlgorithm; // Verify container MAC
return computeContainerMAC(algorithm, content);
}).then(function (hmac) {
if (!equalBuffers(hmac, self.header.hmacKeyContainerContent)) throw new Error("Container is not valid."); // Verify key password MAC
var needPassword = content.attributes.indexOf('kccaSoftPassword') >= 0;
if (!keyPassword && needPassword) throw new Error("Password is required");
if (keyPassword && !needPassword) throw new Error("Password is not reqiured.");
if (keyPassword) // Derive password
return computePasswordMAC(algorithm, keyPassword, content.primaryFP).then(function (hmac) {
if (!equalBuffers(hmac, content.hmacPassword)) throw new Error("Password is not valid.");
return self;
});
return self;
});
},
// </editor-fold>
/**
* Change key password
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {string} oldKeyPassword Old key password
* @param {string} newKeyPassword New key password
* @returns {Promise} Promise to return self object after change password
*/
changePassword: function changePassword(oldKeyPassword, newKeyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
content;
return new Promise(call).then(function () {
content = self.header.keyContainerContent;
if (!content.primaryPrivateKeyParameters) throw new Error('Private key not yet defined');
return self.getPrivateKey(oldKeyPassword).then(function (privateKey) {
return self.setPrivateKey(privateKey, newKeyPassword);
});
}).then(function () {
if (content.secondaryPrivateKeyParameters) return self.getPrivateKey(oldKeyPassword, true).then(function (privateKey) {
return self.setPrivateKey(privateKey, newKeyPassword, true);
});
return self;
});
},
// </editor-fold>
/**
* Generate private key, certificate and return certification request
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm
* @returns {Promise} Promise to return {@link GostCert.Request}
*/
generate: function generate(req, keyPassword, keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this,
certificate,
keyInfo;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request)) req = new cert.Request(req); // Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
keyInfo = key;
return self.setKey(keyInfo, keyPassword);
}).then(function () {
// Create the new certificate
certificate = new cert.X509(req);
return certificate.sign(keyInfo);
}).then(function () {
return self.setCertificate(certificate);
}).then(function () {
return req;
});
},
// </editor-fold>
/**
* Encode key container
*
* @memberOf GostKeys.CryptoProKeyContainer
* @instance
* @param {string} format Encode format 'DER', 'CER', 'PEM'
* @returns {Object} container Object contains encoded files
*/
encode: function encode(format) // <editor-fold defaultstate="collapsed">
{
return {
header: this.header.encode(format),
name: this.name.encode(format),
masks: this.masks.encode(format),
primary: this.primary.encode(format),
masks2: this.masks2.encode(format),
primary2: this.primary2.encode(format)
};
} // </editor-fold>
};
}());
/**
* A class for password-encrypted private keys in CryptoPro container
*
* @memberOf GostKeys
* @type GostKeys.SignalComPrivateKeyInfo
*/
GostKeys.prototype.CryptoProKeyContainer = CryptoProKeyContainer;
/**
* A class for password-encrypted private keys in ViPNet container entry
*
* @class GostKeys.ViPNetContainerEntry
* @extends GostASN1.ViPNetInfo
* @param {(FormatedData|GostKeys.ViPNetContainerEntry)} entry
*/
function ViPNetContainerEntry(entry) // <editor-fold defaultstate="collapsed">
{
asn1.ViPNetInfo.call(this, entry || {
version: 3,
keyInfo: {
keyClass: 1,
keyType: 43556,
flags: 1
},
defenceKeyInfo: {
keyClass: 1024,
keyType: 24622,
keyUID: getSeed(32),
flags: -2147483648
}
});
} // </editor-fold>
extend(asn1.ViPNetInfo, ViPNetContainerEntry, function () {
function getKeyPassword(keyPassword) // <editor-fold defaultstate="collapsed">
{
if (keyPassword === undefined) keyPassword = ''; // Generate key data
var passwordData = coding.Chars.decode(keyPassword, 'win1251'),
keyData;
return subtle.digest('GOST R 34.11-94', passwordData).then(function (data) {
keyData = data; // Generate mask data
var secodeData = new Uint8Array(passwordData.byteLength + keyData.byteLength);
secodeData.set(new Uint8Array(passwordData), 0);
secodeData.set(new Uint8Array(keyData), passwordData.byteLength);
return subtle.digest('GOST R 34.11-94', secodeData);
}).then(function (data) {
// Remove mask
return subtle.importKey('raw', data, 'GOST 28147', false, ['unwrapKey']);
}).then(function (unwrappingKey) {
// Unwrap secret key
return subtle.unwrapKey('raw', keyData, unwrappingKey, 'GOST 28147-MASK/VN', 'GOST 28147-89', 'false', ['encrypt', 'decrypt', 'sign', 'verify']);
});
} // </editor-fold>
return {
/**
* Get the private key
*
* @memberOf GostKeys.ViPNetContainerEntry
* @instance
* @param {string} keyPassword The password of secrect key for decryption
* @returns {Promise} Promise to return the {@link Key}
*/
getPrivateKey: function getPrivateKey(keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this,
keyPart,
encryptedKey; // Decrypt key
return new Promise(call).then(function () {
return !keyPassword || typeof keyPassword === 'string' ? getKeyPassword(keyPassword) : keyPassword;
}).then(function (key) {
keyPassword = key; // Verify password
keyPart = self.keyPart;
encryptedKey = new Uint8Array(keyPart, 0, keyPart.byteLength - 4 - 8);
var macKey = new Uint8Array(keyPart, encryptedKey.byteLength, 4),
encodedKeyInfo = self.keyInfo.encode(),
data = new Uint8Array(encryptedKey.byteLength + encodedKeyInfo.byteLength);
data.set(new Uint8Array(encryptedKey), 0);
data.set(new Uint8Array(encodedKeyInfo), encryptedKey.byteLength);
return subtle.verify({
name: 'GOST 28147-89-MAC'
}, keyPassword, macKey, data);
}).then(function (result) {
if (!result) throw new Error('Invalid key password');
var iv = new Uint8Array(keyPart, keyPart.byteLength - 8, 8); // Decrypt key data
return subtle.decrypt({
name: 'GOST 28147-89-CFB',
iv: iv
}, keyPassword, encryptedKey);
}).then(function (keyData) {
var l2 = keyData.byteLength / 2;
if (self.keyInfo.keyClass & 0x3 === 0) {
// Secret key. Remove mask and import
return subtle.importKey('raw', new Int32Array(keyData, l2, l2), 'GOST 28147', false, ['unwrapKey']).then(function (unwrappingKey) {
// Unwrap secret key
return subtle.unwrapKey('raw', new Int32Array(keyData, 0, l2), unwrappingKey, 'GOST 28147-MASK/VN', 'GOST 28147-89', 'false', ['encrypt', 'decrypt', 'sign', 'verify']);
});
} else {
// Private key
var algorithm = self.keyInfo.algorithm || self.certificate && self.certificate.subjectPublicKeyInfo.algorithm;
if (!algorithm) throw new Error('Algorithm is not specified');
var unwrapAlgorithm = expand(algorithm, {
mode: 'MASK',
procreator: 'VN'
});
unwrapAlgorithm.name = unwrapAlgorithm.name.replace('-DH', '');
var wrapped = new Uint8Array(keyData, 0, l2),
mask = new Uint8Array(keyData, l2, l2); // Import mask key
return subtle.importKey('raw', mask, unwrapAlgorithm, 'false', ['sign', 'unwrapKey']).then(function (unwrappingKey) {
// Unwrap private key
return subtle.unwrapKey('raw', wrapped, unwrappingKey, unwrapAlgorithm, algorithm, 'true', ['sign', 'deriveBits', 'deriveKey']);
}).then(function (privateKey) {
// Generate key pair
if (self.publicKey) return subtle.generateKey(expand(privateKey.algorithm, {
ukm: privateKey.buffer
}), privateKey.extractable, privateKey.usages);else return {
privateKey: privateKey
};
}).then(function (keyPair) {
// Compare public key
if (self.publicKey && !equalBuffers(keyPair.publicKey.buffer, self.publicKey)) throw new Error('Check public key failed');
return keyPair.privateKey;
});
}
});
},
// </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.ViPNetContainerEntry
* @instance
* @param {Key} privateKey The private key
* @param {string} keyPassword The secret key encryption
* @param {number} days Validity days. Default 7305 days (20 years)
* @returns {Promise} Promise to return the self object after set the key
*/
setPrivateKey: function setPrivateKey(privateKey, keyPassword, days) // <editor-fold defaultstate="collapsed">
{
var self = this,
wrapAlgorithm,
wrappingKey,
keyData,
keyPart; // Decrypt key
return new Promise(call).then(function () {
return !keyPassword || typeof keyPassword === 'string' ? getKeyPassword(keyPassword) : keyPassword;
}).then(function (key) {
keyPassword = key;
var algorithm = privateKey.algorithm;
self.keyInfo.algorithm = algorithm;
self.keyInfo.serialNumber = getSeed(16);
self.keyInfo.keyUID = getSeed(8);
self.keyInfo.validity = {
notBefore: today(),
notAfter: today(days || options.days)
};
if (privateKey.type === 'private') {
// Generate mask
wrapAlgorithm = expand(algorithm, {
mode: 'MASK',
procreator: 'VN'
});
wrapAlgorithm.name = wrapAlgorithm.name.replace('-DH', '');
self.keyInfo.keyClass = 1;
self.keyInfo.keyType = 43556; // Generate public key
return subtle.generateKey(expand(algorithm, {
ukm: privateKey.buffer
}), true, ['sign', 'verify']).then(function (keyPair) {
self.publicKey = keyPair.publicKey.buffer; // Check certificate
if (self.certificate) {
var spki = self.certificate.subjectPublicKeyInfo;
return subtle.importKey('spki', spki.encode(), spki.algorithm, true, ['verify']);
}
}).then(function (publicKey) {
if (publicKey && !equalBuffers(publicKey.buffer, self.publicKey)) delete self.certificate; // Remove not valid certificate
});
} else if (privateKey.type === 'secret') {
wrapAlgorithm = 'GOST 28147/MASK/VN';
delete self.certificate;
delete self.publicKey;
self.keyInfo.keyClass = 64;
self.keyInfo.keyType = 24622;
} else throw new Error('Invalid key type');
}).then(function () {
// Generate mask
return subtle.generateKey(wrapAlgorithm, true, ['wrapKey', 'unwrapKey']);
}).then(function (key) {
wrappingKey = key; // Wrap private key with mask
return subtle.wrapKey('raw', privateKey, wrappingKey, wrapAlgorithm);
}).then(function (data) {
keyData = new Uint8Array(data.byteLength * 2);
keyData.set(new Uint8Array(data));
return subtle.exportKey('raw', wrappingKey);
}).then(function (data) {
keyData.set(new Uint8Array(data), data.byteLength);
keyPart = new Uint8Array(keyData.byteLength + 12); // Encrypt key
var encyption = {
name: 'GOST 28147-CFB',
iv: getSeed(8)
};
keyPart.set(new Uint8Array(encyption.iv), keyPart.byteLength - 8);
return subtle.encrypt(encyption, keyPassword, keyData);
}).then(function (encryptedKey) {
keyPart.set(new Uint8Array(encryptedKey)); // Calculate MAC
var encodedKeyInfo = self.keyInfo.encode(),
data = new Uint8Array(encryptedKey.byteLength + encodedKeyInfo.byteLength);
data.set(new Uint8Array(encryptedKey), 0);
data.set(new Uint8Array(encodedKeyInfo), encryptedKey.byteLength);
return subtle.sign({
name: 'GOST 28147-89-MAC'
}, keyPassword, data);
}).then(function (macKey) {
keyPart.set(new Uint8Array(macKey), keyPart.byteLength - 12);
self.keyPart = keyPart.buffer;
return self;
});
},
// </editor-fold>
/**
* Encode container entry
*
* @memberOf GostKeys.ViPNetContainerEntry
* @instance
* @param {string} format The encoded data format
* @returns {CryptoOperationData}
*/
encode: function encode(format) // <editor-fold defaultstate="collapsed">
{
var header = asn1.ViPNetInfo.method('encode').call(this),
result = new Uint8Array(8 + header.byteLength + this.keyPart.byteLength);
set32(result.buffer, 0, 4 + header.byteLength + this.keyPart.byteLength);
result.set(new Uint8Array(header), 4);
set32(result.buffer, 4 + header.byteLength, this.keyPart.byteLength);
result.set(new Uint8Array(this.keyPart), 8 + header.byteLength);
if (format === 'PEM') return coding.Base64.encode(result.buffer);
return result.buffer;
} // </editor-fold>
};
}(), {
/**
* Decode container entry
*
* @memberOf GostKeys.ViPNetContainerEntry
* @param {FormatedData} entry
* @returns {GostKeys.ViPNetContainer}
*/
decode: function decode(entry) // <editor-fold defaultstate="collapsed">
{
if (typeof entry === 'string') entry = coding.Base64.decode(entry);
entry = buffer(entry); // Entry size
var entrySize = get32(entry, 0);
if (entry.byteLength !== entrySize + 4) throw new Error('Invalid container entry size'); // Decode header info
var source = coding.BER.decode(new Uint8Array(entry, 4, entrySize));
var result = asn1.ViPNetInfo.decode.call(this, source); // Decode key info
var headerSize = source.header.byteLength + source.content.byteLength,
keyPartSize = get32(entry, 4 + headerSize);
if (entry.byteLength !== headerSize + keyPartSize + 8) throw new Error('Invalid container key part size');
result.keyPart = new Uint8Array(new Uint8Array(entry, headerSize + 8, keyPartSize)).buffer; // Key Info buffer - can be used in case error of format encoding
// var keyInfoSource = source.object[1];
// result.encodedKeyInfo = new Uint8Array(new Uint8Array(keyInfoSource.header.buffer,
// keyInfoSource.header.byteOffset, keyInfoSource.header.byteLength + keyInfoSource.content.byteLength)).buffer;
return result;
} // </editor-fold>
});
/**
* A class for password-encrypted private keys in CryptoPro container
*
* @memberOf GostKeys
* @type GostKeys.SignalComPrivateKeyInfo
*/
GostKeys.prototype.ViPNetContainerEntry = ViPNetContainerEntry;
/**
* A class for password-encrypted private keys in ViPNet container
*
* @class GostKeys.ViPNetContainer
* @param {(FormatedData|GostKeys.ViPNetContainer)} container
*/
function ViPNetContainer(container) // <editor-fold defaultstate="collapsed">
{
if (container && (container instanceof CryptoOperationData || container.buffer instanceof CryptoOperationData || typeof container === 'string')) this.decode(container);else {
container = container || {};
this.fileType = container.fileType || 'ITCS';
this.fileVersion = container.fileVersion || 0x10;
if (container.applicationHeader) this.applicationHeader = container.applicationHeader;
this.entries = container.entries || [];
}
} // </editor-fold>
extend(Object, ViPNetContainer, {
/**
* Get the certificate from the container
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {number} index Index of the entriy. Default 0
* @returns {Promise} Promise to return {@link GostCert.X509}
*/
getCertificate: function getCertificate(index) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
var entry = self.entries[index || 0];
if (!entry) throw new Error('Entry not defined');
if (entry.certificate) return new cert.X509(entry.certificate);
});
},
// </editor-fold>
/**
* Get the private key info
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {string} keyPassword The password for decryption
* @param {number} index Index of the entriy. Default 0
* @returns {Promise} Promise to return {@link GostKeys.PKCS8}
*/
getKey: function getKey(keyPassword, index) // <editor-fold defaultstate="collapsed">
{
return this.getPrivateKey(keyPassword, index).then(function (privateKey) {
return new PKCS8().setPrivateKey(privateKey);
});
},
// </editor-fold>
/**
* Get the private key
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {string} keyPassword The password of secrect key for decryption
* @param {number} index Index of the entriy. Default 0
* @returns {Promise} Promise to return the {@link Key}
*/
getPrivateKey: function getPrivateKey(keyPassword, index) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
var entry = self.entries[index || 0];
if (!entry) throw new Error('Entry not defined');
return entry.getPrivateKey(keyPassword);
});
},
// </editor-fold>
/**
* Set the certificate to the container
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {(FormatedData|GostCert.X509)} certificate The certificate
* @param {number} index Index of the entriy. Default 0
* @returns {Promise} Promise to return self object after set certificate
*/
setCertificate: function setCertificate(certificate, index) // <editor-fold defaultstate="collapsed">
{
var self = this,
entry,
certificate;
return new Promise(call).then(function () {
entry = self.entries[index || 0] || (self.entries[index || 0] = new ViPNetContainerEntry());
certificate = new cert.X509(certificate);
if (entry.publicKey) return certificate.getPublicKey();
}).then(function (publicKey) {
if (publicKey && !equalBuffers(entry.publicKey, publicKey.buffer)) throw new Error('Invalid certificate for private key');
entry.certificate = certificate;
return self;
});
},
// </editor-fold>
/**
* Set the key to the container
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {(FormatedData|GostKeys.PKCS8)} keyInfo The key
* @param {string} keyPassword The password for decryption
* @param {number} index Index of the entriy. Default 0
* @param {number} days Validity days. Default 7305 days (20 years)
* @returns {Promise} Promise to return self object after set the key
*/
setKey: function setKey(keyInfo, keyPassword, index, days) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new PKCS8(keyInfo).getPrivateKey().then(function (privateKey) {
return self.setPrivateKey(privateKey, keyPassword, index, days);
});
},
// </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.ViPNetContainerEntry
* @instance
* @param {Key} privateKey The private key
* @param {string} keyPassword The secret key encryption
* @param {number} index Index of the entriy. Default 0
* @param {number} days Validity days. Default 7305 days (20 years)
* @returns {Promise} Promise to return the self object after set the key
*/
setPrivateKey: function setPrivateKey(privateKey, keyPassword, index, days) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
var entry = self.entries[index || 0] || (self.entries[index || 0] = new ViPNetContainerEntry());
return entry.setPrivateKey(privateKey, keyPassword, days);
}).then(function () {
return self;
});
},
// </editor-fold>
/**
* Change key password
*
* @memberOf GostKeys.ViPNetContainerEntry
* @instance
* @param {string} oldKeyPassword Old key password
* @param {string} newKeyPassword New key password
* @returns {Promise} Promise to return self object after change password
*/
changePassword: function changePassword(oldKeyPassword, newKeyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
return self.getPrivateKey(oldKeyPassword).then(function (privateKey) {
return self.setPrivateKey(privateKey, newKeyPassword);
});
});
},
// </editor-fold>
/**
* Generate private key, certificate and return certification request
*
* @memberOf GostKeys.ViPNetContainerEntry
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm
* @returns {Promise} Promise to return {@link GostCert.Request}
*/
generate: function generate(req, keyPassword, keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this,
certificate,
keyInfo;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request)) req = new cert.Request(req); // Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
keyInfo = key;
return self.setKey(keyInfo, keyPassword);
}).then(function () {
// Create the new certificate
certificate = new cert.X509(req);
return certificate.sign(keyInfo);
}).then(function () {
return self.setCertificate(certificate);
}).then(function () {
return req;
});
},
// </editor-fold>
/**
* Encode objet to container
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {string} format The encoded data format
* @returns {CryptoOperationData}
*/
encode: function encode(format) // <editor-fold defaultstate="collapsed">
{
// Encode entries
var entries = [],
entriesSize = 0;
this.entries.forEach(function (entry) {
var encoded = entry.encode();
entriesSize += encoded.byteLength;
entries.push(encoded);
});
var headerSize = this.applicationHeader ? this.applicationHeader.byteLength : 0,
result = new Uint8Array(12 + headerSize + entriesSize);
result.set(new Uint8Array(coding.Chars.decode(this.fileType, 'ascii')));
set32(result.buffer, 4, this.fileVersion);
set32(result.buffer, 8, headerSize);
if (headerSize > 0) result.set(new Uint8Array(this.applicationHeader), 12);
var offset = 12 + headerSize;
entries.forEach(function (entry) {
result.set(new Uint8Array(entry), offset);
offset += entry.byteLength;
});
if (format === 'PEM') return coding.Base64.encode(result.buffer);
return result.buffer;
},
// </editor-fold>
/**
* Decode container to the object
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {FormatedData} container
* @returns {GostKeys.ViPNetContainer}
*/
decode: function decode(container) // <editor-fold defaultstate="collapsed">
{
container = this.constructor.decode(container);
this.fileType = container.fileType;
this.fileVersion = container.fileVersion;
if (container.applicationHeader) this.applicationHeader = container.applicationHeader;
this.entries = container.entries;
} // </editor-fold>
}, {
/**
* Encode object
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {GostKeys.ViPNetContainer} object
* @param {string} format The encoded data format
* @returns {CryptoOperationData}
*/
encode: function encode(object, format) // <editor-fold defaultstate="collapsed">
{
return new this(object).encode(format);
},
// </editor-fold>
/**
* Decode container
*
* @memberOf GostKeys.ViPNetContainer
* @instance
* @param {FormatedData} container
* @returns {GostKeys.ViPNetContainer}
*/
decode: function decode(container) // <editor-fold defaultstate="collapsed">
{
if (typeof container === 'string') container = coding.Base64.decode(container);
container = buffer(container); // File type
var fileType = coding.Chars.encode(new Uint8Array(container, 0, 4), 'ascii');
if (fileType !== 'ITCS' && fileType !== 'PKEY' && fileType !== '_CCK' && fileType !== '_LCK') throw new Error('Unsupported ViPNet container type'); // File version
var fileVersion = get32(container, 4),
i = fileVersion >>> 16,
j = fileVersion & 0xffff;
if (i !== 0 && i !== 1 || j > 0xff) throw new Error('Unsupported ViPNet container version'); // File header
var headerSize = get32(container, 8),
applicationHeader;
if (headerSize > 0) applicationHeader = buffer(new Uint8Array(container, 12, headerSize)); // Read entries
var offset = 12 + headerSize,
entries = [];
while (offset < container.byteLength) {
// Entry size
var entrySize = get32(container, offset); // Decode entry
entries.push(ViPNetContainerEntry.decode(new Uint8Array(container, offset, entrySize + 4)));
offset = offset + entrySize + 4;
}
return new ViPNetContainer({
fileType: fileType,
fileVersion: fileVersion,
applicationHeader: applicationHeader,
entries: entries
});
} // </editor-fold>
});
/**
* A class for password-encrypted private keys in CryptoPro container
*
* @memberOf GostKeys
* @type GostKeys.SignalComPrivateKeyInfo
*/
GostKeys.prototype.ViPNetContainer = ViPNetContainer;
/**
* An implementation of PKCS #12 password encryption/integrity modes. Both input and output are implemented.<br><br>
*
* A PFX object may contain multiple authenticated safes (represented as GostASN1.SafeContents objects).
* Each authenticated safe may have its own encryption method, and contains a number of bags
* (represented as instances of GostASN1.SafeBag). <br>
* Note: the methods and constructors that input a PFX object do not automatically check the validity of the MAC.
* You need to explicitly call verify() to make this check.
*
* @class GostKeys.PKCS12
* @extends GostASN1.PFX
* @param {(FormatedData|GostASN1.PFX)} store
*/
function PKCS12(store) // <editor-fold defaultstate="collapsed">
{
asn1.PFX.call(this, store || {
version: 3,
authSafe: {
contentType: 'data'
}
});
} // </editor-fold>
extend(asn1.PFX, PKCS12, function () {
// <editor-fold defaultstate="collapsed">
function calcHMAC(derivation, password, content) {
var hmac = {
name: 'HMAC',
hash: derivation.hash
}; // Import password for key generation
return subtle.importKey('raw', passwordData(derivation, password), derivation, false, ['deriveKey']).then(function (passwordKey) {
// Generate key from password.
return subtle.deriveKey(derivation, passwordKey, hmac, false, ['sign']);
}).then(function (integrityKey) {
// Sign MAC
return subtle.sign(hmac, integrityKey, content);
});
}
function verifyHMAC(derivation, password, digest, content) {
return calcHMAC(derivation, password, content).then(function (test) {
if (!equalBuffers(digest, test)) throw new Error('Invalid password, MAC is not verified');
});
} // </editor-fold>
return {
/**
* Sign the enclosed content with given digest algorithm
*
* @memberOf GostKeys.PKCS12
* @instance
* @param {string} password The password
* @param {(AlgorithmIdentifier|string)} digestAlgorithm Digest algorithm or provider name
* @returns {Promise} Promise to return self object after enclose content
*/
sign: function sign(password, digestAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
// Calculate mac for password integrity
if (password) {
// Define digeset algorithm
var hash, derivation, digestProvider;
if (digestAlgorithm) digestProvider = providers[digestAlgorithm];else digestAlgorithm = providers[options.providerName].digest;
if (digestProvider) {
hash = digestProvider.digest;
derivation = digestProvider.derivation;
} else {
hash = digestAlgorithm;
derivation = {
name: 'PFXKDF',
hash: hash,
iterations: 2000
};
} // Add salt
derivation = expand(derivation, {
salt: getSeed(saltSize(hash)),
diversifier: 3
}); // Sign HMAC
var content = self.authSafe.content;
return calcHMAC(derivation, password, content).then(function (digest) {
self.macData = {
mac: {
digestAlgorithm: hash,
digest: digest
},
macSalt: derivation.salt,
iterations: derivation.iterations
};
return self;
});
} else return self;
});
},
// </editor-fold>
/**
* Verifies the MAC.
*
* @memberOf GostKeys.PKCS12
* @instance
* @param password The password for mac verification
* @returns {Promise} Promise to return self object after verification
*/
verify: function verify(password) // <editor-fold defaultstate="collapsed">
{
var self = this,
authSafe = self.authSafe,
derivation;
return new Promise(call).then(function () {
// Indirectly verification
if (authSafe.contentType === 'data') {
// Check MAC
if (self.macData) {
if (!password) throw new Error('Password must be defined for the MAC verification');
derivation = {
name: 'PFXKDF',
hash: self.macData.mac.digestAlgorithm,
salt: self.macData.macSalt,
iterations: self.macData.iterations,
diversifier: 3
};
var content = self.authSafe.content,
digest = self.macData.mac.digest; // Verify HMAC with PFXKDF (PKCS#12)
return verifyHMAC(derivation, password, digest, content)['catch'](function () {
// Verify HMAC with PBKDF2 (TC 26, PKCS#5)
derivation.name = 'PBKDF2';
return verifyHMAC(derivation, password, digest, content);
});
} // No check with MAC
} else throw new Error('Unsupported format');
}).then(function () {
return self;
});
} // </editor-fold>
};
}());
/**
* An implementation of PKCS #12 password encryption/integrity modes.
*
* @memberOf GostKeys
* @type GostKeys.PKCS12
*/
GostKeys.prototype.PKCS12 = PKCS12;
/**
* This type of entry holds a cryptographic PrivateKey, which is optionally stored
* in a protected format to prevent unauthorized access. It is also accompanied by
* a certificate chain for the corresponding public key.
*
* @class GostKeys.KeyEntry
* @property {(GostKeys.PKCS8|GostKeys.PKCS8Encrypted)} key The Private Key
* @property {GostCert.X509[]} certs The X.509 Certificates chain
* @property {GostCert.CRL[]} crls The X.509 CRLs for certificate chain
*/
/**
* This class represents a storage facility for cryptographic keys and certificates.
*
* @class GostKeys.KeyStore
* @param {Object} entries Object contains aliased {@link KeyEntry} objects
*/
function KeyStore(entries) // <editor-fold defaultstate="collapsed">
{
this.entries = {};
if (entries) for (var name in entries) {
this.setEntry(name, entries[name]);
}
} // </editor-fold>
extend(Object, KeyStore, {
/**
* Lists all the alias names of this keystore.
*
* @memberOf GostKeys.KeyStore
* @instance
* @returns {string[]}
*/
aliases: function aliases() // <editor-fold defaultstate="collapsed">
{
var result = [];
for (var name in this.entries) {
result.push(name);
}
return result;
},
// </editor-fold>
/**
* Checks if the given alias exists in this keystore.
*
* @memberOf GostKeys.KeyStore
* @instance
* @param {string} alias The alias name
* @returns {boolean} True if the alias exists, false otherwise
*/
containsAlias: function containsAlias(alias) // <editor-fold defaultstate="collapsed">
{
return !!this.entries[alias];
},
// </editor-fold>
/**
* Deletes the entry identified by the given alias from this keystore.
*
* @memberOf GostKeys.KeyStore
* @instance
* @param {string} alias The alias name
*/
deleteEntry: function deleteEntry(alias) // <editor-fold defaultstate="collapsed">
{
delete this.entries[alias];
},
// </editor-fold>
/**
* Saves a keystore Entry under the specified alias.
*
* @memberOf GostKeys.KeyStore
* @instance
* @param {string} alias The alias name
* @param {GostKeys.KeyEntry} entry The entry
*/
setEntry: function setEntry(alias, entry) // <editor-fold defaultstate="collapsed">
{
var r = {}; // Keys
if (entry.key) {
try {
r.key = new PKCS8(entry.key, true); // Private key
} catch (e) {
try {
r.key = new PKCS8Encrypted(entry.key, true); // Encrypted private key
} catch (e1) {
if (entry.key instanceof CryptoOperationData) r.key = entry.key; // Secret key
else throw new Error('Unknown Key format');
}
}
} // Certs
if (entry.certs) {
var certs = entry.certs instanceof Array ? entry.certs : [entry.certs];
for (var i = 0; i < certs.length; i++) {
try {
certs[i] = new cert.X509(certs[i]);
} catch (e) {}
}
r.certs = certs;
} // CRLs
if (entry.crls) {
var crls = entry.crls instanceof Array ? entry.crls : [entry.crls];
for (var i = 0; i < crls.length; i++) {
try {
crls[i] = new cert.CRL(crls[i]);
} catch (e) {}
}
r.crls = crls;
}
this.entries[alias] = r;
},
// </editor-fold>
/**
* Gets a keystore Entry for the specified alias
*
* @memberOf GostKeys.KeyStore
* @instance
* @param {string} alias The alias name
* @returns {GostKeys.KeyEntry} The entry
*/
getEntry: function getEntry(alias) // <editor-fold defaultstate="collapsed">
{
return this.entries[alias];
},
// </editor-fold>
/**
* Loads this KeyStore from the given input stream.<br><br>
* A password may be given to unlock the keystore (e.g. the keystore resides on a hardware token device),
* or to check the integrity of the keystore data. If a password is not given for integrity checking,
* then integrity checking is not performed.
*
* @memberOf GostKeys.KeyStore
* @instance
* @param {(FormatedData|GostKeys.PKSC12)} store The input stream from which the keystore is loaded
* @param {string} password The password used to check the integrity of the keystore, the password used to unlock the keystore
* @returns {Promise} Promise to return self object after store loaded
*/
load: function load(store, password) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
// Verify store file
store = new PKCS12(store);
return store.verify(password);
}).then(function () {
if (store.authSafe.contentType !== 'data') throw new Error('Unsupported PFX format');
var authSafe = asn1.AuthenticatedSafe.decode(store.authSafe.content).object,
promises = []; // Decrypt encrypted content
authSafe.forEach(function (info) {
if (info.contentType === 'data') promises.push(new cms.DataContentInfo(info));else if (info.contentType === 'encryptedData') promises.push(new cms.EncryptedDataContentInfo(info).getEnclosed(password));else throw new Error('Unsupported PFX format');
});
return Promise.all(promises);
}).then(function (contents) {
// Read bags
var entries = {};
contents.forEach(function (info) {
var bags = asn1.SafeContents.decode(info.content).object;
bags.forEach(function (bag) {
var keyId = coding.Hex.encode(bag.bagAttributes && bag.bagAttributes.localKeyId || getSeed(4), true),
entry = entries[keyId] || (entries[keyId] = {});
switch (bag.bagId) {
case 'keyBag':
entry.key = new PKCS8(bag.bagValue);
break;
case 'pkcs8ShroudedKeyBag':
entry.key = new PKCS8Encrypted(bag.bagValue);
break;
case 'secretBag':
if (bag.bagValue.secretTypeId === 'secret') entry.key = bag.bagValue.secretValue;
break;
case 'certBag':
var certs = entry.certs || (entry.certs = []);
if (bag.bagValue.certId === 'x509Certificate') certs.push(new cert.X509(bag.bagValue.certValue));
break;
case 'crlBag':
var crls = entry.crls || (entry.crls = []);
if (bag.bagValue.crlId === 'x509CRL') crls.push(new cert.CRL(bag.bagValue.crlValue));
break;
}
if (bag.bagAttributes && bag.bagAttributes.friendlyName) entry.friendlyName = bag.bagAttributes.friendlyName;
});
}); // Decrypt keys
var promises = [];
for (var name in entries) {
promises.push(function (entry) {
// Try to decrypt private key
if (entry.key instanceof PKCS8Encrypted) return entry.key.getKey(password).then(function (key) {
// Return entry with decrypted key
entry.key = key;
return entry;
})['catch'](function () {
// Return entry with encrypted key
return entry;
});else return entry;
}(entries[name]));
}
return Promise.all(promises);
}).then(function (entries) {
// Set alias names
entries.forEach(function (entry) {
var friendlyName = entry.friendlyName;
if (friendlyName) {
delete entry.friendlyName;
self.entries[friendlyName] = entry;
} else self.entries[generateUUID()] = entry;
});
return self;
});
},
// </editor-fold>
/**
* Stores this keystore to the given output stream, and protects its integrity with the given password.
*
* @memberOf GostKeys.KeyStore
* @instance
* @param {string} password The password to generate the keystore integrity check
* @param {string} digestAlgortihm The digest algorithm or provider name for integrity check
* @param {string} encryptionAlgortihm The encryption algorithm or provider name for encrypt certificates
* @returns {Promise} Promise to return {@link GostKeyst.PKCS12}
*/
store: function store(password, digestAlgortihm, encryptionAlgortihm) // <editor-fold defaultstate="collapsed">
{
var self = this,
keys = [],
contents = [],
authSafe = [];
return new Promise(call).then(function () {
// Define encryption algorithm
if (encryptionAlgortihm) encryptionAlgortihm = providers[encryptionAlgortihm] ? providers[encryptionAlgortihm].pbes : encryptionAlgortihm;else if (digestAlgortihm) encryptionAlgortihm = providers[digestAlgortihm] ? providers[digestAlgortihm].pbes : providers[options.providerName].pbes;else encryptionAlgortihm = providers[options.providerName].pbes; // Prepare keys and certs
var index = 1;
for (var name in self.entries) {
var keyId = new Uint32Array([index]),
entry = self.entries[name];
if (entry.key) {
(function (key, attributes) {
if (key instanceof CryptoOperationData) contents.push({
bagId: 'secretBag',
bagValue: {
secretTypeId: 'secret',
secretValue: key,
bagAttributes: attributes
}
});else if (key instanceof PKCS8) {
if (encryptionAlgortihm && password) keys.push(new PKCS8Encrypted().setKey(key, password, encryptionAlgortihm).then(function (encryptedKey) {
return {
bagId: 'pkcs8ShroudedKeyBag',
bagValue: encryptedKey,
bagAttributes: attributes
};
}));else keys.push({
bagId: 'keyBag',
bagValue: key,
bagAttributes: attributes
});
} else if (key instanceof PKCS8Encrypted) keys.push({
bagId: 'pkcs8ShroudedKeyBag',
bagValue: key,
bagAttributes: attributes
});
})(entry.key, {
localKeyId: keyId,
friendlyName: name
});
}
if (entry.certs) {
entry.certs.forEach(function (certificate) {
var attributes = {
localKeyId: keyId
};
if (certificate instanceof cert.X509) contents.push({
bagId: 'certBag',
bagValue: {
certId: 'x509Certificate',
certValue: certificate
},
bagAttributes: attributes
});
});
}
if (entry.crls) {
entry.crls.forEach(function (crl) {
var attributes = {
localKeyId: keyId
};
if (crl instanceof cert.CRL) contents.push({
bagId: 'crlBag',
bagValue: {
crlId: 'x509CRL',
crlValue: crl
},
bagAttributes: attributes
});
});
}
} // Encrypt keys
if (keys.length > 0) return Promise.all(keys);
}).then(function (bags) {
if (bags) {
var keyContents = asn1.SafeContents.encode(bags);
authSafe.push(new cms.DataContentInfo({
contentType: 'data',
content: keyContents
}));
} // Encrypt certificates and crls
if (contents.length > 0) {
contents = asn1.SafeContents.encode(contents);
if (encryptionAlgortihm && password) return new cms.EncryptedDataContentInfo().encloseContent(contents, password, encryptionAlgortihm);else return new cms.DataContentInfo().encloseContent(contents);
}
}).then(function (contents) {
authSafe.push(contents); // Set enclosed data
authSafe = new asn1.AuthenticatedSafe(authSafe);
var store = new PKCS12();
store.authSafe = {
contentType: 'data',
content: authSafe.encode()
}; // Return new PKCS12 with enclosed authenificated content
return store.sign(password, digestAlgortihm);
});
} // </editor-fold>
});
/**
* This class represents a storage facility for cryptographic keys and certificates.
*
* @memberOf GostKeys
* @type GostKeys.KeyStore
*/
GostKeys.prototype.KeyStore = KeyStore;
/**
* Implements the Key and Certificate Store methods
*
* @memberOf gostCrypto
* @type GostKeys
*/
gostCrypto.keys = new GostKeys();
return GostKeys;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostASN1":105,"./gostCMS":106,"./gostCert":107,"./gostCrypto":110}],114:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file Implementation Web Crypto random generatore for GOST algorithms
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory();
} else {
root.GostRandom = factory();
} // </editor-fold>
})(void 0, function () {
/**
* The gostCrypto provide general purpose cryptographic functionality for
* GOST standards including a cryptographically strong pseudo-random number
* generator seeded with truly random values.
*
* @Class GostRandom
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var rootCrypto = root.crypto || root.msCrypto;
var TypeMismatchError = root.TypeMismatchError || Error;
var QuotaExceededError = root.QuotaExceededError || Error; // Initialize mouse and time counters for random generator
var randomRing = {
seed: new Uint8Array(1024),
getIndex: 0,
setIndex: 0,
set: function set(x) {
if (this.setIndex >= 1024) this.setIndex = 0;
this.seed[this.setIndex++] = x;
},
get: function get() {
if (this.getIndex >= 1024) this.getIndex = 0;
return this.seed[this.getIndex++];
}
};
if (typeof document !== 'undefiend') {
try {
// Mouse move event to fill random array
document.addEventListener('mousemove', function (e) {
randomRing.set(new Date().getTime() & 255 ^ (e.clientX || e.pageX) & 255 ^ (e.clientY || e.pageY) & 255);
}, false);
} catch (e) {}
try {
// Keypress event to fill random array
document.addEventListener('keydown', function (e) {
randomRing.set(new Date().getTime() & 255 ^ e.keyCode & 255);
}, false);
} catch (e) {}
} // </editor-fold>
function GostRandom() {}
/**
* The getRandomValues method generates cryptographically random values. <br><br>
*
* Random generator based on JavaScript Web Crypto random genereator
* (if it is possible) or Math.random mixed with time and parameters of
* mouse and keyboard events
*
* @memberOf GostRandom
* @param {(ArrayBuffer|ArrayBufferView)} array Destination buffer for random data
*/
GostRandom.prototype.getRandomValues = function (array) // <editor-fold defaultstate="collapsed">
{
if (!array.byteLength) throw new TypeMismatchError('Array is not of an integer type (Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, or Uint32Array)');
if (array.byteLength > 65536) throw new QuotaExceededError('Byte length of array can\'t be greate then 65536');
var u8 = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
if (rootCrypto && rootCrypto.getRandomValues) {
// Native window cryptographic interface
rootCrypto.getRandomValues(u8);
} else {
// Standard Javascript method
for (var i = 0, n = u8.length; i < n; i++) {
u8[i] = Math.floor(256 * Math.random()) & 255;
}
} // Mix bio randomizator
for (var i = 0, n = u8.length; i < n; i++) {
u8[i] = u8[i] ^ randomRing.get();
}
return array;
}; // </editor-fold>
return GostRandom;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],115:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file GOST and common ASN.1 Object and Algorithm Identifiers
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostCrypto'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostCrypto'));
} else {
root.GostSecurity = factory(root.gostCrypto);
} // </editor-fold>
})(void 0, function (gostCrypto) {
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this; // Expand javascript object
function expand() {
var r = {};
for (var i = 0, n = arguments.length; i < n; i++) {
var item = arguments[i];
if (_typeof(item) === 'object') for (var name in item) {
r[name] = item[name];
}
}
return r;
} // </editor-fold>
/**
* Freandly names for ASN.1 Object Identifiers
*
* @field names
* @memberOf GostSecurity
*/
// <editor-fold defaultstate="collapsed">
var names = {
// CryptoPro algoritms
'1.2.643.2.2': 'CryptoPro',
'1.2.643.2.2.3': 'id-GostR3411-94-with-GostR3410-2001',
'1.2.643.2.2.4': 'id-GostR3411-94-with-GostR3410-94',
'1.2.643.2.2.9': 'id-GostR3411-94',
'1.2.643.2.2.10': 'id-HMACGostR3411-94',
'1.2.643.2.2.13.0': 'id-Gost28147-89-None-KeyWrap',
'1.2.643.2.2.13.1': 'id-Gost28147-89-CryptoPro-KeyWrap',
'1.2.643.2.2.14.0': 'id-Gost28147-89-None-KeyMeshing',
'1.2.643.2.2.14.1': 'id-Gost28147-89-CryptoPro-KeyMeshing',
'1.2.643.2.2.19': 'id-GostR3410-2001',
'1.2.643.2.2.20': 'id-GostR3410-94',
'1.2.643.2.2.20.1': 'id-GostR3410-94-a',
'1.2.643.2.2.20.2': 'id-GostR3410-94-aBis',
'1.2.643.2.2.20.3': 'id-GostR3410-94-b',
'1.2.643.2.2.20.4': 'id-GostR3410-94-bBis',
'1.2.643.2.2.21': 'id-Gost28147-89',
'1.2.643.2.2.22': 'id-Gost28147-89-MAC',
'1.2.643.2.2.30.0': 'id-GostR3411-94-TestParamSet',
'1.2.643.2.2.30.1': 'id-GostR3411-94-CryptoProParamSet',
'1.2.643.2.2.30.2': 'id-GostR3411-94-CryptoPro-B-ParamSet',
'1.2.643.2.2.30.3': 'id-GostR3411-94-CryptoPro-C-ParamSet',
'1.2.643.2.2.30.4': 'id-GostR3411-94-CryptoPro-D-ParamSet',
'1.2.643.2.2.31.0': 'id-Gost28147-89-TestParamSet',
'1.2.643.2.2.31.1': 'id-Gost28147-89-CryptoPro-A-ParamSet',
'1.2.643.2.2.31.2': 'id-Gost28147-89-CryptoPro-B-ParamSet',
'1.2.643.2.2.31.3': 'id-Gost28147-89-CryptoPro-C-ParamSet',
'1.2.643.2.2.31.4': 'id-Gost28147-89-CryptoPro-D-ParamSet',
'1.2.643.2.2.31.5': 'id-Gost28147-89-CryptoPro-Oscar-1-1-ParamSet',
'1.2.643.2.2.31.6': 'id-Gost28147-89-CryptoPro-Oscar-1-0-ParamSet',
'1.2.643.2.2.31.7': 'id-Gost28147-89-CryptoPro-RIC-1-ParamSet ',
'1.2.643.2.2.31.12': 'id-Gost28147-89-CryptoPro-tc26-1',
'1.2.643.2.2.31.13': 'id-Gost28147-89-CryptoPro-tc26-2',
'1.2.643.2.2.31.14': 'id-Gost28147-89-CryptoPro-tc26-3',
'1.2.643.2.2.31.15': 'id-Gost28147-89-CryptoPro-tc26-4',
'1.2.643.2.2.31.16': 'id-Gost28147-89-CryptoPro-tc26-5',
'1.2.643.2.2.31.17': 'id-Gost28147-89-CryptoPro-tc26-6',
'1.2.643.2.2.32.0': 'id-GostR3410-94-TestParamSet',
'1.2.643.2.2.32.2': 'id-GostR3410-94-CryptoPro-A-ParamSet',
'1.2.643.2.2.32.3': 'id-GostR3410-94-CryptoPro-B-ParamSet',
'1.2.643.2.2.32.4': 'id-GostR3410-94-CryptoPro-C-ParamSet',
'1.2.643.2.2.32.5': 'id-GostR3410-94-CryptoPro-D-ParamSet',
'1.2.643.2.2.33.1': 'id-GostR3410-94-CryptoPro-XchA-ParamSet',
'1.2.643.2.2.33.2': 'id-GostR3410-94-CryptoPro-XchB-ParamSet',
'1.2.643.2.2.33.3': 'id-GostR3410-94-CryptoPro-XchC-ParamSet',
// Certificate center attributes
'1.2.643.2.2.34.2': 'temporaryAccessToRC',
'1.2.643.2.2.34.3': 'internetContentSignature',
'1.2.643.2.2.34.4': 'adminRC',
'1.2.643.2.2.34.5': 'operatorRC',
'1.2.643.2.2.34.6': 'userRC',
'1.2.643.2.2.34.7': 'clientRC',
'1.2.643.2.2.34.8': 'serverRC',
'1.2.643.2.2.34.9': 'sysAdminRC',
'1.2.643.2.2.34.10': 'arcAdminRC',
'1.2.643.2.2.34.11': 'authorityPersonRC',
'1.2.643.2.2.34.12': 'clientCC',
'1.2.643.2.2.34.13': 'sysAdminCC',
'1.2.643.2.2.34.14': 'arcAdminCC',
'1.2.643.2.2.34.15': 'accessIPSecCA',
'1.2.643.2.2.34.16': 'auditAdminHSM',
'1.2.643.2.2.34.21': 'adminHSM',
'1.2.643.2.2.34.22': 'serverAdminHSH',
'1.2.643.2.2.34.24': 'winlogonCA',
'1.2.643.2.2.34.25': 'timestampServiceUser',
'1.2.643.2.2.34.26': 'statusServiceUser',
'1.2.643.2.2.34.27': 'arcAdminHSM',
'1.2.643.2.2.34.28': 'auditorHSM',
// CryptoPro algoritms
'1.2.643.2.2.35.0': 'id-GostR3410-2001-CryptoPro-TestParamSet',
'1.2.643.2.2.35.1': 'id-GostR3410-2001-CryptoPro-A-ParamSet',
'1.2.643.2.2.35.2': 'id-GostR3410-2001-CryptoPro-B-ParamSet',
'1.2.643.2.2.35.3': 'id-GostR3410-2001-CryptoPro-C-ParamSet',
'1.2.643.2.2.36.0': 'id-GostR3410-2001-CryptoPro-XchA-ParamSet',
'1.2.643.2.2.36.1': 'id-GostR3410-2001-CryptoPro-XchB-ParamSet',
"1.2.643.2.2.37.1": 'id-CryptoPro-GostPrivateKeys-V1',
"1.2.643.2.2.37.2": 'id-CryptoPro-GostPrivateKeys-V2',
"1.2.643.2.2.37.2.1": 'id-CryptoPro-GostPrivateKeys-V2-Full',
"1.2.643.2.2.37.2.2": 'id-CryptoPro-GostPrivateKeys-V2-PartOf',
'1.2.643.2.2.37.3.1': 'intermediateCertificates',
'1.2.643.2.2.37.3.2': 'trustedCertificatesSignature',
'1.2.643.2.2.37.3.3': 'trustedCertificatesExchange',
'1.2.643.2.2.37.3.10': 'keyValidity',
'1.2.643.2.2.38.1': 'personalBaseProlicy',
'1.2.643.2.2.38.2': 'networkBasePolicy',
'1.2.643.2.2.47.1': 'id-CryptoPro-ocsp-treats-exp-key-or-exp-cert-rev',
'1.2.643.2.2.47.2': 'id-CryptoPro-ocsp-crl-locator',
'1.2.643.2.2.47.3': 'id-CryptoPro-ocsp-instant-revocation-indicator',
'1.2.643.2.2.47.4': 'id-CryptoPro-ocsp-revocation-announcement-reference',
'1.2.643.2.2.47.5': 'id-CryptoPro-ocsp-historical-request',
'1.2.643.2.2.49.2': 'limitedLicense',
'1.2.643.2.2.96': 'id-GostR3410-2001-CryptoPro-ESDH',
'1.2.643.2.2.97': 'id-GostR3410-94-CryptoPro-ESDH',
'1.2.643.2.2.98': 'id-GostR3410-2001DH',
'1.2.643.2.2.99': 'id-GostR3410-94DH',
// signature attributes
'1.2.643.2.45.1.1.1': 'signatureComment',
'1.2.643.2.45.1.1.2': 'resourceName',
'1.2.643.2.45.1.1.3': 'signatureUsage',
// params
'1.2.643.3.131.1.1': 'INN',
'1.2.643.3.141.1.1': 'RNS FSS',
'1.2.643.3.141.1.2': 'KP FSS',
// tc26
'1.2.643.7.1': 'tc26',
'1.2.643.7.1.1.1.1': 'id-tc26-gost3410-12-256',
'1.2.643.7.1.1.1.2': 'id-tc26-gost3410-12-512',
'1.2.643.7.1.1.2.1': 'id-tc26-gost3411-94',
'1.2.643.7.1.1.2.2': 'id-tc26-gost3411-12-256',
'1.2.643.7.1.1.2.3': 'id-tc26-gost3411-12-512',
'1.2.643.7.1.1.3.1': 'id-tc26-signwithdigest-gost3410-12-94',
'1.2.643.7.1.1.3.2': 'id-tc26-signwithdigest-gost3410-12-256',
'1.2.643.7.1.1.3.3': 'id-tc26-signwithdigest-gost3410-12-512',
'1.2.643.7.1.1.4.1': 'id-tc26-hmac-gost-3411-12-256',
'1.2.643.7.1.1.4.2': 'id-tc26-hmac-gost-3411-12-512',
'1.2.643.7.1.1.6.1': 'id-tc26-agreement-gost-3410-12-256',
'1.2.643.7.1.1.6.2': 'id-tc26-agreement-gost-3410-12-512',
'1.2.643.7.1.2.1.1.0': 'id-tc26-gost-3410-12-256-paramSetTest',
'1.2.643.7.1.2.1.1.1': 'id-tc26-gost-3410-12-256-paramSetA',
'1.2.643.7.1.2.1.1.2': 'id-tc26-gost-3410-12-256-paramSetB',
'1.2.643.7.1.2.1.2.0': 'id-tc26-gost-3410-12-512-paramSetTest',
'1.2.643.7.1.2.1.2.1': 'id-tc26-gost-3410-12-512-paramSetA',
'1.2.643.7.1.2.1.2.2': 'id-tc26-gost-3410-12-512-paramSetB',
'1.2.643.7.1.2.1.2.3': 'id-tc26-gost-3410-12-512-paramSetC',
'1.2.643.7.1.2.1.2.4': 'id-tc26-gost-3410-12-512-paramSetD',
'1.2.643.7.1.2.5.1.1': 'id-tc26-gost-28147-param-Z',
// GOST Parameters
'1.2.643.100.1': 'OGRN',
'1.2.643.100.2.1': 'SMEV-person',
'1.2.643.100.2.2': 'SMEV-government',
'1.2.643.100.3': 'SNILS',
'1.2.643.100.4': 'KPP',
'1.2.643.100.5': 'OGRNIP',
'1.2.643.100.6': 'internal-government',
'1.2.643.100.111': 'subjectSignTool',
'1.2.643.100.112': 'issuerSignTool',
'1.2.643.100.113.1': 'signToolClassKC1',
'1.2.643.100.113.2': 'signToolClassKC2',
'1.2.643.100.113.3': 'signToolClassKC3',
'1.2.643.100.113.4': 'signToolClassKB1',
'1.2.643.100.113.5': 'signToolClassKB2',
'1.2.643.100.113.6': 'signToolClassKA1',
'1.2.643.100.114.1': 'issuerToolClassKC1',
'1.2.643.100.114.2': 'issuerToolClassKC2',
'1.2.643.100.114.3': 'issuerToolClassKC3',
'1.2.643.100.114.4': 'issuerToolClassKB2',
'1.2.643.100.114.5': 'issuerToolClassKB1',
'1.2.643.100.114.6': 'issuerToolClassKA1',
// Common algorithms
'1.2.840.10040.4': 'x9cm',
'1.2.840.10040.4.1': 'dsa',
'1.2.840.10040.4.3': 'dsa-with-SHA1',
'1.2.840.10045': 'ansi-x962',
'1.2.840.10045.1': 'id-fieldType',
'1.2.840.10045.1.1': 'id-prime-Field',
'1.2.840.10045.1.2': 'id-characteristic-two-field',
'1.2.840.10045.2.1': 'ecPublicKey',
'1.2.840.10045.3.0': 'characteristicTwo',
'1.2.840.10045.3.1.1': 'secp192r1',
'1.2.840.10045.3.1.2': 'prime192v2',
'1.2.840.10045.3.1.3': 'prime192v3',
'1.2.840.10045.3.1.4': 'prime239v1',
'1.2.840.10045.3.1.5': 'prime239v2',
'1.2.840.10045.3.1.6': 'prime239v3',
'1.2.840.10045.3.1.7': 'secp256r1',
'1.2.840.10045.4': 'ecdsa',
'1.2.840.10045.4.1': 'ecdsa-with-SHA1',
'1.2.840.10045.4.2': 'ecdsa-with-Recommended',
'1.2.840.10045.4.4': 'ecdsa-with-SHA2',
'1.2.840.10045.4.4.1': 'ecdsa-with-SHA224',
'1.2.840.10045.4.4.2': 'ecdsa-with-SHA256',
'1.2.840.10045.4.4.3': 'ecdsa-with-SHA384',
'1.2.840.10045.4.4.4': 'ecdsa-with-SHA512',
'1.2.840.113533.7.66.13': 'PasswordBasedMac',
'1.3.6.1.4.1.22554.1.1.2.1.2': 'pbeWithSHAAndAES128-CBC',
'1.3.6.1.4.1.22554.1.1.2.1.22': 'pbeWithSHAAndAES192-CBC',
'1.3.6.1.4.1.22554.1.1.2.1.42': 'pbeWithSHAAndAES256-CBC',
'1.3.6.1.4.1.22554.1.2.1.2.1.2': 'pbeWithSHA256AndAES128-CBC',
'1.3.6.1.4.1.22554.1.2.1.2.1.22': 'pbeWithSHA256AndAES192-CBC',
'1.3.6.1.4.1.22554.1.2.1.2.1.42': 'pbeWithSHA256AndAES256-CBC',
// Diffie-Hellman Key Exchange Keys
'1.2.840.113549': 'rsa',
'1.2.840.113549.1.1.1': 'rsaEncryption',
'1.2.840.113549.1.1.2': 'md2withRSAEncryption',
'1.2.840.113549.1.1.3': 'md4withRSAEncryption',
'1.2.840.113549.1.1.4': 'md5withRSAEncryption',
'1.2.840.113549.1.1.5': 'sha1withRSAEncryption',
'1.2.840.113549.1.1.7': 'rsaes-oaep',
'1.2.840.113549.1.1.8': 'mgf1',
'1.2.840.113549.1.1.9': 'pSpecified',
'1.2.840.113549.1.1.10': 'rsassa-pss',
'1.2.840.113549.1.1.11': 'sha256withRSAEncryption',
'1.2.840.113549.1.1.12': 'sha384withRSAEncryption',
'1.2.840.113549.1.1.13': 'sha512withRSAEncryption',
'1.2.840.113549.1.2.7': 'hmacWithSHA1',
'1.2.840.113549.1.2.8': 'hmacWithSHA224',
'1.2.840.113549.1.2.9': 'hmacWithSHA256',
'1.2.840.113549.1.2.10': 'hmacWithSHA384',
'1.2.840.113549.1.2.11': 'hmacWithSHA512',
'1.2.840.113549.1.3.1': 'dhKeyAgreement',
// pkcs#7 content types
'1.2.840.113549.1.5.12': 'PBKDF2',
'1.2.840.113549.1.5.13': 'PBES2',
'1.2.840.113549.1.5.14': 'PBMAC1',
'1.2.840.113549.1.7.1': 'data',
'1.2.840.113549.1.7.2': 'signedData',
'1.2.840.113549.1.7.3': 'envelopedData',
'1.2.840.113549.1.7.4': 'signedAndEnvelopedData',
'1.2.840.113549.1.7.5': 'digestedData',
'1.2.840.113549.1.7.6': 'encryptedData',
'1.2.840.113549.1.9.1': 'emailAddress',
'1.2.840.113549.1.9.2': 'unstructuredName',
'1.2.840.113549.1.9.3': 'contentType',
'1.2.840.113549.1.9.4': 'messageDigest',
'1.2.840.113549.1.9.5': 'signingTime',
'1.2.840.113549.1.9.6': 'countersignature',
'1.2.840.113549.1.9.7': 'challengePassword',
'1.2.840.113549.1.9.8': 'unstructuredAddress',
'1.2.840.113549.1.9.9': 'extendedCertificateAttributes',
'1.2.840.113549.1.9.10': 'issuerAndSerialNumber',
'1.2.840.113549.1.9.11': 'passwordCheck',
'1.2.840.113549.1.9.12': 'publicKey',
'1.2.840.113549.1.9.13': 'signingDescription',
'1.2.840.113549.1.9.14': 'extensionRequest',
'1.2.840.113549.1.9.15': 'sMimeCapabilities',
'1.2.840.113549.1.9.16': 'sMimeObjectIdentifierRegistry',
'1.2.840.113549.1.9.16.1.2': 'authData',
'1.2.840.113549.1.9.16.1.4 ': 'timestampToken',
'1.2.840.113549.1.9.16.1.17 ': 'firmwareLoadReceipt',
'1.2.840.113549.1.9.16.1.21': 'encKeyWithID',
'1.2.840.113549.1.9.16.1.23': 'authEnvelopedData',
'1.2.840.113549.1.9.16.2': 'sMimeAttributes',
'1.2.840.113549.1.9.16.2.1': 'receiptRequest',
'1.2.840.113549.1.9.16.2.12': 'signingCertificate',
'1.2.840.113549.1.9.16.2.14': 'timeStampToken',
'1.2.840.113549.1.9.16.2.2': 'securityLabel',
'1.2.840.113549.1.9.16.2.3': 'mlExpansionHistory',
'1.2.840.113549.1.9.16.2.34': 'unsignedData',
'1.2.840.113549.1.9.16.2.47': 'signingCertificateV2',
'1.2.840.113549.1.9.16.3.5': 'ESDH',
// pkcs#9 oids
'1.2.840.113549.1.9.20': 'friendlyName',
'1.2.840.113549.1.9.21': 'localKeyId',
'1.2.840.113549.1.9.22': 'certTypes',
'1.2.840.113549.1.9.22.1': 'x509Certificate',
'1.2.840.113549.1.9.22.2': 'sdsiCertificate',
'1.2.840.113549.1.9.23': 'crlTypes',
'1.2.840.113549.1.9.23.1': 'x509CRL',
'1.2.840.113549.1.9.24': 'secretTypes',
'1.2.840.113549.1.9.24.1': 'secret',
'1.2.840.113549.1.9.25.1': 'pkcs15Token',
'1.2.840.113549.1.9.25.2': 'encryptedPrivateKeyInfo',
'1.2.840.113549.1.9.25.3': 'randomNonce',
'1.2.840.113549.1.9.25.4': 'sequenceNumber',
'1.2.840.113549.1.9.25.5': 'pkcs7PDU',
'1.2.840.113549.1.9.26.1': 'pkcs9String',
'1.2.840.113549.1.9.26.2': 'signingTimeString',
'1.2.840.113549.1.9.27.1': 'caseIgnoreMatch',
'1.2.840.113549.1.9.27.2': 'signingTimeMatch',
// password-based-encryption for pkcs#12
'1.2.840.113549.1.12.0.1': 'pkcs-12',
'1.2.840.113549.1.12.1': 'pbe',
'1.2.840.113549.1.12.1.1': 'pbeWithSHAAnd128BitRC4',
'1.2.840.113549.1.12.1.2': 'pbeWithSHAAnd40BitRC4',
'1.2.840.113549.1.12.1.3': 'pbeWithSHAAnd3-KeyTripleDES-CBC',
'1.2.840.113549.1.12.1.4': 'pbeWithSHAAnd2-KeyTripleDES-CBC',
'1.2.840.113549.1.12.1.5': 'pbeWithSHAAnd128BitRC2-CBC',
'1.2.840.113549.1.12.1.6': 'pbeWithSHAAnd40BitRC2-CBC',
'1.2.840.113549.1.12.1.80': 'pbeUnknownGost',
'1.2.840.113549.1.12.2.1': 'pkcs8-key-shrouding',
'1.2.840.113549.1.12.3.1': 'keyBagId',
'1.2.840.113549.1.12.3.2': 'certAndCRLBagId',
'1.2.840.113549.1.12.3.3': 'secretBagId',
'1.2.840.113549.1.12.3.4': 'safeContentsId',
'1.2.840.113549.1.12.3.5': 'pkcs-8ShroudedKeyBagId',
'1.2.840.113549.1.12.4.1': 'x509CertCRLBagId',
'1.2.840.113549.1.12.4.2': 'pkcs-12-SDSICertBag',
// pkcs#12 safe bags
'1.2.840.113549.1.12.10.1.1': 'keyBag',
'1.2.840.113549.1.12.10.1.2': 'pkcs8ShroudedKeyBag',
'1.2.840.113549.1.12.10.1.3': 'certBag',
'1.2.840.113549.1.12.10.1.4': 'crlBag',
'1.2.840.113549.1.12.10.1.5': 'secretBag',
'1.2.840.113549.1.12.10.1.6': 'safeContentsBag',
// hash algorithm
'1.2.840.113549.2.5': 'md-5',
// symmetric key algorithm oids
'1.2.840.113549.3.7': 'des-EDE3-CBC',
// additional algorithms
'1.3.132.0.34': 'secp384r1',
'1.3.132.0.35': 'secp521r1',
'1.3.132.112': 'ecDH',
'1.3.14.3.2.26': 'sha1',
'1.3.6.1.4.1.311.2.1.14': 'msCertExtensions',
'1.3.6.1.4.1.311.17.1': 'keyProviderNameAttr',
'1.3.6.1.4.1.311.17.2': 'localMachineKeyset',
'1.3.6.1.4.1.311.17.3.20': 'certKeyIdentifierPropId',
// SignalCom algorithms
'1.3.6.1.4.1.5849': 'SignalCom',
'1.3.6.1.4.1.5849.1.1.1': 'id-sc-gost28147-ecb',
'1.3.6.1.4.1.5849.1.1.2': 'id-sc-gost28147-gamma',
'1.3.6.1.4.1.5849.1.1.3': 'id-sc-gost28147-gfb',
'1.3.6.1.4.1.5849.1.1.4': 'id-sc-gost28147-mac',
'1.3.6.1.4.1.5849.1.1.5': 'id-sc-gostR3410-94',
'1.3.6.1.4.1.5849.1.1.6.1.1.1': 'id-sc-gostR3410-94-default',
'1.3.6.1.4.1.5849.1.1.6.1.1.2': 'id-sc-gostR3410-94-test',
'1.3.6.1.4.1.5849.1.2.1': 'id-sc-gostR3411-94',
'1.3.6.1.4.1.5849.1.3.1': 'id-sc-gostR3411-94-with-gostR3410-94',
'1.3.6.1.4.1.5849.1.3.2': 'id-sc-gostR3411-94-with-gostR3410-2001',
'1.3.6.1.4.1.5849.1.4.1': 'id-sc-cmsGostWrap',
'1.3.6.1.4.1.5849.1.4.2': 'id-sc-cmsGost28147Wrap',
'1.3.6.1.4.1.5849.1.5.1': 'id-sc-pbeWithGost3411AndGost28147',
'1.3.6.1.4.1.5849.1.5.2': 'id-sc-pbeWithGost3411AndGost28147CFB',
'1.3.6.1.4.1.5849.1.6.2': 'id-sc-gostR3410-2001',
'1.3.6.1.4.1.5849.1.7.2': 'id-sc-hmacWithGostR3411',
'1.3.6.1.4.1.5849.1.8.1': 'id-sc-r3410-ESDH-r3411kdf',
'1.3.6.1.4.1.5849.1.8.3': 'id-sc-ecdh-singlePass-cofactor-r3411kdf',
'1.3.6.1.4.1.5849.2.2.1': 'id-sc-gostR3410-2001-publicKey',
// additinal data
'1.3.6.1.5.5.7.0.12': 'attribute-cert',
'1.3.6.1.5.5.7.1.1': 'authorityInfoAccess',
'1.3.6.1.5.5.7.1.4': 'auditIdentity',
'1.3.6.1.5.5.7.1.6': 'aaControls',
'1.3.6.1.5.5.7.1.10': 'ac-proxying',
'1.3.6.1.5.5.7.1.11': 'subjectInfoAccess',
'1.3.6.1.5.5.7.3.1': 'serverAuth',
'1.3.6.1.5.5.7.3.2': 'clientAuth',
'1.3.6.1.5.5.7.3.3': 'codeSigning',
'1.3.6.1.5.5.7.3.4': 'emailProtection',
'1.3.6.1.5.5.7.3.5': 'ipsecEndSystem',
'1.3.6.1.5.5.7.3.6': 'ipsecTunnel',
'1.3.6.1.5.5.7.3.7': 'ipsecUser',
'1.3.6.1.5.5.7.3.8': 'timeStamping',
'1.3.6.1.5.5.7.3.9': 'OCSPSigning',
'1.3.6.1.5.5.7.5.1': 'regCtrl',
'1.3.6.1.5.5.7.5.1.1': 'regToken',
'1.3.6.1.5.5.7.5.1.2': 'authenticator',
'1.3.6.1.5.5.7.5.1.3': 'pkiPublicationInfo',
'1.3.6.1.5.5.7.5.1.4': 'pkiArchiveOptions',
'1.3.6.1.5.5.7.5.1.5': 'oldCertID',
'1.3.6.1.5.5.7.5.1.6': 'protocolEncrKey',
'1.3.6.1.5.5.7.5.2': 'regInfoAttr',
'1.3.6.1.5.5.7.5.2.1': 'UTF8Pairs',
'1.3.6.1.5.5.7.5.2.2': 'certReq',
'1.3.6.1.5.5.7.6.2': 'noSignature',
'1.3.6.1.5.5.7.7.1': 'statusInfo',
'1.3.6.1.5.5.7.7.2': 'identification',
'1.3.6.1.5.5.7.7.3': 'identityProof',
'1.3.6.1.5.5.7.7.4': 'dataReturn',
'1.3.6.1.5.5.7.7.5': 'transactionId',
'1.3.6.1.5.5.7.7.6': 'senderNonce',
'1.3.6.1.5.5.7.7.7': 'recipientNonce',
'1.3.6.1.5.5.7.7.8': 'addExtensions',
'1.3.6.1.5.5.7.7.9': 'encryptedPOP',
'1.3.6.1.5.5.7.7.10': 'decryptedPOP',
'1.3.6.1.5.5.7.7.11': 'lraPOPWitness',
'1.3.6.1.5.5.7.7.15': 'getCert',
'1.3.6.1.5.5.7.7.16': 'getCRL',
'1.3.6.1.5.5.7.7.17': 'revokeRequest',
'1.3.6.1.5.5.7.7.18': 'regInfo',
'1.3.6.1.5.5.7.7.19': 'responseInfo',
'1.3.6.1.5.5.7.7.21': 'queryPending',
'1.3.6.1.5.5.7.7.22': 'popLinkRandom',
'1.3.6.1.5.5.7.7.23': 'popLinkWitness',
'1.3.6.1.5.5.7.7.24': 'confirmCertAcceptance',
'1.3.6.1.5.5.7.7.25': 'statusInfoV2',
'1.3.6.1.5.5.7.7.26': 'trustedAnchors',
'1.3.6.1.5.5.7.7.27': 'authPublish',
'1.3.6.1.5.5.7.7.28': 'batchRequests',
'1.3.6.1.5.5.7.7.29': 'batchResponses',
'1.3.6.1.5.5.7.7.30': 'publishCert',
'1.3.6.1.5.5.7.7.31': 'modCertTemplate',
'1.3.6.1.5.5.7.7.32': 'controlProcessed',
'1.3.6.1.5.5.7.7.33': 'popLinkWitnessV2',
'1.3.6.1.5.5.7.7.34': 'identityProofV2',
'1.3.6.1.5.5.7.9.1': 'dateOfBirth',
'1.3.6.1.5.5.7.9.2': 'placeOfBirth',
'1.3.6.1.5.5.7.9.3': 'gender',
'1.3.6.1.5.5.7.9.4': 'countryOfCitizenship',
'1.3.6.1.5.5.7.9.5': 'countryOfResidence',
'1.3.6.1.5.5.7.10.1': 'authenticationInfo',
'1.3.6.1.5.5.7.10.2': 'accessIdentity',
'1.3.6.1.5.5.7.10.3': 'chargingIdentity',
'1.3.6.1.5.5.7.10.4': 'group',
'1.3.6.1.5.5.7.10.6': 'encAttrs',
'1.3.6.1.5.5.7.12.2': 'PKIData',
'1.3.6.1.5.5.7.12.3': 'PKIResponse',
'1.3.6.1.5.5.7.48.1.1': 'ocsp-basic',
'1.3.6.1.5.5.7.48.1.2': 'ocsp-nonce',
'1.3.6.1.5.5.7.48.1.3': 'ocsp-crl',
'1.3.6.1.5.5.7.48.1.4': 'ocsp-response',
'1.3.6.1.5.5.7.48.1.5': 'ocsp-nocheck',
'1.3.6.1.5.5.7.48.1.6': 'ocsp-archive-cutoff',
'1.3.6.1.5.5.7.48.1.7': 'ocsp-service-locator',
// Key packages
'2.16.840.1.101.2.1.2.78.2': 'encryptedKeyPkg',
'2.16.840.1.101.2.1.2.78.3': 'keyPackageReceipt',
'2.16.840.1.101.2.1.2.78.5': 'aKeyPackage',
'2.16.840.1.101.2.1.2.78.6': 'keyPackageError',
// symmetric key algorithm oids
'2.16.840.1.101.3.4': 'nistAlgorithms',
'2.16.840.1.101.3.4.1': 'aes',
'2.16.840.1.101.3.4.1.1': 'aes128-ECB',
'2.16.840.1.101.3.4.1.2': 'aes128-CBC',
'2.16.840.1.101.3.4.1.3': 'aes128-OFB',
'2.16.840.1.101.3.4.1.4': 'aes128-CFB',
'2.16.840.1.101.3.4.1.5': 'aes128-wrap',
'2.16.840.1.101.3.4.1.6': 'aes128-GCM',
'2.16.840.1.101.3.4.1.7': 'aes128-CCM',
'2.16.840.1.101.3.4.1.8': 'aes128-wrap-pad',
'2.16.840.1.101.3.4.1.21': 'aes192-ECB',
'2.16.840.1.101.3.4.1.22': 'aes192-CBC',
'2.16.840.1.101.3.4.1.23': 'aes192-OFB',
'2.16.840.1.101.3.4.1.24': 'aes192-CFB',
'2.16.840.1.101.3.4.1.25': 'aes192-wrap',
'2.16.840.1.101.3.4.1.26': 'aes192-GCM',
'2.16.840.1.101.3.4.1.27': 'aes192-CCM',
'2.16.840.1.101.3.4.1.28': 'aes192-wrap-pad',
'2.16.840.1.101.3.4.1.41': 'aes256-ECB',
'2.16.840.1.101.3.4.1.42': 'aes256-CBC',
'2.16.840.1.101.3.4.1.43': 'aes256-OFB',
'2.16.840.1.101.3.4.1.44': 'aes256-CFB',
'2.16.840.1.101.3.4.1.45': 'aes256-wrap',
'2.16.840.1.101.3.4.1.46': 'aes256-GCM',
'2.16.840.1.101.3.4.1.47': 'aes256-CCM',
'2.16.840.1.101.3.4.1.48': 'aes256-wrap-pad',
// hash algorihtms
'2.16.840.1.101.3.4.2.1': 'sha256',
'2.16.840.1.101.3.4.2.2': 'sha384',
'2.16.840.1.101.3.4.2.3': 'sha512',
// pkcs12
'2.16.840.1.113730.3.1.216': 'userPKCS12',
// certificate issuer/subject OIDsets
'2.5.1.5.55': 'clearance',
'2.5.4.0': 'objectClass',
'2.5.4.1': 'aliasedEntryName',
'2.5.4.2': 'knowldgeinformation',
'2.5.4.3': 'commonName',
'2.5.4.4': 'surName',
'2.5.4.5': 'serialName',
'2.5.4.6': 'countryName',
'2.5.4.7': 'localityName',
'2.5.4.8': 'stateOrProvinceName',
'2.5.4.9': 'streetAddress',
'2.5.4.10': 'organizationName',
'2.5.4.11': 'organizationalUnitName',
'2.5.4.12': 'title',
'2.5.4.13': 'description',
'2.5.4.14': 'searchGuide',
'2.5.4.15': 'businessCategory',
'2.5.4.16': 'postalAddress',
'2.5.4.17': 'postalCode',
'2.5.4.18': 'postOfficeBox',
'2.5.4.19': 'physicalDeliveryOfficeName',
'2.5.4.20': 'telephoneNumber',
'2.5.4.21': 'telexNumber',
'2.5.4.22': 'teletexTerminalIdentifier',
'2.5.4.23': 'facsimileTelephoneNumber',
'2.5.4.24': 'x121Address',
'2.5.4.25': 'internationalISDNNumber',
'2.5.4.26': 'registeredAddress',
'2.5.4.27': 'destinationIndicator',
'2.5.4.28': 'preferredDeliveryMethod',
'2.5.4.29': 'presentationAddress',
'2.5.4.30': 'supportedApplicationContext',
'2.5.4.31': 'member',
'2.5.4.32': 'owner',
'2.5.4.33': 'roleOccupant',
'2.5.4.34': 'seeAlso',
'2.5.4.35': 'userPassword',
'2.5.4.36': 'userCertificate',
'2.5.4.37': 'cACertificate',
'2.5.4.38': 'authorityRevocationList',
'2.5.4.39': 'certificateRevocationList',
'2.5.4.40': 'crossCertificatePair',
'2.5.4.41': 'name',
'2.5.4.42': 'givenName',
'2.5.4.43': 'initials',
'2.5.4.44': 'generationQualifier',
'2.5.4.45': 'uniqueIdentifier',
'2.5.4.46': 'dnQualifier',
'2.5.4.47': 'enhancedSearchGuide',
'2.5.4.48': 'protocolInformation',
'2.5.4.49': 'distinguishedName',
'2.5.4.50': 'uniqueMember',
'2.5.4.51': 'houseIdentifier',
'2.5.4.52': 'supportedAlgorithms',
'2.5.4.53': 'deltaRevocationList',
'2.5.4.58': 'attributeCertificate',
'2.5.4.65': 'pseudonym',
'2.5.4.72': 'role',
// X.509 extension OIDsets
'2.5.29.1': 'authorityKeyIdentifierX',
'2.5.29.2': 'keyAttributesX',
'2.5.29.3': 'certificatePoliciesX',
'2.5.29.4': 'keyUsageRestriction',
'2.5.29.5': 'policyMapping',
'2.5.29.6': 'subtreesConstraint',
'2.5.29.7': 'subjectAltNameX',
'2.5.29.8': 'issuerAltNameX',
'2.5.29.9': 'subjectDirectoryAttributes',
'2.5.29.10': 'basicConstraintsX',
'2.5.29.11': 'nameConstraintsX',
'2.5.29.12': 'policyConstraintsX',
'2.5.29.13': 'basicConstraintsY',
'2.5.29.14': 'subjectKeyIdentifier',
'2.5.29.15': 'keyUsage',
'2.5.29.16': 'privateKeyUsagePeriod',
'2.5.29.17': 'subjectAltName',
'2.5.29.18': 'issuerAltName',
'2.5.29.19': 'basicConstraints',
'2.5.29.20': 'cRLNumber',
'2.5.29.21': 'cRLReason',
'2.5.29.22': 'expirationDate',
'2.5.29.23': 'instructionCode',
'2.5.29.24': 'invalidityDate',
'2.5.29.25': 'cRLDistributionPointsX',
'2.5.29.26': 'issuingDistributionPointX',
'2.5.29.27': 'deltaCRLIndicator',
'2.5.29.28': 'issuingDistributionPoint',
'2.5.29.29': 'certificateIssuer',
'2.5.29.30': 'nameConstraints',
'2.5.29.31': 'cRLDistributionPoints',
'2.5.29.32': 'certificatePolicies',
'2.5.29.33': 'policyMappings',
'2.5.29.34': 'policyConstraintsY',
'2.5.29.35': 'authorityKeyIdentifier',
'2.5.29.36': 'policyConstraints',
'2.5.29.37': 'extKeyUsage',
'2.5.29.46': 'freshestCRL',
'2.5.29.54': 'inhibitAnyPolicy',
'2.5.29.55': 'targetInformation',
'2.5.29.56': 'noRevAvail'
};
/**
* ASN.1 Object Identifiers for friandly names
* Generated automaticly
* @field identifiers
* @memberOf GostSecurity
*/
var identifiers = {};
for (var id in names) {
identifiers[names[id]] = id;
} // </editor-fold>
/**
* Algorithm identifiers {@link gostCrypto.AlgorithmIdentifier} for Object Identifiers
*
* @field algorithms
* @memberOf GostSecurity
*/
// <editor-fold defaultstate="collapsed">
var algorithms = {
// CryptoPro algoritms
'id-GostR3411-94-with-GostR3410-2001': 'GOST R 34.10-2001/GOST R 34.11-94',
'id-GostR3411-94-with-GostR3410-94': 'GOST R 34.10-94/GOST R 34.11-94',
'id-GostR3411-94': 'GOST R 34.11-94',
'id-HMACGostR3411-94': {
name: 'HMAC',
hash: {
name: 'GOST R 34.11-94'
}
},
'id-Gost28147-89-None-KeyWrap': 'GOST 28147-89-KW',
'id-Gost28147-89-CryptoPro-KeyWrap': 'GOST 28147-89-CPKW',
'id-GostR3410-2001': 'GOST R 34.10-2001',
'id-GostR3410-94': 'GOST R 34.10-94',
'id-GostR3410-94-a': 'GOST R 34.10-94',
'id-GostR3410-94-aBis': 'GOST R 34.10-94',
'id-GostR3410-94-b': 'GOST R 34.10-94',
'id-GostR3410-94-bBis': 'GOST R 34.10-94',
'id-Gost28147-89': 'GOST 28147-89',
'id-Gost28147-89-MAC': 'GOST 28147-89-MAC',
'id-GostR3410-2001-CryptoPro-ESDH': 'GOST R 34.10-2001-DH/GOST R 34.11-94',
'id-GostR3410-94-CryptoPro-ESDH': 'GOST R 34.10-94-DH/GOST R 34.11-94',
'id-GostR3410-2001DH': 'GOST R 34.10-2001-DH',
'id-GostR3410-94DH': 'GOST R 34.10-94-DH',
// TK-26 attributes
'id-tc26-gost3410-12-256': 'GOST R 34.10-256',
'id-tc26-gost3410-12-512': 'GOST R 34.10-512',
'id-tc26-gost3411-94': 'GOST R 34.11-94',
'id-tc26-gost3411-12-256': 'GOST R 34.11-256',
'id-tc26-gost3411-12-512': 'GOST R 34.11-512',
'id-tc26-signwithdigest-gost3410-12-94': 'GOST R 34.10-256/GOST R 34.11-94',
'id-tc26-signwithdigest-gost3410-12-256': 'GOST R 34.10-256/GOST R 34.11-256',
'id-tc26-signwithdigest-gost3410-12-512': 'GOST R 34.10-512/GOST R 34.11-512',
'id-tc26-hmac-gost-3411-12-256': {
name: 'HMAC',
hash: {
name: 'GOST R 34.11-256'
}
},
'id-tc26-hmac-gost-3411-12-512': {
name: 'HMAC',
hash: {
name: 'GOST R 34.11-512'
}
},
'id-tc26-agreement-gost-3410-12-256': 'GOST R 34.10-256-DH/GOST R 34.11-256',
'id-tc26-agreement-gost-3410-12-512': 'GOST R 34.10-512-DH/GOST R 34.11-256',
// SignalCom algorithms
'id-sc-gost28147-ecb': 'GOST 28147-89-ECB/SC',
'id-sc-gost28147-gamma': 'GOST 28147-89-CTR/SC',
'id-sc-gost28147-gfb': 'GOST 28147-89-CFB/SC',
'id-sc-gost28147-mac': 'GOST 28147-89-MAC/SC',
'id-sc-gostR3410-94': 'GOST R 34.10-94/SC',
'id-sc-gostR3410-94-default': 'GOST R 34.10-94/SC',
'id-sc-gostR3410-94-test': 'GOST R 34.10-94/SC/S-TEST',
'id-sc-gostR3411-94': 'GOST R 34.11-94/SC',
'id-sc-gostR3411-94-with-gostR3410-94': 'GOST R 34.10-94/GOST R 34.11-94/SC',
'id-sc-gostR3411-94-with-gostR3410-2001': 'GOST R 34.10-2001/GOST R 34.11-94/SC',
'id-sc-cmsGostWrap': 'GOST 28147-89-SCKW/SC',
'id-sc-cmsGost28147Wrap': 'GOST 28147-89-KW/SC',
'id-sc-pbeWithGost3411AndGost28147': {
derivation: {
name: 'GOST R 34.11-94-PBKDF2/SC'
},
encryption: {
name: 'GOST 28147-ECB/SC'
}
},
'id-sc-pbeWithGost3411AndGost28147CFB': {
derivation: {
name: 'GOST R 34.11-94-PBKDF2/SC'
},
encryption: {
name: 'GOST 28147-CFB/SC'
}
},
'id-sc-gostR3410-2001': 'GOST R 34.10-2001/SC',
'id-sc-hmacWithGostR3411': {
name: 'HMAC',
hash: {
name: 'GOST R 34.11-94/SC'
}
},
'id-sc-r3410-ESDH-r3411kdf': 'GOST R 34.10-2001-DH/GOST R 34.11-94/SC',
// RSA algorithms
noSignature: 'NONE',
rsaEncryption: {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-256'
}
},
sha1withRSAEncryption: {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-1'
}
},
sha256withRSAEncryption: {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-256'
}
},
sha384withRSAEncryption: {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-384'
}
},
sha512withRSAEncryption: {
name: 'RSASSA-PKCS1-v1_5',
hash: {
name: 'SHA-512'
}
},
'rsaes-oaep': 'RSA-OAEP',
'rsassa-pss': 'RSA-PSS',
// ECDSA
'ecdsa': 'ECDSA',
'ecdsa-with-SHA1': {
name: 'ECDSA',
hash: {
name: 'SHA-1'
}
},
'ecdsa-with-SHA256': {
name: 'ECDSA',
hash: {
name: 'SHA-256'
}
},
'ecdsa-with-SHA384': {
name: 'ECDSA',
hash: {
name: 'SHA-384'
}
},
'ecdsa-with-SHA512': {
name: 'ECDSA',
hash: {
name: 'SHA-512'
}
},
// Legion of the Bouncy Castle pbe
'pbeWithSHAAndAES128-CBC': {
derivation: {
name: 'PBKDF2',
hash: {
name: 'SHA-1'
}
},
encryption: {
name: 'AES-CBC',
length: 128
}
},
'pbeWithSHAAndAES192-CBC': {
derivation: {
name: 'PBKDF2',
hash: {
name: 'SHA-1'
}
},
encryption: {
name: 'AES-CBC',
length: 192
}
},
'pbeWithSHAAndAES256-CBC': {
derivation: {
name: 'PBKDF2',
hash: {
name: 'SHA-1'
}
},
encryption: {
name: 'AES-CBC',
length: 256
}
},
'pbeWithSHA256AndAES128-CBC': {
derivation: {
name: 'PBKDF2',
hash: {
name: 'SHA-256'
}
},
encryption: {
name: 'AES-CBC',
length: 128
}
},
'pbeWithSHA256AndAES192-CBC': {
derivation: {
name: 'PBKDF2',
hash: {
name: 'SHA-256'
}
},
encryption: {
name: 'AES-CBC',
length: 192
}
},
'pbeWithSHA256AndAES256-CBC': {
derivation: {
name: 'PBKDF2',
hash: {
name: 'SHA-256'
}
},
encryption: {
name: 'AES-CBC',
length: 256
}
},
// PKCS12 PBE
'pbeWithSHAAnd3-KeyTripleDES-CBC': {
derivation: {
name: 'PFXKDF',
iterations: 2000,
hash: 'SHA-1'
},
encryption: {
name: '3DES',
block: 'CBC'
}
},
'pbeWithSHAAnd2-KeyTripleDES-CBC': {
derivation: {
name: 'PFXKDF',
iterations: 2000,
hash: 'SHA-1'
},
encryption: {
name: '2DES',
block: 'CBC'
}
},
'pbeWithSHAAnd128BitRC2-CBC': {
derivation: {
name: 'PFXKDF',
iterations: 2000,
hash: 'SHA-1'
},
encryption: {
name: 'RC2',
block: 'CBC',
length: 128
}
},
'pbeWithSHAAnd40BitRC2-CBC': {
derivation: {
name: 'PFXKDF',
iterations: 2000,
hash: 'SHA-1'
},
encryption: {
name: 'RC2',
block: 'CBC',
length: 40
}
},
'pbeUnknownGost': {
derivation: {
name: 'PFXKDF',
iterations: 2000,
hash: 'GOST R 34.11-94'
},
encryption: {
name: 'GOST 28147-89-CFB'
}
},
// Diffie-Hellman Key Exchange Keys
ecDH: 'ECDH',
dhKeyAgreement: 'DH',
// symmetric key algorithm oids
'aes128-CBC': {
name: 'AES-CBC',
length: 128
},
'aes128-CFB': {
name: 'AES-CFB-8',
length: 128
},
'aes128-GCM': {
name: 'AES-GCM',
length: 128
},
'aes128-wrap': {
name: 'AES-KW',
length: 128
},
'aes192-CBC': {
name: 'AES-CBC',
length: 192
},
'aes192-CFB': {
name: 'AES-CFB-8',
length: 192
},
'aes192-GCM': {
name: 'AES-GCM',
length: 192
},
'aes192-wrap': {
name: 'AES-KW',
length: 192
},
'aes256-CBC': {
name: 'AES-CBC',
length: 256
},
'aes256-CFB': {
name: 'AES-CFB-8',
length: 256
},
'aes256-GCM': {
name: 'AES-GCM',
length: 256
},
'aes256-wrap': {
name: 'AES-KW',
length: 256
},
// hash algorihtms
sha1: 'SHA-1',
sha256: 'SHA-256',
sha384: 'SHA-384',
sha512: 'SHA-512',
// PBE
PBKDF2: 'PBKDF2',
PBES2: {
derivation: {
name: 'PBKDF2'
},
encryption: {}
},
PBMAC1: {
derivation: {
name: 'PBKDF2'
},
hmac: {}
},
// HMAC
hmacWithSHA1: 'SHA-1-HMAC',
hmacWithSHA256: {
name: 'HMAC',
hash: {
name: 'SHA-256'
}
},
hmacWithSHA384: {
name: 'HMAC',
hash: {
name: 'SHA-384'
}
},
hmacWithSHA512: {
name: 'HMAC',
hash: {
name: 'SHA-512'
}
}
}; // Each algorithm must has id for convertions
for (var id in algorithms) {
var algorithm = algorithms[id];
if (typeof algorithm === 'string') {
algorithm = {
name: algorithm
};
}
algorithm.id = id;
algorithms[id] = algorithm;
} // </editor-fold>
/**
* Algorithm parameters
*
* @field parameters
* @memberOf GostSecurity
*/
// <editor-fold defaultstate="collapsed">
var parameters = {
'id-GostR3410-94-TestParamSet': {
namedParam: 'S-TEST'
},
'id-GostR3410-94-CryptoPro-A-ParamSet': {
namedParam: 'S-A'
},
'id-GostR3410-94-CryptoPro-B-ParamSet': {
namedParam: 'S-B'
},
'id-GostR3410-94-CryptoPro-C-ParamSet': {
namedParam: 'S-C'
},
'id-GostR3410-94-CryptoPro-D-ParamSet': {
namedParam: 'S-D'
},
'id-GostR3410-94-CryptoPro-XchA-ParamSet': {
namedParam: 'X-A'
},
'id-GostR3410-94-CryptoPro-XchB-ParamSet': {
namedParam: 'X-B'
},
'id-GostR3410-94-CryptoPro-XchC-ParamSet': {
namedParam: 'X-C'
},
// CryptoPro named curves
'id-GostR3410-2001-CryptoPro-TestParamSet': {
namedCurve: 'S-256-TEST'
},
'id-GostR3410-2001-CryptoPro-A-ParamSet': {
namedCurve: 'S-256-A'
},
'id-GostR3410-2001-CryptoPro-B-ParamSet': {
namedCurve: 'S-256-B'
},
'id-GostR3410-2001-CryptoPro-C-ParamSet': {
namedCurve: 'S-256-C'
},
'id-GostR3410-2001-CryptoPro-XchA-ParamSet': {
namedCurve: 'X-256-A'
},
'id-GostR3410-2001-CryptoPro-XchB-ParamSet': {
namedCurve: 'X-256-B'
},
// TC-26 named curves
'id-tc26-gost-3410-12-256-paramSetTest': {
namedCurve: 'T-256-TEST'
},
'id-tc26-gost-3410-12-256-paramSetA': {
namedCurve: 'T-256-A'
},
'id-tc26-gost-3410-12-256-paramSetB': {
namedCurve: 'T-256-B'
},
'id-tc26-gost-3410-12-512-paramSetTest': {
namedCurve: 'T-512-TEST'
},
'id-tc26-gost-3410-12-512-paramSetA': {
namedCurve: 'T-512-A'
},
'id-tc26-gost-3410-12-512-paramSetB': {
namedCurve: 'T-512-B'
},
'id-tc26-gost-3410-12-512-paramSetC': {
namedCurve: 'T-512-C'
},
'id-tc26-gost-3410-12-512-paramSetD': {
namedCurve: 'T-512-D'
},
// Curve attributes additional algorithms
secp256r1: {
namedCurve: 'P-256'
},
secp384r: {
namedCurve: 'P-384'
},
secp521r: {
namedCurve: 'P-521'
},
// CryptoPro encryption parameters
'id-GostR3411-94-TestParamSet': {
sBox: 'D-TEST'
},
'id-GostR3411-94-CryptoProParamSet': {
sBox: 'D-A'
},
'id-GostR3411-94-CryptoPro-A-ParamSet': {
sBox: 'D-B'
},
'id-GostR3411-94-CryptoPro-B-ParamSet': {
sBox: 'D-C'
},
'id-GostR3411-94-CryptoPro-C-ParamSet': {
sBox: 'D-D'
},
'id-Gost28147-89-TestParamSet': {
block: 'CTR',
sBox: 'E-TEST'
},
'id-Gost28147-89-CryptoPro-A-ParamSet': {
block: 'CFB',
sBox: 'E-A',
keyMeshing: 'CP'
},
'id-Gost28147-89-CryptoPro-B-ParamSet': {
block: 'CFB',
sBox: 'E-B',
keyMeshing: 'CP'
},
'id-Gost28147-89-CryptoPro-C-ParamSet': {
block: 'CFB',
sBox: 'E-C',
keyMeshing: 'CP'
},
'id-Gost28147-89-CryptoPro-D-ParamSet': {
block: 'CFB',
sBox: 'E-D',
keyMeshing: 'CP'
},
'id-Gost28147-89-None-KeyMeshing': {
keyMeshing: 'NO'
},
'id-Gost28147-89-CryptoPro-KeyMeshing': {
keyMeshing: 'CP'
},
// TC-26 encryption parameters
'id-tc26-gost-28147-param-Z': {
block: 'CFB',
sBox: 'E-Z'
}
}; // </editor-fold>
/**
* Named attributes for Algorithm identifiers {@link AlgorithmIdentifier}<br><br>
*
* Recognized attributes:
* <ul>
* <li>sBox - Paramsets for GOST 28147. Supported values:
* <ul>
* <li>D-TEST - id-GostR3411-94-TestParamSet</li>
* <li>D-A - id-GostR3411-94-CryptoProParamSet</li>
* <li>D-B - id-GostR3411-94-CryptoPro-A-ParamSet</li>
* <li>D-C - id-GostR3411-94-CryptoPro-B-ParamSet</li>
* <li>D-D - id-GostR3411-94-CryptoPro-C-ParamSet</li>
* <li>E-TEST - id-Gost28147-89-TestParamSet</li>
* <li>E-A - id-Gost28147-89-CryptoPro-A-ParamSet</li>
* <li>E-B - id-Gost28147-89-CryptoPro-B-ParamSet</li>
* <li>E-C - id-Gost28147-89-CryptoPro-C-ParamSet</li>
* <li>E-D - id-Gost28147-89-CryptoPro-D-ParamSet</li>
* <li>E-Z - id-tc26-gost-28147-param-Z</li>
* <li>D-256 - id-tc26-gost3411-12-256</li>
* <li>D-512 - id-tc26-gost3411-12-512</li>
* </ul>
* </li>
* <li>namedParam - Paramset for GOST R 34.10-94
* <ul>
* <li>S-TEST - id-GostR3410-94-TestParamSet</li>
* <li>S-A - id-GostR3410-94-CryptoPro-A-ParamSet</li>
* <li>S-B - id-GostR3410-94-CryptoPro-B-ParamSet</li>
* <li>S-C - id-GostR3410-94-CryptoPro-C-ParamSet</li>
* <li>S-D - id-GostR3410-94-CryptoPro-D-ParamSet</li>
* <li>X-A - id-GostR3410-94-CryptoPro-XchA-ParamSet</li>
* <li>X-B - id-GostR3410-94-CryptoPro-XchB-ParamSet</li>
* <li>X-C - id-GostR3410-94-CryptoPro-XchC-ParamSet</li>
* </ul>
* </li>
* <li>namedCurve - Paramset for GOST R 34.10-01 and GOST R 34.10-12
* <ul>
* <li>S-256-TEST - id-GostR3410-2001-CryptoPro-TestParamSet</li>
* <li>S-256-A - id-GostR3410-2001-CryptoPro-A-ParamSet</li>
* <li>S-256-B - id-GostR3410-2001-CryptoPro-B-ParamSet</li>
* <li>S-256-C - id-GostR3410-2001-CryptoPro-C-ParamSet</li>
* <li>X-256-A - id-GostR3410-2001-CryptoPro-XchA-ParamSet</li>
* <li>X-256-B - id-GostR3410-2001-CryptoPro-XchB-ParamSet</li>
* <li>P-256 - secp256r1</li>
* <li>T-256-TEST - id-tc26-gost-3410-12-256-paramSetTest</li>
* <li>T-256-A - id-tc26-gost-3410-12-256-paramSetA</li>
* <li>T-256-B - id-tc26-gost-3410-12-256-paramSetB</li>
* <li>T-512-TEST - id-tc26-gost-3410-12-512-paramSetTest</li>
* <li>T-512-A - id-tc26-gost-3410-12-512-paramSetA</li>
* <li>T-512-B - id-tc26-gost-3410-12-512-paramSetB</li>
* </ul>
* </li>
* </ul>
* @field attributes
* @memberOf GostSecurity
*/
// <editor-fold defaultstate="collapsed">
var attributes = {
sBox: {
'D-TEST': 'id-GostR3411-94-TestParamSet',
'D-A': 'id-GostR3411-94-CryptoProParamSet',
'D-B': 'id-GostR3411-94-CryptoPro-A-ParamSet',
'D-C': 'id-GostR3411-94-CryptoPro-B-ParamSet',
'D-D': 'id-GostR3411-94-CryptoPro-C-ParamSet',
'E-TEST': 'id-Gost28147-89-TestParamSet',
'E-A': 'id-Gost28147-89-CryptoPro-A-ParamSet',
'E-B': 'id-Gost28147-89-CryptoPro-B-ParamSet',
'E-C': 'id-Gost28147-89-CryptoPro-C-ParamSet',
'E-D': 'id-Gost28147-89-CryptoPro-D-ParamSet',
'E-Z': 'id-tc26-gost-28147-param-Z',
'D-256': 'id-tc26-gost3411-12-256',
'D-512': 'id-tc26-gost3411-12-512'
},
namedParam: {
'S-TEST': 'id-GostR3410-94-TestParamSet',
'S-A': 'id-GostR3410-94-CryptoPro-A-ParamSet',
'S-B': 'id-GostR3410-94-CryptoPro-B-ParamSet',
'S-C': 'id-GostR3410-94-CryptoPro-C-ParamSet',
'S-D': 'id-GostR3410-94-CryptoPro-D-ParamSet',
'X-A': 'id-GostR3410-94-CryptoPro-XchA-ParamSet',
'X-B': 'id-GostR3410-94-CryptoPro-XchB-ParamSet',
'X-C': 'id-GostR3410-94-CryptoPro-XchC-ParamSet'
},
namedCurve: {
'S-256-TEST': 'id-GostR3410-2001-CryptoPro-TestParamSet',
'S-256-A': 'id-GostR3410-2001-CryptoPro-A-ParamSet',
'S-256-B': 'id-GostR3410-2001-CryptoPro-B-ParamSet',
'S-256-C': 'id-GostR3410-2001-CryptoPro-C-ParamSet',
'X-256-A': 'id-GostR3410-2001-CryptoPro-XchA-ParamSet',
'X-256-B': 'id-GostR3410-2001-CryptoPro-XchB-ParamSet',
'P-256': 'secp256r1',
'T-256-TEST': 'id-tc26-gost-3410-12-256-paramSetTest',
'T-256-A': 'id-tc26-gost-3410-12-256-paramSetA',
'T-256-B': 'id-tc26-gost-3410-12-256-paramSetB',
'T-512-TEST': 'id-tc26-gost-3410-12-512-paramSetTest',
'T-512-A': 'id-tc26-gost-3410-12-512-paramSetA',
'T-512-B': 'id-tc26-gost-3410-12-512-paramSetB'
}
}; // </editor-fold>
/**
* Set of algorithms for different providers<br><br>
* Supported providers:
* <ul>
* <li><b>CP-94</b> - CryptoPro GOST R 34.10-94 algorithm set</li>
* <li><b>CP-01</b> - CryptoPro GOST R 34.10-2001 algorithm set</li>
* <li><b>TC-256</b> - Technical Commitee GOST R 34.10-256 algorithm set</li>
* <li><b>TC-512</b> - Technical Commitee GOST R 34.10-512 algorithm set</li>
* <li><b>SC-94</b> - SignalCom GOST R 34.10-94 algorithm set</li>
* <li><b>SC-01</b> - SignalCom GOST R 34.10-2001 algorithm set</li>
* </ul>
*
* Follow set can be used if it's supported your browser native WebCrypto API:
* <ul>
* <li><b>RSA-2048</b> - RSA Encryption 2048 bits with SHA-256 algorithm set</li>
* <li><b>ECDSA-256</b> - ECDSA-256 with SHA-256 algorithm set</li>
* </ul>
*
* Each provider records has follow standart algorithm identifiers:
* <ul>
* <li><b>signature</b> - Signature algorithm</li>
* <li><b>generation</b> - Asymmetric key generation algorithm</li>
* <li><b>digest</b> - Digest algorithm</li>
* <li><b>wrapping</b> - Key wrapping algorithm</li>
* <li><b>hmac</b> - Hash-based message authentication code algorithm</li>
* <li><b>agreement</b> - Key agreement algorithm (except RSA schema)</li>
* <li><b>encryption</b> - Content encription algorithm</li>
* <li><b>derivation</b> - Password-based derivation algorithm</li>
* <li><b>pbes</b> - Password-based encryption algorithm</li>
* <li><b>pbmac</b> - Password-based message authentication code algorithm</li>
* </ul>
*
* @field providers
* @memberOf GostSecurity
*/
// <editor-fold defaultstate="collapsed">
var providers = {
'CP-94': {
title: 'Crypto-Pro GOST R 34.10-94 Cryptographic Service Provider',
signature: algorithms['id-GostR3411-94-with-GostR3410-94'],
publicKey: {
id: 'id-GostR3410-94',
name: 'GOST R 34.10-94',
namedParam: 'X-A'
},
privateKey: {
id: 'id-GostR3410-94DH',
name: 'GOST R 34.10-94-DH',
namedParam: 'X-A'
},
digest: algorithms['id-GostR3411-94'],
wrapping: {
id: 'id-Gost28147-89-CryptoPro-KeyWrap',
name: 'GOST 28147-89-CPKW',
sBox: 'E-A'
},
hmac: algorithms['id-HMACGostR3411-94'],
agreement: algorithms['id-GostR3410-94-CryptoPro-ESDH'],
encryption: {
id: 'id-Gost28147-89',
name: 'GOST 28147-89',
block: 'CFB',
sBox: 'E-A',
keyMeshing: 'CP'
},
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-94-PBKDF2',
iterations: 2000
}
},
'CP-01': {
title: 'Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider',
signature: algorithms['id-GostR3411-94-with-GostR3410-2001'],
publicKey: {
id: 'id-GostR3410-2001',
name: 'GOST R 34.10-2001',
namedCurve: 'X-256-A'
},
privateKey: {
id: 'id-GostR3410-2001DH',
name: 'GOST R 34.10-2001-DH',
namedCurve: 'X-256-A'
},
digest: {
id: 'id-GostR3411-94',
name: 'GOST R 34.11-94',
sBox: 'D-A'
},
wrapping: {
id: 'id-Gost28147-89-CryptoPro-KeyWrap',
name: 'GOST 28147-89-CPKW',
sBox: 'E-A'
},
hmac: algorithms['id-HMACGostR3411-94'],
agreement: algorithms['id-GostR3410-2001-CryptoPro-ESDH'],
encryption: {
id: 'id-Gost28147-89',
name: 'GOST 28147-89-CFB-CPKM',
sBox: 'E-A'
},
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-94-PBKDF2',
iterations: 2000
}
},
'TC-256': {
title: 'Crypto-Pro GOST R 34.10-2012 Cryptographic Service Provider',
signature: algorithms['id-tc26-signwithdigest-gost3410-12-256'],
publicKey: {
id: 'id-tc26-gost3410-12-256',
name: 'GOST R 34.10-256',
namedCurve: 'X-256-A'
},
privateKey: {
id: 'id-tc26-agreement-gost-3410-12-256',
name: 'GOST R 34.10-256-DH/GOST R 34.11-256',
namedCurve: 'X-256-A'
},
digest: algorithms['id-tc26-gost3411-12-256'],
wrapping: {
id: 'id-Gost28147-89-CryptoPro-KeyWrap',
name: 'GOST 28147-89-CPKW',
sBox: 'E-A'
},
hmac: algorithms['id-tc26-hmac-gost-3411-12-256'],
agreement: algorithms['id-tc26-agreement-gost-3410-12-256'],
encryption: {
id: 'id-Gost28147-89',
name: 'GOST 28147-89-CFB-CPKM',
sBox: 'E-A'
},
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-256-12-PBKDF2',
iterations: 2000
}
},
'TC-512': {
title: 'Crypto-Pro GOST R 34.10-2012 Strong Cryptographic Service Provider',
signature: algorithms['id-tc26-signwithdigest-gost3410-12-512'],
publicKey: {
id: 'id-tc26-gost3410-12-512',
name: 'GOST R 34.10-512',
namedCurve: 'T-512-A'
},
privateKey: {
id: 'id-tc26-agreement-gost-3410-12-512',
name: 'GOST R 34.10-512-DH/GOST R 34.11-256',
namedCurve: 'T-512-A'
},
digest: algorithms['id-tc26-gost3411-12-512'],
wrapping: {
id: 'id-Gost28147-89-CryptoPro-KeyWrap',
name: 'GOST 28147-89-CPKW',
sBox: 'E-A'
},
hmac: algorithms['id-tc26-hmac-gost-3411-12-512'],
agreement: algorithms['id-tc26-agreement-gost-3410-12-512'],
encryption: {
id: 'id-Gost28147-89',
name: 'GOST 28147-89-CFB-CPKM',
sBox: 'E-A'
},
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-256-PBKDF2',
iterations: 2000
}
},
'SC-94': {
title: 'Signal-COM GOST Cryptographic Provider',
signature: algorithms['id-sc-gostR3411-94-with-gostR3410-94'],
publicKey: {
id: 'id-sc-gostR3410-94',
name: 'GOST R 34.10-94/SC',
namedParam: 'S-A'
},
privateKey: {
id: 'id-sc-gostR3410-94',
name: 'GOST R 34.10-94/SC',
modulusLength: 1024,
param: {
p: '0xB4E25EFB018E3C8B87505E2A67553C5EDC56C2914B7E4F89D23F03F03377E70A2903489DD60E78418D3D851EDB5317C4871E40B04228C3B7902963C4B7D85D52B9AA88F2AFDBEB28DA8869D6DF846A1D98924E925561BD69300B9DDD05D247B5922D967CBB02671881C57D10E5EF72D3E6DAD4223DC82AA1F7D0294651A480DF',
q: '0x972432A437178B30BD96195B773789AB2FFF15594B176DD175B63256EE5AF2CF',
a: '0x8FD36731237654BBE41F5F1F8453E71CA414FFC22C25D915309E5D2E62A2A26C7111F3FC79568DAFA028042FE1A52A0489805C0DE9A1A469C844C7CABBEE625C3078888C1D85EEA883F1AD5BC4E6776E8E1A0750912DF64F79956499F1E182475B0B60E2632ADCD8CF94E9C54FD1F3B109D81F00BF2AB8CB862ADF7D40B9369A'
}
},
digest: algorithms['id-sc-gostR3411-94'],
encryption: {
id: 'id-sc-gost28147-gfb',
name: 'GOST 28147-89-CFB/SC'
},
hmac: algorithms['id-sc-hmacWithGostR3411'],
wrapping: ['id-sc-cmsGostWrap'],
agreement: algorithms['id-sc-r3410-ESDH-r3411kdf'],
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-94-PBKDF2/SC',
iterations: 2048
},
pbes: {
id: 'id-sc-pbeWithGost3411AndGost28147CFB',
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-94-PBKDF2/SC',
iterations: 2048
},
encryption: {
id: 'id-sc-gost28147-gfb',
name: 'GOST 28147-CFB/SC',
iv: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])
}
}
},
'SC-01': {
title: 'Signal-COM ECGOST Cryptographic Provider',
signature: algorithms['id-sc-gostR3411-94-with-gostR3410-2001'],
publicKey: {
id: 'id-sc-gostR3410-2001',
name: 'GOST R 34.10-2001/SC',
namedCurve: 'P-256'
},
privateKey: {
id: 'id-sc-gostR3410-2001',
name: 'GOST R 34.10-2001/SC',
curve: {
p: '0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF',
a: '0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC',
b: '0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B',
x: '0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296',
y: '0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5',
q: '0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551'
}
},
digest: algorithms['id-sc-gostR3411-94'],
encryption: {
id: 'id-sc-gost28147-gfb',
name: 'GOST 28147-89-CFB/SC'
},
hmac: algorithms['id-sc-hmacWithGostR3411'],
wrapping: algorithms['id-sc-cmsGostWrap'],
agreement: algorithms['id-sc-r3410-ESDH-r3411kdf'],
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-94-PBKDF2/SC',
iterations: 2048
},
pbes: {
id: 'id-sc-pbeWithGost3411AndGost28147CFB',
derivation: {
id: 'PBKDF2',
name: 'GOST R 34.11-94-PBKDF2/SC',
iterations: 2048
},
encryption: {
id: 'id-sc-gost28147-gfb',
name: 'GOST 28147-CFB/SC',
iv: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])
}
}
},
'RSA-2048': {
title: 'Microsoft Strong Cryptographic Provider',
signature: algorithms['sha256withRSAEncryption'],
publicKey: {
id: 'rsaEncryption',
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: algorithms['sha256']
},
privateKey: {
id: 'rsaEncryption',
name: 'RSASSA-PKCS1-v1_5',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: algorithms['sha256']
},
digest: algorithms['sha256'],
encryption: algorithms['aes256-CFB'],
hmac: algorithms['hmacWithSHA256']
},
'ECDSA-256': {
title: 'Microsoft Base DSS and Diffie-Hellman Cryptographic Provider',
signature: algorithms['ecdsa-with-SHA256'],
publicKey: {
id: 'ecdsa',
name: 'ECDSA',
namedCurve: 'P-256'
},
privateKey: {
id: 'ecdsa',
name: 'ECDSA',
namedCurve: 'P-256'
},
digest: algorithms['sha256'],
encryption: algorithms['aes256-CFB'],
hmac: algorithms['hmacWithSHA256'],
agreement: algorithms['ecDH']
}
}; // Russian providers extension
['CP-94', 'CP-01', 'TC-256', 'TC-512', 'SC-94', 'SC-01'].forEach(function (name) {
var provider = providers[name];
provider.hmac = expand(provider.hmac, {
hash: provider.digest
});
provider.derivation = expand(provider.derivation, {
hash: provider.digest,
hmac: provider.hmac
});
provider.pbes = provider.pbes || {
id: 'PBES2',
derivation: provider.derivation,
encryption: provider.encryption
};
provider.pbmac = provider.pbmac || {
id: 'PBMAC1',
derivation: provider.derivation,
hmac: provider.hmac
};
provider.agreement = expand(provider.agreement, {
wrapping: provider.wrapping
});
}); // RSA & ECDA providers extension
['RSA-2048', 'ECDSA-256'].forEach(function (name) {
var provider = providers[name];
provider.derivation = provider.derivation || {
id: 'PBKDF2',
name: 'PBKDF2',
iterations: 2048,
hash: provider.digest
};
provider.pbes = provider.pbes || {
id: 'PBES2',
derivation: provider.derivation,
encryption: provider.encryption
};
provider.pbmac = provider.pbmac || {
id: 'PBMAC1',
derivation: provider.derivation,
hmac: provider.hmac
};
}); // Workaround for Chrome error for RSA algorithm when hash for keys is not defined
// if (root.crypto && root.crypto.subtle)
// setTimeout(function () {
// root.crypto.subtle.generateKey(providers['RSA-2048'].generation, false, ["sign"])['catch'](function () {
// providers['RSA-2048'].generation.hash = providers['RSA-2048'].digest;
// algorithms['rsaEncryption'].hash = providers['RSA-2048'].digest;
// });
// });
// </editor-fold>
/**
* GOST and common ASN.1 Object and Algorithm Identifiers
* @class GostSecurity
*/
function GostSecurity() {}
GostSecurity.prototype = {
names: names,
identifiers: identifiers,
algorithms: algorithms,
parameters: parameters,
attributes: attributes,
providers: providers
};
/**
* GOST and common ASN.1 Object and Algorithm Identifiers
*
* @memberOf gostCrypto
* @type GostSecurity
*/
gostCrypto.security = new GostSecurity();
return GostSecurity();
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostCrypto":110}],116:[function(require,module,exports){
(function (global){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/**
* @file GOST 34.10-2012 signature function with 1024/512 bits digest
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Used library JSBN http://www-cs-students.stanford.edu/~tjw/jsbn/
* Copyright (c) 2003-2005 Tom Wu (tjw@cs.Stanford.EDU)
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/
// <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostRandom', 'gostDigest'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostRandom'), require('./gostDigest'));
} else {
root.GostSign = factory(root.GostRandom, root.GostDigest);
} // </editor-fold>
})(void 0, function (GostRandom, GostDigest) {
/*
* Predefined curves and params collection
*
* http://tools.ietf.org/html/rfc5832
* http://tools.ietf.org/html/rfc7091
* http://tools.ietf.org/html/rfc4357
*
*/
// <editor-fold defaultstate="collapsed">
var root = (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object' && self.self === self && self || (typeof global === "undefined" ? "undefined" : _typeof(global)) === 'object' && global.global === global && global || this;
var rootCrypto = root.crypto || root.msCrypto;
var CryptoOperationData = root.ArrayBuffer;
var OperationError = root.OperationError || root.Error,
DataError = root.DataError || root.Error,
NotSupportedError = root.NotSupportedError || root.Error; // Predefined named curve collection
var ECGostParams = {
'S-256-TEST': {
a: 7,
b: '0x5FBFF498AA938CE739B8E022FBAFEF40563F6E6A3472FC2A514C0CE9DAE23B7E',
p: '0x8000000000000000000000000000000000000000000000000000000000000431',
q: '0x8000000000000000000000000000000150FE8A1892976154C59CFC193ACCF5B3',
x: 2,
y: '0x8E2A8A0E65147D4BD6316030E16D19C85C97F0A9CA267122B96ABBCEA7E8FC8'
},
'S-256-A': {
a: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD94',
b: 166,
p: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97',
q: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C611070995AD10045841B09B761B893',
x: 1,
y: '0x8D91E471E0989CDA27DF505A453F2B7635294F2DDF23E3B122ACC99C9E9F1E14'
},
'S-256-B': {
a: '0x8000000000000000000000000000000000000000000000000000000000000C96',
b: '0x3E1AF419A269A5F866A7D3C25C3DF80AE979259373FF2B182F49D4CE7E1BBC8B',
p: '0x8000000000000000000000000000000000000000000000000000000000000C99',
q: '0x800000000000000000000000000000015F700CFFF1A624E5E497161BCC8A198F',
x: 1,
y: '0x3FA8124359F96680B83D1C3EB2C070E5C545C9858D03ECFB744BF8D717717EFC'
},
'S-256-C': {
a: '0x9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598',
b: 32858,
p: '0x9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B',
q: '0x9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9',
x: 0,
y: '0x41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67'
},
'P-256': {
p: '0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF',
a: '0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC',
b: '0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B',
x: '0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296',
y: '0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5',
q: '0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551'
},
'T-512-TEST': {
a: 7,
b: '0x1CFF0806A31116DA29D8CFA54E57EB748BC5F377E49400FDD788B649ECA1AC4361834013B2AD7322480A89CA58E0CF74BC9E540C2ADD6897FAD0A3084F302ADC',
p: '0x4531ACD1FE0023C7550D267B6B2FEE80922B14B2FFB90F04D4EB7C09B5D2D15DF1D852741AF4704A0458047E80E4546D35B8336FAC224DD81664BBF528BE6373',
q: '0x4531ACD1FE0023C7550D267B6B2FEE80922B14B2FFB90F04D4EB7C09B5D2D15DA82F2D7ECB1DBAC719905C5EECC423F1D86E25EDBE23C595D644AAF187E6E6DF',
x: '0x24D19CC64572EE30F396BF6EBBFD7A6C5213B3B3D7057CC825F91093A68CD762FD60611262CD838DC6B60AA7EEE804E28BC849977FAC33B4B530F1B120248A9A',
y: '0x2BB312A43BD2CE6E0D020613C857ACDDCFBF061E91E5F2C3F32447C259F39B2C83AB156D77F1496BF7EB3351E1EE4E43DC1A18B91B24640B6DBB92CB1ADD371E'
},
'T-512-A': {
p: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC7',
a: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC4',
b: '0xE8C2505DEDFC86DDC1BD0B2B6667F1DA34B82574761CB0E879BD081CFD0B6265EE3CB090F30D27614CB4574010DA90DD862EF9D4EBEE4761503190785A71C760',
q: '0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF27E69532F48D89116FF22B8D4E0560609B4B38ABFAD2B85DCACDB1411F10B275',
x: 3,
y: '0x7503CFE87A836AE3A61B8816E25450E6CE5E1C93ACF1ABC1778064FDCBEFA921DF1626BE4FD036E93D75E6A50E3A41E98028FE5FC235F5B889A589CB5215F2A4'
},
'T-512-B': {
p: '0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006F',
a: '0x8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006C',
b: '0x687D1B459DC841457E3E06CF6F5E2517B97C7D614AF138BCBF85DC806C4B289F3E965D2DB1416D217F8B276FAD1AB69C50F78BEE1FA3106EFB8CCBC7C5140116',
q: '0x800000000000000000000000000000000000000000000000000000000000000149A1EC142565A545ACFDB77BD9D40CFA8B996712101BEA0EC6346C54374F25BD',
x: 2,
y: '0x1A8F7EDA389B094C2C071E3647A8940F3C123B697578C213BE6DD9E6C8EC7335DCB228FD1EDF4A39152CBCAAF8C0398828041055F94CEEEC7E21340780FE41BD'
}
};
ECGostParams['X-256-A'] = ECGostParams['S-256-A'];
ECGostParams['X-256-B'] = ECGostParams['S-256-C'];
ECGostParams['T-256-TEST'] = ECGostParams['S-256-TEST'];
ECGostParams['T-256-A'] = ECGostParams['S-256-A'];
ECGostParams['T-256-B'] = ECGostParams['S-256-B'];
ECGostParams['T-256-C'] = ECGostParams['S-256-C'];
var GostParams = {
'S-TEST': {
modulusLength: 512,
// bit length of p (512 or 1024 bits)
p: '0xEE8172AE8996608FB69359B89EB82A69854510E2977A4D63BC97322CE5DC3386EA0A12B343E9190F23177539845839786BB0C345D165976EF2195EC9B1C379E3',
q: '0x98915E7EC8265EDFCDA31E88F24809DDB064BDC7285DD50D7289F0AC6F49DD2D',
a: '0x9e96031500c8774a869582d4afde2127afad2538b4b6270a6f7c8837b50d50f206755984a49e509304d648be2ab5aab18ebe2cd46ac3d8495b142aa6ce23e21c'
},
'S-A': {
modulusLength: 1024,
p: '0xB4E25EFB018E3C8B87505E2A67553C5EDC56C2914B7E4F89D23F03F03377E70A2903489DD60E78418D3D851EDB5317C4871E40B04228C3B7902963C4B7D85D52B9AA88F2AFDBEB28DA8869D6DF846A1D98924E925561BD69300B9DDD05D247B5922D967CBB02671881C57D10E5EF72D3E6DAD4223DC82AA1F7D0294651A480DF',
q: '0x972432A437178B30BD96195B773789AB2FFF15594B176DD175B63256EE5AF2CF',
a: '0x8FD36731237654BBE41F5F1F8453E71CA414FFC22C25D915309E5D2E62A2A26C7111F3FC79568DAFA028042FE1A52A0489805C0DE9A1A469C844C7CABBEE625C3078888C1D85EEA883F1AD5BC4E6776E8E1A0750912DF64F79956499F1E182475B0B60E2632ADCD8CF94E9C54FD1F3B109D81F00BF2AB8CB862ADF7D40B9369A'
},
'S-B': {
modulusLength: 1024,
p: '0xC6971FC57524B30C9018C5E621DE15499736854F56A6F8AEE65A7A404632B1BCF0349FFCAFCB0A103177971FC1612ADCDB8C8CC938C70225C8FD12AFF01B1D064E0AD6FDE6AB9159166CB9F2FC171D92F0CC7B6A6B2CD7FA342ACBE2C9315A42D576B1ECCE77A963157F3D0BD96A8EB0B0F3502AD238101B05116334F1E5B7AB',
q: '0xB09D634C10899CD7D4C3A7657403E05810B07C61A688BAB2C37F475E308B0607',
a: '0x3D26B467D94A3FFC9D71BF8DB8934084137264F3C2E9EB16DCA214B8BC7C872485336744934FD2EF5943F9ED0B745B90AA3EC8D70CDC91682478B664A2E1F8FB56CEF2972FEE7EDB084AF746419B854FAD02CC3E3646FF2E1A18DD4BEB3C44F7F2745588029649674546CC9187C207FB8F2CECE8E2293F68395C4704AF04BAB5'
},
'S-C': {
modulusLength: 1024,
p: '0x9D88E6D7FE3313BD2E745C7CDD2AB9EE4AF3C8899E847DE74A33783EA68BC30588BA1F738C6AAF8AB350531F1854C3837CC3C860FFD7E2E106C3F63B3D8A4C034CE73942A6C3D585B599CF695ED7A3C4A93B2B947B7157BB1A1C043AB41EC8566C6145E938A611906DE0D32E562494569D7E999A0DDA5C879BDD91FE124DF1E9',
q: '0xFADD197ABD19A1B4653EECF7ECA4D6A22B1F7F893B641F901641FBB555354FAF',
a: '0x7447ED7156310599070B12609947A5C8C8A8625CF1CF252B407B331F93D639DDD1BA392656DECA992DD035354329A1E95A6E32D6F47882D960B8F10ACAFF796D13CD9611F853DAB6D2623483E46788708493937A1A29442598AEC2E0742022563440FE9C18740ECE6765AC05FAF024A64B026E7E408840819E962E7E5F401AE3'
},
'S-D': {
modulusLength: 1024,
p: '0x80F102D32B0FD167D069C27A307ADAD2C466091904DBAA55D5B8CC7026F2F7A1919B890CB652C40E054E1E9306735B43D7B279EDDF9102001CD9E1A831FE8A163EED89AB07CF2ABE8242AC9DEDDDBF98D62CDDD1EA4F5F15D3A42A6677BDD293B24260C0F27C0F1D15948614D567B66FA902BAA11A69AE3BCEADBB83E399C9B5',
q: '0xF0F544C418AAC234F683F033511B65C21651A6078BDA2D69BB9F732867502149',
a: '0x6BCC0B4FADB3889C1E06ADD23CC09B8AB6ECDEDF73F04632595EE4250005D6AF5F5ADE44CB1E26E6263C672347CFA26F9E9393681E6B759733784CDE5DBD9A14A39369DFD99FA85CC0D10241C4010343F34A91393A706CF12677CBFA1F578D6B6CFBE8A1242CFCC94B3B653A476E145E3862C18CC3FED8257CFEF74CDB205BF1'
},
'X-A': {
modulusLength: 1024,
p: '0xCA3B3F2EEE9FD46317D49595A9E7518E6C63D8F4EB4D22D10D28AF0B8839F079F8289E603B03530784B9BB5A1E76859E4850C670C7B71C0DF84CA3E0D6C177FE9F78A9D8433230A883CD82A2B2B5C7A3306980278570CDB79BF01074A69C9623348824B0C53791D53C6A78CAB69E1CFB28368611A397F50F541E16DB348DBE5F',
q: '0xCAE4D85F80C147704B0CA48E85FB00A9057AA4ACC44668E17F1996D7152690D9',
a: '0xBE27D652F2F1E339DA734211B85B06AE4DE236AA8FBEEB3F1ADCC52CD43853777E834A6A518138678A8ADBD3A55C70A7EAB1BA7A0719548677AAF4E609FFB47F6B9D7E45B0D06D83D7ADC53310ABD85783E7317F7EC73268B6A9C08D260B85D8485696CA39C17B17F044D1E050489036ABD381C5E6BF82BA352A1AFF136601AF'
},
'X-B': {
modulusLength: 1024,
p: '0x9286DBDA91ECCFC3060AA5598318E2A639F5BA90A4CA656157B2673FB191CD0589EE05F4CEF1BD13508408271458C30851CE7A4EF534742BFB11F4743C8F787B11193BA304C0E6BCA25701BF88AF1CB9B8FD4711D89F88E32B37D95316541BF1E5DBB4989B3DF13659B88C0F97A3C1087B9F2D5317D557DCD4AFC6D0A754E279',
q: '0xC966E9B3B8B7CDD82FF0F83AF87036C38F42238EC50A876CD390E43D67B6013F',
a: '0x7E9C3096676F51E3B2F9884CF0AC2156779496F410E049CED7E53D8B7B5B366B1A6008E5196605A55E89C3190DABF80B9F1163C979FCD18328DAE5E9048811B370107BB7715F82091BB9DE0E33EE2FED6255474F8769FCE5EAFAEEF1CB5A32E0D5C6C2F0FC0B3447072947F5B4C387666993A333FC06568E534AD56D2338D729'
},
'X-C': {
modulusLength: 1024,
p: '0xB194036ACE14139D36D64295AE6C50FC4B7D65D8B340711366CA93F383653908EE637BE428051D86612670AD7B402C09B820FA77D9DA29C8111A8496DA6C261A53ED252E4D8A69A20376E6ADDB3BDCD331749A491A184B8FDA6D84C31CF05F9119B5ED35246EA4562D85928BA1136A8D0E5A7E5C764BA8902029A1336C631A1D',
q: '0x96120477DF0F3896628E6F4A88D83C93204C210FF262BCCB7DAE450355125259',
a: '0x3F1817052BAA7598FE3E4F4FC5C5F616E122CFF9EBD89EF81DC7CE8BF56CC64B43586C80F1C4F56DD5718FDD76300BE336784259CA25AADE5A483F64C02A20CF4A10F9C189C433DEFE31D263E6C9764660A731ECCAECB74C8279303731E8CF69205BC73E5A70BDF93E5BB681DAB4EEB9C733CAAB2F673C475E0ECA921D29782E'
}
}; // </editor-fold>
/*
* BigInteger arithmetic tools
* optimized release of http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js
*
*/
// <editor-fold defaultstate="collapsed">
// Bits per one element
var DB = 28,
DM = (1 << DB) - 1,
DV = 1 << DB,
FV = Math.pow(2, 52),
F1 = 52 - DB,
F2 = 2 * DB - 52;
function am(y, i, x, w, j, c, n) {
var xl = x & 0x3fff,
xh = x >> 14;
while (--n >= 0) {
var l = y[i] & 0x3fff;
var h = y[i++] >> 14;
var m = xh * l + h * xl;
l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
c = (l >> 28) + (m >> 14) + xh * h;
w[j++] = l & 0xfffffff;
}
return c;
}
function nbi(words) {
var r = new Array(Math.ceil(words));
r.s = 0;
r.t = 0;
return r;
}
function copyTo(x, r) {
for (var i = x.t - 1; i >= 0; --i) {
r[i] = x[i];
}
r.t = x.t;
r.s = x.s;
return r;
}
function copy(x) {
return copyTo(x, nbi(x.t));
}
function setInt(x, i) {
x.t = 1;
x.s = i < 0 ? -1 : 0;
if (i > 0) x[0] = i;else if (i < -1) x[0] = i + DV;else x.t = 0;
return x;
}
function nbv(i) {
var r = nbi(1);
setInt(r, i);
return r;
}
var ZERO = nbv(0),
ONE = nbv(1),
THREE = nbv(3);
function clamp(x) {
var c = x.s & DM;
while (x.t > 0 && x[x.t - 1] === c) {
--x.t;
}
return x;
}
function subTo(x, a, r) {
var i = 0,
c = 0,
m = Math.min(a.t, x.t);
while (i < m) {
c += x[i] - a[i];
r[i++] = c & DM;
c >>= DB;
}
if (a.t < x.t) {
c -= a.s;
while (i < x.t) {
c += x[i];
r[i++] = c & DM;
c >>= DB;
}
c += x.s;
} else {
c += x.s;
while (i < a.t) {
c -= a[i];
r[i++] = c & DM;
c >>= DB;
}
c -= a.s;
}
r.s = c < 0 ? -1 : 0;
if (c < -1) r[i++] = DV + c;else if (c > 0) r[i++] = c;
r.t = i;
return clamp(r);
}
function sub(x, y) {
return subTo(x, y, nbi(x.t));
}
function addTo(x, a, r) {
var i = 0,
c = 0,
m = Math.min(a.t, x.t);
while (i < m) {
c += x[i] + a[i];
r[i++] = c & DM;
c >>= DB;
}
if (a.t < x.t) {
c += a.s;
while (i < x.t) {
c += x[i];
r[i++] = c & DM;
c >>= DB;
}
c += x.s;
} else {
c += x.s;
while (i < a.t) {
c += a[i];
r[i++] = c & DM;
c = c >> DB;
}
c += a.s;
}
r.s = c < 0 ? -1 : 0;
if (c > 0) r[i++] = c;else if (c < -1) r[i++] = DV + c;
r.t = i;
return clamp(r);
}
function add(x, y) {
return addTo(x, y, nbi(x.t));
}
function negTo(x, r) {
return subTo(ZERO, x, r);
}
function neg(x) {
return negTo(x, nbi(x.t));
}
function absTo(x, r) {
return x.s < 0 ? negTo(r) : copyTo(r);
}
function abs(x) {
return x.s < 0 ? neg(x) : x;
}
function compare(x, a) {
var r = x.s - a.s;
if (r !== 0) return r;
var i = x.t;
r = i - a.t;
if (r !== 0) return x.s < 0 ? -r : r;
while (--i >= 0) {
if ((r = x[i] - a[i]) !== 0) return r;
}
return 0;
}
function equals(x, y) {
return compare(x, y) === 0;
}
function min(x, y) {
return compare(x, y) < 0 ? x : y;
}
function max(x, y) {
return compare(x, y) > 0 ? x : y;
}
function nbits(x) {
var r = 1,
t;
if ((t = x >>> 16) !== 0) {
x = t;
r += 16;
}
if ((t = x >> 8) !== 0) {
x = t;
r += 8;
}
if ((t = x >> 4) !== 0) {
x = t;
r += 4;
}
if ((t = x >> 2) !== 0) {
x = t;
r += 2;
}
if ((t = x >> 1) !== 0) {
x = t;
r += 1;
}
return r;
}
function dshlTo(x, n, r) {
var i;
for (i = x.t - 1; i >= 0; --i) {
r[i + n] = x[i];
}
for (i = n - 1; i >= 0; --i) {
r[i] = 0;
}
r.t = x.t + n;
r.s = x.s;
return r;
}
function dshrTo(x, n, r) {
for (var i = n; i < x.t; ++i) {
r[i - n] = x[i];
}
r.t = Math.max(x.t - n, 0);
r.s = x.s;
return r;
}
function shlTo(x, n, r) {
var bs = n % DB;
var cbs = DB - bs;
var bm = (1 << cbs) - 1;
var ds = Math.floor(n / DB),
c = x.s << bs & DM,
i;
for (i = x.t - 1; i >= 0; --i) {
r[i + ds + 1] = x[i] >> cbs | c;
c = (x[i] & bm) << bs;
}
for (i = ds - 1; i >= 0; --i) {
r[i] = 0;
}
r[ds] = c;
r.t = x.t + ds + 1;
r.s = x.s;
return clamp(r);
}
function shrTo(x, n, r) {
r.s = x.s;
var ds = Math.floor(n / DB);
if (ds >= x.t) {
r.t = 0;
return;
}
var bs = n % DB;
var cbs = DB - bs;
var bm = (1 << bs) - 1;
r[0] = x[ds] >> bs;
for (var i = ds + 1; i < x.t; ++i) {
r[i - ds - 1] |= (x[i] & bm) << cbs;
r[i - ds] = x[i] >> bs;
}
if (bs > 0) r[x.t - ds - 1] |= (x.s & bm) << cbs;
r.t = x.t - ds;
return clamp(r);
}
function shl(x, n) {
var r = nbi(x.t);
if (n < 0) shrTo(x, -n, r);else shlTo(x, n, r);
return r;
}
function shr(x, n) {
var r = nbi(x.t);
if (n < 0) shlTo(x, -n, r);else shrTo(x, n, r);
return r;
}
function bitLength(x) {
if (x.t <= 0) return 0;
return DB * (x.t - 1) + nbits(x[x.t - 1] ^ x.s & DM);
}
function _mulTo(b, a, r) {
var x = abs(b),
y = abs(a);
var i = x.t;
r.t = i + y.t;
while (--i >= 0) {
r[i] = 0;
}
for (i = 0; i < y.t; ++i) {
r[i + x.t] = am(x, 0, y[i], r, i, 0, x.t);
}
r.s = 0;
if (b.s !== a.s) subTo(ZERO, r, r);
return clamp(r);
}
function mul(x, y) {
return _mulTo(x, y, nbi(x.t + y.t));
}
function _sqrTo(a, r) {
var x = abs(a);
var i = r.t = 2 * x.t;
while (--i >= 0) {
r[i] = 0;
}
for (i = 0; i < x.t - 1; ++i) {
var c = am(x, i, x[i], r, 2 * i, 0, 1);
if ((r[i + x.t] += am(x, i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
r[i + x.t] -= x.DV;
r[i + x.t + 1] = 1;
}
}
if (r.t > 0) r[r.t - 1] += am(x, i, x[i], r, 2 * i, 0, 1);
r.s = 0;
return clamp(r);
}
function sqr(a) {
return _sqrTo(a, nbi(a.t * 2));
}
function divRemTo(n, m, q, r) {
var pm = abs(m);
if (pm.t <= 0) throw new OperationError('Division by zero');
var pt = abs(n);
if (pt.t < pm.t) {
if (q) setInt(q, 0);
if (r) copyTo(n, r);
return q;
}
if (!r) r = nbi(m.t);
var y = nbi(m.t),
ts = n.s,
ms = m.s;
var nsh = DB - nbits(pm[pm.t - 1]);
if (nsh > 0) {
shlTo(pm, nsh, y);
shlTo(pt, nsh, r);
} else {
copyTo(pm, y);
copyTo(pt, r);
}
var ys = y.t;
var y0 = y[ys - 1];
if (y0 === 0) return q;
var yt = y0 * (1 << F1) + (ys > 1 ? y[ys - 2] >> F2 : 0);
var d1 = FV / yt,
d2 = (1 << F1) / yt,
e = 1 << F2;
var i = r.t,
j = i - ys,
t = !q ? nbi(Math.max(n.t - m.t, 1)) : q;
dshlTo(y, j, t);
if (compare(r, t) >= 0) {
r[r.t++] = 1;
subTo(r, t, r);
}
dshlTo(ONE, ys, t);
subTo(t, y, y);
while (y.t < ys) {
y[y.t++] = 0;
}
while (--j >= 0) {
var qd = r[--i] === y0 ? DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
if ((r[i] += am(y, 0, qd, r, j, 0, ys)) < qd) {
dshlTo(y, j, t);
subTo(r, t, r);
while (r[i] < --qd) {
subTo(r, t, r);
}
}
}
if (q) {
dshrTo(r, ys, q);
if (ts !== ms) subTo(ZERO, q, q);
}
r.t = ys;
clamp(r);
if (nsh > 0) shrTo(r, nsh, r);
if (ts < 0) subTo(ZERO, r, r);
return q;
}
function modTo(b, a, r) {
divRemTo(abs(b), a, null, r);
if (b.s < 0 && compare(r, ZERO) > 0) subTo(a, r, r);
return r;
}
function mod(b, a) {
return modTo(b, a, nbi(a.t));
}
function div(b, a) {
return divRemTo(b, a, nbi(Math.max(b.t - a.t, 1)), null);
}
function isEven(x) {
return (x.t > 0 ? x[0] & 1 : x.s) === 0;
}
function isZero(x) {
return equals(x, ZERO);
}
function sig(x) {
if (x.s < 0) return -1;else if (x.t <= 0 || x.t === 1 && x[0] <= 0) return 0;else return 1;
}
function invMod(x, m) {
var ac = isEven(m);
if (isEven(x) && ac || sig(m) === 0) return ZERO;
var u = copy(m),
v = copy(x);
var a = nbv(1),
b = nbv(0),
c = nbv(0),
d = nbv(1);
while (sig(u) !== 0) {
while (isEven(u)) {
shrTo(u, 1, u);
if (ac) {
if (!isEven(a) || !isEven(b)) {
addTo(a, x, a);
subTo(b, m, b);
}
shrTo(a, 1, a);
} else if (!isEven(b)) subTo(b, m, b);
shrTo(b, 1, b);
}
while (isEven(v)) {
shrTo(v, 1, v);
if (ac) {
if (!isEven(c) || !isEven(d)) {
addTo(c, x, c);
subTo(d, m, d);
}
shrTo(c, 1, c);
} else if (!isEven(d)) subTo(d, m, d);
shrTo(d, 1, d);
}
if (compare(u, v) >= 0) {
subTo(u, v, u);
if (ac) subTo(a, c, a);
subTo(b, d, b);
} else {
subTo(v, u, v);
if (ac) subTo(c, a, c);
subTo(d, b, d);
}
}
if (compare(v, ONE) !== 0) return ZERO;
if (compare(d, m) >= 0) return sub(d, m);
if (sig(d) < 0) addTo(d, m, d);else return d;
if (sig(d) < 0) return add(d, m);else return d;
}
function testBit(x, n) {
var j = Math.floor(n / DB);
if (j >= x.t) return x.s !== 0;
return (x[j] & 1 << n % DB) !== 0;
}
function nothing(x) {
return x;
}
function extend(c, o) {
for (var i in o) {
c.prototype[i] = o[i];
}
} // </editor-fold>
/*
* Classic, Barret, Mongomery reductions, optimized ExpMod algorithms
* optimized release of http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn2.js
*
*/
// <editor-fold defaultstate="collapsed">
// Classic reduction
var Classic = function Classic(m) {
this.m = m;
};
extend(Classic, {
convert: function convert(x) {
if (x.s < 0 || compare(x, this.m) >= 0) return mod(x, this.m);else return x;
},
revert: nothing,
reduce: function reduce(x) {
modTo(x, this.m, x);
},
sqrTo: function sqrTo(x, r) {
_sqrTo(x, r);
this.reduce(r);
},
mulTo: function mulTo(x, y, r) {
_mulTo(x, y, r);
this.reduce(r);
}
});
function invDig(a) {
if (a.t < 1) return 0;
var x = a[0];
if ((x & 1) === 0) return 0;
var y = x & 3;
y = y * (2 - (x & 0xf) * y) & 0xf;
y = y * (2 - (x & 0xff) * y) & 0xff;
y = y * (2 - ((x & 0xffff) * y & 0xffff)) & 0xffff;
y = y * (2 - x * y % DV) % DV;
return y > 0 ? DV - y : -y;
} // Montgomery reduction
var Montgomery = function Montgomery(m) {
this.m = m;
this.mp = invDig(m);
this.mpl = this.mp & 0x7fff;
this.mph = this.mp >> 15;
this.um = (1 << DB - 15) - 1;
this.mt2 = 2 * m.t;
};
extend(Montgomery, {
// xR mod m
convert: function convert(x) {
var r = nbi(x.t);
dshlTo(abs(x), this.m.t, r);
divRemTo(r, this.m, null, r);
if (x.s < 0 && compare(r, ZERO) > 0) subTo(this.m, r, r);
return r;
},
// x/R mod m
revert: function revert(x) {
var r = nbi(x.t);
copyTo(x, r);
this.reduce(r);
return r;
},
// x = x/R mod m (HAC 14.32)
reduce: function reduce(x) {
while (x.t <= this.mt2) {
x[x.t++] = 0;
}
for (var i = 0; i < this.m.t; ++i) {
var j = x[i] & 0x7fff;
var u0 = j * this.mpl + ((j * this.mph + (x[i] >> 15) * this.mpl & this.um) << 15) & DM;
j = i + this.m.t;
x[j] += am(this.m, 0, u0, x, i, 0, this.m.t);
while (x[j] >= DV) {
x[j] -= DV;
x[++j]++;
}
}
clamp(x);
dshrTo(x, this.m.t, x);
if (compare(x, this.m) >= 0) subTo(x, this.m, x);
},
// r = "x^2/R mod m"; x != r
sqrTo: function sqrTo(x, r) {
_sqrTo(x, r);
this.reduce(r);
},
// r = "xy/R mod m"; x,y != r
mulTo: function mulTo(x, y, r) {
_mulTo(x, y, r);
this.reduce(r);
}
});
function dAddOffset(x, n, w) {
if (n === 0) return;
while (x.t <= w) {
x[x.t++] = 0;
}
x[w] += n;
while (x[w] >= DV) {
x[w] -= DV;
if (++w >= x.t) x[x.t++] = 0;
++x[w];
}
}
function mulLowerTo(x, a, n, r) {
var i = Math.min(x.t + a.t, n);
r.s = 0; // assumes a,x >= 0
r.t = i;
while (i > 0) {
r[--i] = 0;
}
var j;
for (j = r.t - x.t; i < j; ++i) {
r[i + x.t] = am(x, 0, a[i], r, i, 0, x.t);
}
for (j = Math.min(a.t, n); i < j; ++i) {
am(x, 0, a[i], r, i, 0, n - i);
}
return clamp(r);
}
function mulUpperTo(x, a, n, r) {
--n;
var i = r.t = x.t + a.t - n;
r.s = 0; // assumes a,x >= 0
while (--i >= 0) {
r[i] = 0;
}
for (i = Math.max(n - x.t, 0); i < a.t; ++i) {
r[x.t + i - n] = am(x, n - i, a[i], r, 0, 0, x.t + i - n);
}
clamp(r);
return dshrTo(r, 1, r);
} // Barrett modular reduction
function Barrett(m) {
// setup Barrett
this.r2 = nbi(2 * m.t);
this.q3 = nbi(2 * m.t);
dshlTo(ONE, 2 * m.t, this.r2);
this.mu = div(this.r2, m);
this.m = m;
}
extend(Barrett, {
convert: function convert(x) {
if (x.s < 0 || x.t > 2 * this.m.t) return mod(x, this.m);else if (compare(x, this.m) < 0) return x;else {
var r = nbi(x.t);
copyTo(x, r);
this.reduce(r);
return r;
}
},
revert: function revert(x) {
return x;
},
// x = x mod m (HAC 14.42)
reduce: function reduce(x) {
dshrTo(x, this.m.t - 1, this.r2);
if (x.t > this.m.t + 1) {
x.t = this.m.t + 1;
clamp(x);
}
mulUpperTo(this.mu, this.r2, this.m.t + 1, this.q3);
mulLowerTo(this.m, this.q3, this.m.t + 1, this.r2);
while (compare(x, this.r2) < 0) {
dAddOffset(x, 1, this.m.t + 1);
}
subTo(x, this.r2, x);
while (compare(x, this.m) >= 0) {
subTo(x, this.m, x);
}
},
// r = x^2 mod m; x != r
sqrTo: function sqrTo(x, r) {
_sqrTo(x, r);
this.reduce(r);
},
// r = x*y mod m; x,y != r
mulTo: function mulTo(x, y, r) {
_mulTo(x, y, r);
this.reduce(r);
}
}); // x^e % m (HAC 14.85)
function expMod(x, e, m) {
var i = bitLength(e),
k,
r = nbv(1),
z;
if (i <= 0) return r;else if (i < 18) k = 1;else if (i < 48) k = 3;else if (i < 144) k = 4;else if (i < 768) k = 5;else k = 6;
if (i < 8) z = new Classic(m);else if (isEven(m)) z = new Barrett(m);else z = new Montgomery(m); // precomputation
var g = new Array(),
n = 3,
k1 = k - 1,
km = (1 << k) - 1;
g[1] = z.convert(x);
if (k > 1) {
var g2 = nbi(m.t * 2);
z.sqrTo(g[1], g2);
while (n <= km) {
g[n] = nbi(m.t * 2);
z.mulTo(g2, g[n - 2], g[n]);
n += 2;
}
}
var j = e.t - 1,
w,
is1 = true,
r2 = nbi(m.t * 2),
t;
i = nbits(e[j]) - 1;
while (j >= 0) {
if (i >= k1) w = e[j] >> i - k1 & km;else {
w = (e[j] & (1 << i + 1) - 1) << k1 - i;
if (j > 0) w |= e[j - 1] >> DB + i - k1;
}
n = k;
while ((w & 1) == 0) {
w >>= 1;
--n;
}
if ((i -= n) < 0) {
i += DB;
--j;
}
if (is1) {
// ret == 1, don't bother squaring or multiplying it
copyTo(g[w], r);
is1 = false;
} else {
while (n > 1) {
z.sqrTo(r, r2);
z.sqrTo(r2, r);
n -= 2;
}
if (n > 0) z.sqrTo(r, r2);else {
t = r;
r = r2;
r2 = t;
}
z.mulTo(r2, g[w], r);
}
while (j >= 0 && (e[j] & 1 << i) == 0) {
z.sqrTo(r, r2);
t = r;
r = r2;
r2 = t;
if (--i < 0) {
i = DB - 1;
--j;
}
}
}
return z.revert(r);
} // </editor-fold>
/*
* EC Field Elements, Points, Curves
* optimized release of http://www-cs-students.stanford.edu/~tjw/jsbn/ec.js
*
*/
// <editor-fold defaultstate="collapsed">
// EC Field Elemets
function newFE(a, x) {
a.r.reduce(x);
x.q = a.q;
x.r = a.r;
return x;
}
function copyFE(a, x) {
x.q = a.q;
x.r = a.r;
return x;
}
function negFE(a) {
return copyFE(a, sub(a.q, a));
}
function addFE(a, b) {
var r = add(a, b);
if (compare(r, a.q) > 0) subTo(r, a.q, r);
return copyFE(a, r);
}
function subFE(a, b) {
var r = sub(a, b);
if (r.s < 0) addTo(a.q, r, r);
return copyFE(a, r);
}
function mulFE(a, b) {
return newFE(a, mul(a, b));
}
function sqrFE(a) {
return newFE(a, sqr(a));
}
function shlFE(a, i) {
return newFE(a, shl(a, i));
}
function invFE(a) {
return copyFE(a, invMod(a, a.q));
} // EC Points
function newEC(curve, x, y, z) {
return {
curve: curve,
x: x,
y: y,
z: z || newFE(curve, ONE)
};
}
function getX(point) {
if (!point.zinv) point.zinv = invFE(point.z);
return mulFE(point.x, point.zinv);
}
function getY(point) {
if (!point.zinv) point.zinv = invFE(point.z);
return mulFE(point.y, point.zinv);
}
function isInfinity(a) {
if (!a.x && !a.y) return true;
return isZero(a.z) && !isZero(a.y);
}
function getInfinity(a) {
return a.curve.infinity;
}
function equalsEC(a, b) {
if (a === b) return true;
if (isInfinity(a)) return isInfinity(b);
if (isInfinity(b)) return isInfinity(a);
var u, v; // u = Y2 * Z1 - Y1 * Z2
u = subFE(mulFE(b.y, a.z), mulFE(a.y, b.z));
if (!isZero(u)) return false; // v = X2 * Z1 - X1 * Z2
v = subFE(mulFE(b.x, a.z), mulFE(a.x, b.z));
return isZero(v);
}
function negEC(a) {
return newEC(a.curve, a.x, negFE(a.y), a.z);
}
function addEC(a, b) {
if (isInfinity(a)) return b;
if (isInfinity(b)) return a; // u = Y2 * Z1 - Y1 * Z2
var u = subFE(mulFE(b.y, a.z), mulFE(a.y, b.z)); // v = X2 * Z1 - X1 * Z2
var v = subFE(mulFE(b.x, a.z), mulFE(a.x, b.z));
if (isZero(v)) {
if (isZero(u)) {
return twiceEC(a); // a == b, so double
}
return getInfinity(a); // a = -b, so infinity
}
var x1 = a.x;
var y1 = a.y;
var v2 = sqrFE(v);
var v3 = mulFE(v2, v);
var x1v2 = mulFE(x1, v2);
var zu2 = mulFE(sqrFE(u), a.z); // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
var x3 = mulFE(subFE(mulFE(subFE(zu2, shlFE(x1v2, 1)), b.z), v3), v); // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
var y3 = addFE(mulFE(subFE(subFE(mulFE(mulFE(x1v2, THREE), u), mulFE(y1, v3)), mulFE(zu2, u)), b.z), mulFE(u, v3)); // z3 = v^3 * z1 * z2
var z3 = mulFE(mulFE(v3, a.z), b.z);
return newEC(a.curve, x3, y3, z3);
}
function twiceEC(b) {
if (isInfinity(b)) return b;
if (sig(b.y) === 0) return getInfinity(b);
var x1 = b.x;
var y1 = b.y;
var y1z1 = mulFE(y1, b.z);
var y1sqz1 = mulFE(y1z1, y1);
var a = b.curve.a; // w = 3 * x1^2 + a * z1^2
var w = mulFE(sqrFE(x1), THREE);
if (!isZero(a)) {
w = addFE(w, mulFE(sqrFE(b.z), a));
} // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
var x3 = mulFE(shlFE(subFE(sqrFE(w), mulFE(shlFE(x1, 3), y1sqz1)), 1), y1z1); // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
var y3 = subFE(mulFE(shlFE(subFE(mulFE(mulFE(w, THREE), x1), shlFE(y1sqz1, 1)), 2), y1sqz1), mulFE(sqrFE(w), w)); // z3 = 8 * (y1 * z1)^3
var z3 = shlFE(mulFE(sqrFE(y1z1), y1z1), 3);
return newEC(b.curve, x3, y3, z3);
} // Simple NAF (Non-Adjacent Form) multiplication algorithm
function mulEC(a, k) {
if (isInfinity(a)) return a;
if (sig(k) === 0) return getInfinity(a);
var e = k;
var h = mul(e, THREE);
var neg = negEC(a);
var R = a;
var i;
for (i = bitLength(h) - 2; i > 0; --i) {
R = twiceEC(R);
var hBit = testBit(h, i);
var eBit = testBit(e, i);
if (hBit !== eBit) {
R = addEC(R, hBit ? a : neg);
}
}
return R;
}
function mul2AndAddEC(a, k) {
var nbits = bitLength(k);
var R = a,
Q = getInfinity(a);
for (var i = 0; i < nbits - 1; i++) {
if (testBit(k, i) === 1) Q = addEC(Q, R);
R = twiceEC(R);
}
if (testBit(k, nbits - 1) === 1) Q = addEC(Q, R);
return Q;
} // Compute a*j + x*k (simultaneous multiplication)
function mulTwoEC(a, j, x, k) {
var i;
if (bitLength(j) > bitLength(k)) i = bitLength(j) - 1;else i = bitLength(k) - 1;
var R = getInfinity(a);
var both = addEC(a, x);
while (i >= 0) {
R = twiceEC(R);
if (testBit(j, i)) {
if (testBit(k, i)) {
R = addEC(R, both);
} else {
R = addEC(R, a);
}
} else {
if (testBit(k, i)) {
R = addEC(R, x);
}
}
--i;
}
return R;
} // EC Curve
function newCurve(q, a, b) {
var curve = {};
curve.q = q;
curve.r = new Barrett(q);
curve.a = newFE(curve, a);
curve.b = newFE(curve, b);
curve.infinity = newEC(curve);
return curve;
} // </editor-fold>
/*
* Converion tools (hex, binary)
*
*/
// <editor-fold defaultstate="collapsed">
function atobi(d) {
var k = 8;
var a = new Uint8Array(d);
var r = nbi(a.length * 8 / DB);
r.t = 0;
r.s = 0;
var sh = 0;
for (var i = 0, n = a.length; i < n; i++) {
var x = a[i];
if (sh === 0) r[r.t++] = x;else if (sh + k > DB) {
r[r.t - 1] |= (x & (1 << DB - sh) - 1) << sh;
r[r.t++] = x >> DB - sh;
} else r[r.t - 1] |= x << sh;
sh += k;
if (sh >= DB) sh -= DB;
}
return clamp(r);
}
function bitoa(s, bitLength) {
var k = 8;
var km = (1 << k) - 1,
d,
m = false,
r = [],
i = s.t;
var p = DB - i * DB % k;
if (i-- > 0) {
if (p < DB && (d = s[i] >> p) > 0) {
m = true;
r.push(d);
}
while (i >= 0) {
if (p < k) {
d = (s[i] & (1 << p) - 1) << k - p;
d |= s[--i] >> (p += DB - k);
} else {
d = s[i] >> (p -= k) & km;
if (p <= 0) {
p += DB;
--i;
}
}
if (d > 0) m = true;
if (m) r.push(d);
}
}
var r8 = new Uint8Array(bitLength ? bitLength / 8 : r.length);
if (m) r8.set(r.reverse());
return r8.buffer;
}
function htobi(s) {
if (typeof s === 'number' || s instanceof Number) return nbv(s);
s = s.replace(/[^\-A-Fa-f0-9]/g, '');
if (!s) s = '0';
var k = 4;
var r = nbi(s.length / 7);
var i = s.length,
mi = false,
sh = 0;
while (--i >= 0) {
var c = s.charAt(i);
if (c === '-') {
mi = true;
continue;
}
var x = parseInt(s.charAt(i), 16);
mi = false;
if (sh === 0) r[r.t++] = x;else if (sh + k > DB) {
r[r.t - 1] |= (x & (1 << DB - sh) - 1) << sh;
r[r.t++] = x >> DB - sh;
} else r[r.t - 1] |= x << sh;
sh += k;
if (sh >= DB) sh -= DB;
}
if (mi) subTo(ZERO, r, r);
return clamp(r);
}
function bitoh(x) {
if (x.s < 0) return "-" + bitoh(negTo(x, nbi(x.t)));
var k = 4;
var km = (1 << k) - 1,
d,
m = false,
r = "",
i = x.t;
var p = DB - i * DB % k;
if (i-- > 0) {
if (p < DB && (d = x[i] >> p) > 0) {
m = true;
r = d.toString(16);
}
while (i >= 0) {
if (p < k) {
d = (x[i] & (1 << p) - 1) << k - p;
d |= x[--i] >> (p += DB - k);
} else {
d = x[i] >> (p -= k) & km;
if (p <= 0) {
p += DB;
--i;
}
}
if (d > 0) m = true;
if (m) r += d.toString(16);
}
}
return "0x" + (m ? r : "0");
} // biginteger to big-endian integer bytearray
function bitoi(s) {
var i = s.t,
r = [];
r[0] = s.s;
var p = DB - i * DB % 8,
d,
k = 0;
if (i-- > 0) {
if (p < DB && (d = s[i] >> p) !== (s.s & DM) >> p) r[k++] = d | s.s << DB - p;
while (i >= 0) {
if (p < 8) {
d = (s[i] & (1 << p) - 1) << 8 - p;
d |= s[--i] >> (p += DB - 8);
} else {
d = s[i] >> (p -= 8) & 0xff;
if (p <= 0) {
p += DB;
--i;
}
}
if ((d & 0x80) !== 0) d |= -256;
if (k === 0 && (s.s & 0x80) !== (d & 0x80)) ++k;
if (k > 0 || d !== s.s) r[k++] = d;
}
}
return new Uint8Array(r).buffer;
} // big-endian integer bytearray to biginteger
function itobi(d) {
var k = 8,
s = new Uint8Array(d),
r = nbi(s.length / 7);
r.t = 0;
r.s = 0;
var i = s.length,
sh = 0;
while (--i >= 0) {
var x = s[i] & 0xff;
if (sh === 0) r[r.t++] = x;else if (sh + k > DB) {
r[r.t - 1] |= (x & (1 << DB - sh) - 1) << sh;
r[r.t++] = x >> DB - sh;
} else r[r.t - 1] |= x << sh;
sh += k;
if (sh >= DB) sh -= DB;
}
if ((s[0] & 0x80) !== 0) {
r.s = -1;
if (sh > 0) r[r.t - 1] |= (1 << DB - sh) - 1 << sh;
}
return clamp(r);
} // Swap bytes in buffer
function swap(s) {
var src = new Uint8Array(s),
dst = new Uint8Array(src.length);
for (var i = 0, n = src.length; i < n; i++) {
dst[n - i - 1] = src[i];
}
return dst.buffer;
} // Calculate hash of data
function hash(d) {
if (this.hash) d = this.hash.digest(d); // Swap hash for SignalCom
if (this.procreator === 'SC' || this.procreator === 'VN' && this.hash.version === 2012) d = swap(d);
return d;
} // Check buffer
function buffer(d) {
if (d instanceof CryptoOperationData) return d;else if (d && d.buffer && d.buffer instanceof CryptoOperationData) return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ? d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;else throw new DataError('CryptoOperationData or CryptoOperationDataView required');
} // Check double buffer
function to2(d) {
var b = buffer(d);
if (b.byteLength % 2 > 0) throw new DataError('Buffer length must be even');
var n = b.byteLength / 2;
return [atobi(new Uint8Array(b, 0, n)), atobi(new Uint8Array(b, n, n))];
}
function from2(x, y, bitLength) {
var a = bitoa(x, bitLength),
b = bitoa(y, bitLength),
d = new Uint8Array(a.byteLength + b.byteLength);
d.set(new Uint8Array(a));
d.set(new Uint8Array(b), a.byteLength);
return d.buffer;
}
function getSeed(length) {
GostRandom = GostRandom || root.GostRandom;
var randomSource = GostRandom ? new (GostRandom || root.GostRandom)() : rootCrypto;
if (randomSource.getRandomValues) {
var d = new Uint8Array(Math.ceil(length / 8));
randomSource.getRandomValues(d);
return d;
} else throw new NotSupportedError('Random generator not found');
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* The sign method returns sign data generated with the supplied privateKey.<br>
*
* @memberOf GostSign
* @method sign
* @instance
* @param {(CryptoOperationData|TypedArray)} privateKey Private key
* @param {(CryptoOperationData|TypedArray)} data Data
* @returns {CryptoOperationData} Signature
*/
function sign(privateKey, data) // <editor-fold defaultstate="collapsed">
{
// Stage 1
var b = buffer(data);
var alpha = atobi(hash.call(this, b));
var q = this.q;
var x = mod(atobi(buffer(privateKey)), q); // Stage 2
var e = mod(alpha, q);
if (isZero(e)) e = ONE;
var s = ZERO;
while (isZero(s)) {
var r = ZERO;
while (isZero(r)) {
// Stage 3
var k = mod(atobi(this.ukm || getSeed(this.bitLength)), q); // pseudo random 0 < k < q
// Stage 4
if (this.curve) {
// Gost R 34.10-2001 || Gost R 34.10-2012
var P = this.P;
var C = mulEC(P, k);
r = mod(getX(C), q);
} else {
// Gost R 34.10-94
var p = this.p,
a = this.a;
r = mod(expMod(a, k, p), q);
}
} // Stage 5
s = mod(add(mul(r, x), mul(k, e)), q);
} // Stage 6
// console.log('s', bitoh(s));
// console.log('r', bitoh(r));
var zetta; // Integer structure for SignalCom algorithm
if (this.procreator === 'SC') {
zetta = {
r: bitoh(r),
s: bitoh(s)
};
} else {
zetta = from2(r, s, this.bitLength); // Swap bytes for CryptoPro algorithm
if (this.procreator === 'CP' || this.procreator === 'VN') zetta = swap(zetta);
}
return zetta;
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* The verify method returns signature verification for the supplied publicKey.<br>
*
* @memberOf GostSign
* @method sign
* @instance
* @param {(CryptoOperationData|TypedArray)} publicKey Public key
* @param {(CryptoOperationData|TypedArray)} signature Signature
* @param {(CryptoOperationData|TypedArray)} data Data
* @returns {boolean} Signature verified = true
*/
function verify(publicKey, signature, data) // <editor-fold defaultstate="collapsed">
{
// Stage 1
var q = this.q;
var r, s; // Ready int for SignalCom algorithm
if (this.procreator === 'SC') {
r = htobi(signature.r);
s = htobi(signature.s);
} else {
if (this.procreator === 'CP' || this.procreator === 'VN') signature = swap(signature);
var zetta = to2(signature); // Swap bytes for CryptoPro algorithm
s = zetta[1]; // first 32 octets contain the big-endian representation of s
r = zetta[0]; // and second 32 octets contain the big-endian representation of r
}
if (compare(r, q) >= 0 || compare(s, q) >= 0) return false; // Stage 2
var b = buffer(data);
var alpha = atobi(hash.call(this, b)); // Stage 3
var e = mod(alpha, q);
if (isZero(e) === 0) e = ONE; // Stage 4
var v = invMod(e, q); // Stage 5
var z1 = mod(mul(s, v), q);
var z2 = sub(q, mod(mul(r, v), q)); // Stage 6
if (this.curve) {
// Gost R 34.10-2001 || Gost R 34.10-2012
var k2 = to2(publicKey),
curve = this.curve,
P = this.P,
x = newFE(curve, k2[0]),
// first 32 octets contain the little-endian representation of x
y = newFE(curve, k2[1]),
// and second 32 octets contain the little-endian representation of y.
Q = new newEC(curve, x, y); // This corresponds to the binary representation of (<y>256||<x>256)
var C = mulTwoEC(P, z1, Q, z2);
var R = mod(getX(C), q);
} else {
// Gost R 34.10-94
var p = this.p,
a = this.a;
var y = atobi(publicKey);
var R = mod(mod(mul(expMod(a, z1, p), expMod(y, z2, p)), p), q);
} // Stage 7
return compare(R, r) === 0;
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* The generateKey method returns a new generated key pair using the specified
* AlgorithmIdentifier.
*
* @memberOf GostSign
* @method generateKey
* @instance
* @returns {Object} Object with two CryptoOperationData members: privateKey and publicKey
*/
function generateKey() // <editor-fold defaultstate="collapsed">
{
var curve = this.curve;
if (curve) {
var Q = curve.infinity;
while (isInfinity(Q)) {
// Generate random private key
var d = ZERO;
if (this.ukm) {
d = atobi(this.ukm);
} else {
while (isZero(d)) {
d = mod(atobi(getSeed(this.bitLength)), this.q);
} // 0 < d < q
} // Calculate public key
Q = mulEC(this.P, d);
var x = getX(Q),
y = getY(Q); // console.log('d', bitoh(d));
// console.log('x', bitoh(x));
// console.log('y', bitoh(y));
} // Return result
return {
privateKey: bitoa(d, this.bitLength),
publicKey: from2(x, y, this.bitLength) // This corresponds to the binary representation of (<y>256||<x>256)
};
} else throw new NotSupportedError('Key generation for GOST R 34.10-94 not supported');
} // </editor-fold>
/**
* Algorithm name GOST R 34.10 mode MASK<br><br>
*
* The generateMaskKey method returns a new generated key mask using for wrapping.
*
* @memberOf GostSign
* @method generateMaskKey
* @instance
* @returns {Object} Object with two CryptoOperationData members: privateKey and publicKey
*/
function generateMaskKey() // <editor-fold defaultstate="collapsed">
{
var curve = this.curve;
if (curve) {
// Generate random private key
var d = ZERO;
while (isZero(d)) {
d = mod(atobi(getSeed(this.bitLength)), this.q);
} // 0 < d < q
// Return result
return bitoa(d, this.bitLength);
} else throw new NotSupportedError('Key generation for GOST R 34.10-94 not supported');
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* Unwrap private key from private key and ukm (mask)
*
* @memberOf GostSign
* @method unwrap
* @instance
* @param {(CryptoOperationData|TypedArray)} baseKey Unwrapping key
* @param {(CryptoOperationData|TypedArray)} data Wrapped key
* @returns {Object} CryptoOperationData unwrapped privateKey
*/
function unwrapKey(baseKey, data) // <editor-fold defaultstate="collapsed">
{
var curve = this.curve;
if (curve) {
var q = this.q;
var x = mod(atobi(buffer(data)), q);
var y = mod(atobi(buffer(baseKey)), q);
var z = this.procreator === 'VN' ? mod(mul(x, y), q) : mod(mul(x, invMod(y, q)), q);
return bitoa(z);
} else throw new NotSupportedError('Key wrapping GOST R 34.10-94 not supported');
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* Wrap private key with private key and ukm (mask)
*
* @memberOf GostSign
* @method unwrap
* @instance
* @param {(CryptoOperationData|TypedArray)} baseKey Wrapping key
* @param {(CryptoOperationData|TypedArray)} data Key
* @returns {Object} CryptoOperationData unwrapped privateKey
*/
function wrapKey(baseKey, data) // <editor-fold defaultstate="collapsed">
{
var curve = this.curve;
if (curve) {
var q = this.q;
var x = mod(atobi(buffer(data)), q);
var y = mod(atobi(buffer(baseKey)), q);
var z = this.procreator === 'VN' ? mod(mul(x, invMod(y, q)), q) : mod(mul(x, y), q);
return bitoa(z);
} else throw new NotSupportedError('Key wrapping GOST R 34.10-94 not supported');
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* @memberOf GostSign
* @method derive
* @instance
* @private
* @param {CryptoOperationData} baseKey Key for deriviation
* @returns {CryptoOperationData}
*/
function derive(baseKey) // <editor-fold defaultstate="collapsed">
{
var k,
ukm = atobi(this.ukm);
var q = this.q;
var x = mod(atobi(buffer(baseKey)), q);
if (this.curve) {
// 1) Let K(x,y,UKM) = ((UKM*x)(mod q)) . (y.P) (512 bit), where
// x - sender’s private key (256 bit)
// x.P - sender’s public key (512 bit)
// y - recipient’s private key (256 bit)
// y.P - recipient’s public key (512 bit)
// UKM - non-zero integer, produced as in step 2 p. 6.1 [GOSTR341001]
// P - base point on the elliptic curve (two 256-bit coordinates)
// UKM*x - x multiplied by UKM as integers
// x.P - a multiple point
var K = mulEC(this.peer_Q, mod(mul(ukm, x), q));
k = from2(getX(K), getY(K), // This corresponds to the binary representation of (<y>256||<x>256)
this.bitLength);
} else {
// 1) Let K(x,y) = a^(x*y) (mod p), where
// x - sender’s private key, a^x - sender’s public key
// y - recipient’s private key, a^y - recipient’s public key
// a, p - parameters
var p = this.p,
a = this.a;
k = bitoa(expMod(this.peer_y, x, p));
} // 2) Calculate a 256-bit hash of K(x,y,UKM):
// KEK(x,y,UKM) = gostSign (K(x,y,UKM)
return hash.call(this, k);
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* The deriveBits method returns length bits on baseKey.
*
* @memberOf GostSign
* @method deriveBits
* @instance
* @param {(CryptoOperationData|TypedArray)} baseKey Key for deriviation
* @param {number} length output bit-length
* @returns {CryptoOperationData} result
*/
function deriveBits(baseKey, length) // <editor-fold defaultstate="collapsed">
{
if (length < 8 || length > this.bitLength || length % 8 > 0) throw new DataError('Length must be no more than ' + this.bitLength + ' bits and multiple of 8');
var n = length / 8,
b = derive.call(this, baseKey),
r = new Uint8Array(n);
r.set(new Uint8Array(b, 0, n));
return r.buffer;
} // </editor-fold>
/**
* Algorithm name GOST R 34.10<br><br>
*
* The deriveKey method returns 256 bit Key encryption key on baseKey.
*
* This algorithm creates a key encryption key (KEK) using 64 bit UKM,
* the sender’s private key, and the recipient’s public key (or the
* reverse of the latter pair
*
* @memberOf GostSign
* @method deriveKey
* @instance
* @param {(CryptoOperationData|TypedArray)} baseKey Key for deriviation
* @returns {CryptoOperationData} result
*/
function deriveKey(baseKey) // <editor-fold defaultstate="collapsed">
{
var b = derive.call(this, baseKey),
r = new Uint8Array(32);
r.set(new Uint8Array(b, 0, 32));
return r.buffer;
} // </editor-fold>
/**
* Gost R 34.10 universal object<br><br>
*
* References: {@link http://tools.ietf.org/html/rfc6986} and {@link http://tools.ietf.org/html/rfc5831}<br><br>
*
* Normalized algorithm identifier common parameters:
*
* <ul>
* <li><b>name</b> Algorithm name 'GOST R 34.10'</li>
* <li><b>version</b> Algorithm version
* <ul>
* <li><b>1994</b> - Old-style GOST R 34.10-94 ExpMod algorithm with GOST R 34.11-94 hash</li>
* <li><b>2001</b> - GOST R 34.10-2001 Eliptic curve algorithm with old GOST R 34.11-94 hash</li>
* <li><b>2012</b> - GOST R 34.10-2012 Eliptic curve algorithm with GOST R 34.11-12 hash, default mode</li>
* </ul>
* </li>
* <li><b>length</b> Length of hash and signature. Key length == hash length for EC algorithms and 2 * hash length for ExpMod algorithm
* <ul>
* <li><b>GOST R 34.10-256</b> - 256 bits digest, default mode</li>
* <li><b>GOST R 34.10-512</b> - 512 bits digest only for GOST R 34.11-2012 hash</li>
* </ul>
* </li>
* <li><b>mode</b> Algorithm mode
* <ul>
* <li><b>SIGN</b> Digital signature mode (default)</li>
* <li><b>DH</b> Diffie-Hellman key generation and key agreement mode</li>
* </ul>
* </li>
* <li><b>sBox</b> Paramset sBox for GOST 34.11-94. Used only if version = 1994 or 2001</li>
* </ul>
*
* Supported algorithms, modes and parameters:
*
* <ul>
* <li>Sign/Verify mode (SIGN)</li>
* <li>DeriveKey/DeriveBits mode (DH)
* <ul>
* <li>{@link CryptoOperationData} <b>ukm</b> User key material. Default - random generated value</li>
* <li>{@link CryptoOperationData} <b>public</b> The peer's EC public key data</li>
* </ul>
* </li>
* <li>GenerateKey mode (SIGN and DH) version = 1994
* <ul>
* <li><b>namedParam</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
* </ul>
* Additional parameters, if namedParam not specified
* <ul>
* <li><b>modulusLength</b> Bit length of p (512 or 1024 bits). Default = 1024</li>
* <li><b>p</b> {@link CryptoOperationData} Modulus, prime number, 2^(t-1)<p<2^t</li>
* <li><b>q</b> {@link CryptoOperationData} Order of cyclic group, prime number, 2^254<q<2^256, q is a factor of p-1</li>
* <li><b>a</b> {@link CryptoOperationData} Generator, integer, 1<a<p-1, at that aq (mod p) = 1</li>
* </ul>
* </li>
* <li>GenerateKey mode (SIGN and DH) version = 2001 or 2012
* <ul>
* <li><b>namedCurve</b> Paramset for key generation algorithm. If specified no additianal parameters required</li>
* </ul>
* Additional EC parameters, if namedCurve not specified
* <ul>
* <li><b>p</b> {@link CryptoOperationData} Prime number - elliptic curve modulus</li>
* <li><b>a</b> {@link CryptoOperationData} Coefficients a of the elliptic curve E</li>
* <li><b>b</b> {@link CryptoOperationData} Coefficients b of the elliptic curve E</li>
* <li><b>q</b> {@link CryptoOperationData} Prime number - order of cyclic group</li>
* <li><b>x</b> {@link CryptoOperationData} Base point p x-coordinate</li>
* <li><b>y</b> {@link CryptoOperationData} Base point p y-coordinate</li>
* </ul>
* </li>
* </ul>
*
* @class GostSign
* @param {AlgorithmIndentifier} algorithm
*/
function GostSign(algorithm) // <editor-fold defaultstate="collapsed">
{
algorithm = algorithm || {};
this.name = (algorithm.name || 'GOST R 34.10') + '-' + (algorithm.version || 2012) % 100 + '-' + (algorithm.length || 256) + ((algorithm.mode || 'SIGN') !== 'SIGN' ? '-' + algorithm.mode : '') + (typeof algorithm.namedParam === 'string' ? '/' + algorithm.namedParam : '') + (typeof algorithm.namedCurve === 'string' ? '/' + algorithm.namedCurve : '') + (typeof algorithm.sBox === 'string' ? '/' + algorithm.sBox : '');
var version = algorithm.version || 2012; // Functions
switch (algorithm.mode || 'SIGN') {
case 'SIGN':
this.sign = sign;
this.verify = verify;
this.generateKey = generateKey;
break;
case 'DH':
this.deriveBits = deriveBits;
this.deriveKey = deriveKey;
this.generateKey = generateKey;
break;
case 'MASK':
this.wrapKey = wrapKey;
this.unwrapKey = unwrapKey;
this.generateKey = generateMaskKey;
break;
} // Define parameters
if (version === 1994) {
// Named or parameters algorithm
var param = algorithm.param;
if (!param) param = GostParams[this.namedParam = (algorithm.namedParam || 'S-A').toUpperCase()];
this.modulusLength = algorithm.modulusLength || param.modulusLength || 1024;
this.p = htobi(param.p);
this.q = htobi(param.q);
this.a = htobi(param.a); // Public key for derive
if (algorithm['public']) this.peer_y = atobi(algorithm['public']);
} else {
// Named or parameters algorithm
var param = algorithm.curve;
if (!param) param = ECGostParams[this.namedCurve = (algorithm.namedCurve || 'S-256-A').toUpperCase()];
var curve = this.curve = newCurve(htobi(param.p), htobi(param.a), htobi(param.b));
this.P = newEC(curve, newFE(curve, htobi(param.x)), newFE(curve, htobi(param.y)));
this.q = htobi(param.q); // Public key for derive
if (algorithm['public']) {
var k2 = to2(algorithm['public']);
this.peer_Q = new newEC(this.curve, // This corresponds to the binary representation of (<y>256||<x>256)
newFE(this.curve, k2[0]), // first 32 octets contain the little-endian representation of x
newFE(this.curve, k2[1])); // and second 32 octets contain the little-endian representation of y.
}
} // Check bit length
var hashLen, keyLen;
if (this.curve) {
keyLen = algorithm.length || bitLength(this.q);
if (keyLen > 508 && keyLen <= 512) keyLen = 512;else if (keyLen > 254 && keyLen <= 256) keyLen = 256;else throw new NotSupportedError('Support keys only 256 or 512 bits length');
hashLen = keyLen;
} else {
keyLen = algorithm.modulusLength || bitLength(this.p);
if (keyLen > 1016 && keyLen <= 1024) keyLen = 1024;else if (keyLen > 508 && keyLen <= 512) keyLen = 512;else throw new NotSupportedError('Support keys only 512 or 1024 bits length');
hashLen = 256;
}
this.bitLength = hashLen;
this.keyLength = keyLen; // Algorithm proceator for result conversion
this.procreator = algorithm.procreator; // Hash function definition
var hash = algorithm.hash;
if (hash) {
if (typeof hash === 'string' || hash instanceof String) hash = {
name: hash
};
if (algorithm.version === 1994 || algorithm.version === 2001) {
hash.version = 1994;
hash.length = 256;
hash.sBox = algorithm.sBox || hash.sBox;
} else {
hash.version = 2012;
hash.length = hashLen;
}
hash.procreator = hash.procreator || algorithm.procreator;
if (!GostDigest) GostDigest = root.GostDigest;
if (!GostDigest) throw new NotSupportedError('Object GostDigest not found');
this.hash = new GostDigest(hash);
} // Pregenerated seed for key exchange algorithms
if (algorithm.ukm) // Now don't check size
this.ukm = algorithm.ukm;
} // </editor-fold>
return GostSign;
});
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./gostDigest":111,"./gostRandom":114}],117:[function(require,module,exports){
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/*
* Copyright (c) 2014, Rudolf Nickolaev.
* All rights reserved.
*
* ASN.1 decode viewers
*
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['gostCrypto', 'gostCoding', 'gostSecurity', 'gostASN1'], factory);
} else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object') {
module.exports = factory(require('./gostCrypto'), require('./gostCoding'), require('./gostSecurity'), require('./gostASN1'));
} else {
root.gostViewer = factory(root.gostCrypto, root.gostCoding, root.gostSecurity, root.gostASN1);
}
})(void 0, function (gostCrypto) {
var coding = gostCrypto.coding,
names = gostCrypto.security.names,
asn1 = gostCrypto.asn1;
var printASN1 = function () {
var BERtypes = {
0x00: 'EOC',
0x01: 'BOOLEAN',
0x02: 'INTEGER',
0x03: 'BIT STRING',
0x04: 'OCTET STRING',
0x05: 'NULL',
0x06: 'OBJECT IDENTIFIER',
0x07: 'ObjectDescriptor',
0x08: 'EXTERNAL',
0x09: 'REAL',
0x0A: 'ENUMERATED',
0x0B: 'EMBEDDED PDV',
0x0C: 'UTF8String',
0x10: 'SEQUENCE',
0x11: 'SET',
0x12: 'NumericString',
0x13: 'PrintableString',
// ASCII subset
0x14: 'TeletexString',
// aka T61String
0x15: 'VideotexString',
0x16: 'IA5String',
// ASCII
0x17: 'UTCTime',
0x18: 'GeneralizedTime',
0x19: 'GraphicString',
0x1A: 'VisibleString',
// ASCII subset
0x1B: 'GeneralString',
0x1C: 'UniversalString',
0x1E: 'BMPString'
};
function hex(start, buffer) {
var s = '',
d = new Uint8Array(buffer);
for (var i = 0; i < d.length; i++) {
s += (i % 16 === 0 ? (i > 0 ? '</b>' : '') + '\r\n' + start + '<b>' : ' ') + ('00' + d[i].toString(16)).slice(-2);
}
return s ? s + '</b>' : '';
}
function childs(block, offset, ident) {
var s = '',
start = ' : ';
if (block.object.length > 0) {
s += ' {\r\n';
block.object.forEach(function (child) {
s += process(child, offset, ident + ' ');
offset += child.header.length + child.content.length;
});
s += start + ident + '}';
} else s += ' {}';
return s;
}
function process(block, offset, ident) {
if (block.tagClass > 2) throw new Error('Private and Application tags is not supported');
offset = offset || 0;
ident = ident || ''; // type name
var typeName = block.tagClass === 1 ? 'Application_' + block.tagNumber : block.tagClass === 2 ? '[' + block.tagNumber.toString() + ']' : // Context
block.tagClass === 3 ? 'Private_' + block.tagNumber : BERtypes[block.tagNumber] || "Universal_" + block.tagNumber.toString();
var start = ' : ',
s = (' ' + offset).slice(-5) + ' ' + ('00' + block.header[0].toString(16)).slice(-2) + (' ' + block.content.length).slice(-5) + ': ' + ident + typeName;
if (block.tagConstructed) s += childs(block, offset + block.header.length, ident);else switch (typeName.toUpperCase()) {
case 'OBJECT IDENTIFIER':
var id = block.object,
name = names[id];
s += ' <b>' + (name ? name : '?') + '</b> (' + id + ')';
break;
case 'INTEGER':
case 'ENUMERATED':
if (typeof block.object === 'number') {
s += ' <b>' + block.object + '</b>';
} else s += hex(start + ident + ' ', block.content);
break;
case 'GENERALIZEDTIME':
case 'UTCTIME':
s += ' <b>' + block.object + '</b>';
break;
case 'PRINTABLESTRING':
case 'IA5STRING':
case 'VISIBLESTRING':
case 'VIDEOTEXSTRING':
case 'NUMERICSTRING':
case 'BMPSTRING':
case 'UTF8STRING':
case 'UNIVERSALSTRING':
s += ' <b>"' + block.object + '"</b>';
break;
case 'BOOLEAN':
s += ' <b>' + (block.object ? 'true' : 'false') + '</b>';
break;
case 'OCTET STRING':
try {
s += ', encapsulates' + childs({
object: [coding.BER.decode(block.content)]
}, offset + block.header.length, ident);
} catch (e) {
s += hex(start + ident + ' ', block.content);
}
break;
case 'BIT STRING':
s += ', unused ' + block.content[0] + ' bits';
if (block.object instanceof ArrayBuffer) {
try {
s += ', encapsulates' + childs({
object: [coding.BER.decode(block.object)]
}, offset + block.header.length, ident);
} catch (e) {
s += hex(start + ident + ' ', block.object);
}
} else s += '\r\n' + start + ident + ' <b>' + block.object + 'B</b>';
break;
default:
try {
s += ', encapsulates' + childs({
object: [coding.BER.decode(block.content)]
}, offset + block.header.length, ident);
} catch (e) {
s += hex(start + ident + ' ', block.content);
}
}
return s + '\r\n';
}
return function (value) {
if (typeof value === 'string' || value instanceof String) {
// text
var t = /([A-Fa-f0-9\s]+)/g.exec(value);
if (t && t[1].length === value.length) // Hex format
value = coding.Hex.decode(value);else // PEM format
value = coding.PEM.decode(value);
} else {
// binary
try {
value = coding.PEM.decode(coding.Chars.encode(value, 'ascii'));
} catch (e) {}
}
return process(coding.BER.decode(value));
};
}();
var printSyntax = function () {
function process(value, ident) {
ident = ident || '';
if (typeof value === 'undefined') return '<b>undefined</b>';else if (value instanceof Array) {
var r = [],
l = 0;
for (var i = 0, n = value.length; i < n; i++) {
r[i] = process(value[i], ident + ' ');
l += r[i].replace(/\<[^\>]+\>/g, '').length + 2;
}
if (l > 80) {
var s = '[',
m = 0;
for (var i = 0, n = r.length; i < n; i++) {
s += (i > 0 ? ', ' : '') + (m === 0 && l > 80 ? '\r\n' + ident + ' ' : ' ') + r[i];
m += r[i].replace(/\<[^\>]+\>/g, '').length + 2;
if (m > 80) m = 0;
}
s += l > 80 ? '\r\n' + ident + ']' : ' ]';
return s;
} else return '[ ' + r.join(', ') + ' ]';
} else if (typeof value === 'string' || value instanceof String) {
if (value.toString() === '') // null
return '<b>null</b>';else return '<b>"' + value.replace(/([\"])/g, '\\$1') + '"</b>';
} else if (typeof value === 'number' || value instanceof Number) {
return '<b>' + value + '</b>';
} else if (value instanceof Date) {
return '<b>' + JSON.stringify(value) + '</b>';
} else if (typeof value === 'boolean' || value instanceof Boolean) {
return '<b>' + value + '</b>';
} else if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
var d = new Uint8Array(value);
var s = '';
for (var i = 0, n = d.length; i < n; i++) {
s += (i > 0 && i % 16 === 0 ? '\r\n' + ident + ' ' : ' ') + '<b>0x' + ('00' + d[i].toString(16)).slice(-2) + '</b>' + (i < n - 1 ? ',' : '');
}
if (d.length > 16) return '[\r\n' + ident + ' ' + s + '\r\n' + ident + ']';else return '[' + s + ' ]';
} else if (_typeof(value) === 'object') {
var first = true;
var s = '{';
for (var name in value) {
if (typeof value[name] === 'function' || value[name] === undefined) continue;
var norm = /^[a-zA-Z\_][a-zA-Z0-9\_]*$/.test(name);
if (first) first = false;else s += ',';
s += '\r\n' + ident + ' ' + (norm ? '' : '"') + name + (norm ? '' : '"') + ': ' + process(value[name], ident + ' ');
}
s += (first ? '' : '\r\n' + ident) + '}';
return s;
}
return 'unrecognized';
}
return function (value, type) {
if (typeof value === 'string' || value instanceof String) {
// text
var t = /([A-Fa-f0-9\s]+)/g.exec(value);
if (t && t[1].length === value.length) // Hex format
value = coding.Hex.decode(value);else // PEM format
value = coding.PEM.decode(value);
} else {
// binary
try {
value = coding.PEM.decode(coding.Chars.encode(value, 'ascii'));
} catch (e) {}
}
if (type) {
return process(asn1[type].decode(value));
} else return process(coding.BER.decode(value));
};
}();
function open(header, content, item) {
var el = document.getElementById('print');
if (el) el.parentNode.removeChild(el);
el = document.createElement('div');
el.id = 'print';
el.innerHTML = '<span class="label">' + header + '</span>' + '<pre class="encoded">' + content + '</pre>' + '<button onclick="(function(x){x.parentNode.removeChild(x);})(document.getElementById(\'print\'))">Close View</button>';
var next = item.nextElementSibling;
while (next.nodeName.toLowerCase() === 'button') {
next = next.nextElementSibling;
}
next.parentNode.insertBefore(el, next);
}
function openASN1(item) {
open('ASN.1 Data', printASN1(item.textContent), item);
}
function openSyntax(item, type) {
open('Syntax ' + (type ? 'gostCrypto.asn1.' + type + '.decode(value):' : 'gostCrypto.coding.PEM.decode(value):'), printSyntax(item.textContent, type), item);
}
return {
printASN1: printASN1,
printSyntax: printSyntax,
openASN1: openASN1,
openSyntax: openSyntax
};
});
},{"./gostASN1":105,"./gostCoding":109,"./gostCrypto":110,"./gostSecurity":115}],118:[function(require,module,exports){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hexadecimalToUint8Array = hexadecimalToUint8Array;
exports.hexadecimalToBinaryString = hexadecimalToBinaryString;
exports.uint8ArrayToHexadecimal = uint8ArrayToHexadecimal;
exports.uint8ArrayToBinaryString = uint8ArrayToBinaryString;
exports.binaryStringToUint8Array = binaryStringToUint8Array;
exports.binaryStringToHexadecimal = binaryStringToHexadecimal;
exports.stringToUint8Array = stringToUint8Array;
var validate = _interopRequireWildcard(require("../types/validate"));
/**
* Convert hexadecimal string into uint8Array
* @param {string} str
* @returns {Uint8Array}
*/
function hexadecimalToUint8Array(str) {
if (typeof str !== 'string') {
throw new TypeError('Wrong data type passed to convertor. Hexadecimal string is expected');
}
if (!validate.validateHexadecimal(str, str.length / 2)) {
throw new TypeError('String of wrong type is passed. Hexadecimal expected.');
}
var uint8arr = new Uint8Array(str.length / 2);
for (var i = 0, j = 0; i < str.length; i += 2, j++) {
uint8arr[j] = parseInt(str.substr(i, 2), 16);
}
return uint8arr;
}
/**
* Convert hexadecimal string into binary string
* @param {string} str
* @returns {string}
*/
function hexadecimalToBinaryString(str) {
var binaryStr = '';
if (typeof str !== 'string') {
throw new TypeError('Wrong data type passed to convertor. Hexadecimal string is expected');
}
if (!validate.validateHexadecimal(str, Math.ceil(str.length / 2))) {
throw new TypeError('String of wrong type is passed. Hexadecimal expected.');
}
var prevBin = null;
for (var i = 0; i < str.length; i++) {
var bin = strReverse(parseInt(str[i], 16).toString(2));
while (bin.length < 4) {
bin = bin + '0';
}
if (!prevBin) {
prevBin = bin;
} else {
binaryStr += bin + prevBin;
prevBin = null;
}
}
return binaryStr;
}
/**
* Convert uint8Array into string
* @param {Uint8Array} uint8arr
* @returns {string}
*/
function uint8ArrayToHexadecimal(uint8arr) {
var str = '';
if (!(uint8arr instanceof Uint8Array)) {
throw new TypeError('Wrong data type of array of 8-bit integers. Uint8Array is expected');
}
for (var i = 0; i < uint8arr.length; i++) {
var hex = uint8arr[i].toString(16);
hex = hex.length === 1 ? '0' + hex : hex;
str += hex;
}
return str.toLowerCase();
}
/**
* Convert uint8Array into binary string
* @param {Uint8Array} uint8arr
* @returns {string}
*/
function uint8ArrayToBinaryString(uint8arr) {
var binaryStr = '';
if (!(uint8arr instanceof Uint8Array)) {
throw new TypeError('Wrong data type of array of 8-bit integers. Uint8Array is expected');
}
for (var i = 0; i < uint8arr.length; i++) {
var bin = strReverse(uint8arr[i].toString(2));
while (bin.length < 8) {
bin = bin + '0';
}
binaryStr += bin;
}
return binaryStr;
}
/**
* Convert binary string into uint8Array
* @param {string} binaryStr
* @returns {Uint8Array}
*/
function binaryStringToUint8Array(binaryStr) {
var array = [];
if (typeof binaryStr !== 'string') {
throw new TypeError('Wrong data type passed to convertor. Binary string is expected');
}
if (!validate.validateBinaryString(binaryStr)) {
throw new TypeError('String of wrong type is passed. Binary string expected.');
}
for (var i = 0; i < binaryStr.length; i += 8) {
array.push(parseInt(strReverse(binaryStr.substr(i, 8)), 2));
}
return new Uint8Array(array);
}
/**
* Convert string into reverse string
* @param str
* @returns {string}
*/
function strReverse(str) {
return str.split('').reverse().join('');
}
/**
* Convert binary string into hexadecimal string
* @param {string} binaryStr
* @returns {string}
*/
function binaryStringToHexadecimal(binaryStr) {
var str = '';
if (typeof binaryStr !== 'string') {
throw new TypeError('Wrong data type passed to convertor. Binary string is expected');
}
if (!validate.validateBinaryString(binaryStr)) {
throw new TypeError('String of wrong type is passed. Binary string expected.');
}
for (var i = 0; i < binaryStr.length; i += 8) {
var hex = parseInt(strReverse(binaryStr.substr(i, 8)), 2).toString(16);
hex = hex.length === 1 ? '0' + hex : hex;
str += hex;
}
return str.toLowerCase();
}
/**
* Convert sting into uint8Array
* @param {string} str
* @param {number} [len] - optional
* @returns {Uint8Array}
*/
function stringToUint8Array(str, len) {
var array;
var from = 0;
if (typeof str !== 'string') {
throw new TypeError('Wrong data type passed to convertor. String is expected');
}
if (len > 0) {
array = new Array(len);
array.fill(0);
} else {
array = [];
}
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c < 128) {
array[from++] = c;
} else if (c < 2048) {
array[from++] = c >> 6 | 192;
array[from++] = c & 63 | 128;
} else if ((c & 0xFC00) === 0xD800 && i + 1 < str.length && (str.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
// surrogate pair
c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
array[from++] = c >> 18 | 240;
array[from++] = c >> 12 & 63 | 128;
array[from++] = c >> 6 & 63 | 128;
array[from++] = c & 63 | 128;
} else {
array[from++] = c >> 12 | 224;
array[from++] = c >> 6 & 63 | 128;
array[from++] = c & 63 | 128;
}
}
return new Uint8Array(array);
}
},{"../types/validate":124,"@babel/runtime/helpers/interopRequireWildcard":12}],119:[function(require,module,exports){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newType = newType;
exports.isType = isType;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var crypto = _interopRequireWildcard(require("../crypto"));
var _helpers = require("../helpers");
/**
* @constructor
* @param {Object} schema
*/
var Type =
/*#__PURE__*/
function () {
function Type(schema) {
(0, _classCallCheck2["default"])(this, Type);
this.schema = schema;
}
/**
* Serialize data into array of 8-bit integers
* @param {Object} data
* @returns {Uint8Array}
*/
(0, _createClass2["default"])(Type, [{
key: "serialize",
value: function serialize(data) {
var object = (0, _helpers.cleanZeroValuedFields)(data, {});
return this.schema.encode(object).finish();
}
/**
* Get SHA256 hash
* @param {Object} data
* @returns {string}
*/
}, {
key: "hash",
value: function hash(data) {
return crypto.hash(data, this);
}
/**
* Get ED25519 signature
* @param {string} secretKey
* @param {Object} data
* @returns {string}
*/
}, {
key: "sign",
value: function sign(secretKey, data) {
return crypto.sign(secretKey, data, this);
}
/**
* Verifies ED25519 signature
* @param {string} signature
* @param {string} publicKey
* @param {Object} data
* @returns {boolean}
*/
}, {
key: "verifySignature",
value: function verifySignature(signature, publicKey, data) {
return crypto.verifySignature(signature, publicKey, data, this);
}
}]);
return Type;
}();
/**
* Create element of Type class
* @param {Object} type
* @returns {Type}
*/
function newType(type) {
return new Type(type);
}
/**
* Check if passed object is of type Type
* @param {Object} type
* @returns {boolean}
*/
function isType(type) {
return type instanceof Type;
}
},{"../crypto":100,"../helpers":102,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":7,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/interopRequireWildcard":12}],120:[function(require,module,exports){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PublicKey = exports.Digest = exports.Hash = exports.Uuid = void 0;
var validate = _interopRequireWildcard(require("./validate"));
var _crypto = require("../crypto");
/**
* Encoder
*
* @param {string} str string to encode
* @param {Array} buffer buffer to place result to
* @param {number} from position to write from
* @returns {Array} modified buffer
* @private
*/
function insertHexadecimalToByteArray(str, buffer, from) {
for (var i = 0; i < str.length; i += 2) {
buffer[from] = parseInt(str.substr(i, 2), 16);
from++;
}
return buffer;
}
/**
* Validator wrapper
*
* @param {string} name structure name
* @param {number} size value size in bytes
* @param {string} value value representation
* @returns {string} value if validation passes
* @throws {TypeError} in case of validation break
* @private
*/
function validateHexadecimal(name, size, value) {
if (!validate.validateHexadecimal(value, size)) {
throw new TypeError("".concat(name, " of wrong type is passed: ").concat(value));
}
return value;
}
/**
* Factory for building Hex Types
*
* @param {function(value, buffer, from)} serizalizer function accepting value, buffer, position and returns modified buffer
* @param {function() => number} sizeGetter a function, that returns the size of a type in bytes
* @param {string} name type name to distinguish between types
* @returns {Object} hex type
*/
function hexTypeFactory(serizalizer, sizeGetter, name) {
return Object.defineProperties({}, {
size: {
get: function get() {
return sizeGetter;
},
enumerable: true
},
name: {
get: function get() {
return name;
},
enumerable: true
},
serialize: {
get: function get() {
return serizalizer;
}
}
});
}
/**
* Common serializer
*
* @param {function(name, size, value)} validator hexadecimal validator
* @param {function(value, buffer, from)} encoder function accepting value, buffer, position and returns modified buffer
* @returns {function(value, buffer, from)} encoder wrapper
* @throws {TypeError} in case of validation break
* @private
*/
function serializer(encoder, validator) {
return function (value, buffer, from) {
return encoder(validator(value), buffer, from);
};
}
/**
* Uuid type factory
*
* @param {function(name, size, value)} validator hexadecimal validator
* @param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
* @param {function(serizalizer, size, name)} factory type builder factory
* @returns {Object} hex type
* @private
*/
function Uuid(validator, serializer, factory) {
var size = 16;
var name = 'Uuid';
function cleaner(value) {
return String(value).replace(/-/g, '');
}
validator = validator.bind(null, name, size);
serializer = serializer(function (value) {
return validator(cleaner(value));
});
return factory(serializer, function () {
return size;
}, name);
}
/**
* Hash type factory
*
* @param {function(name, size, value)} validator hexadecimal validator
* @param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
* @param {function(serizalizer, size, name)} factory type builder factory
* @returns {Object} hex type
* @private
*/
function Hash(validator, serializer, factory) {
var size = _crypto.HASH_LENGTH;
var name = 'Hash';
validator = validator.bind(null, name, size);
serializer = serializer(validator);
var hasher = function hasher(value) {
return validator(value) && value;
};
return Object.defineProperty(factory(serializer, _crypto.HASH_LENGTH, name), 'hash', {
value: hasher
});
}
/**
* Digest type factory
*
* @param {function(name, size, value)} validator hexadecimal validator
* @param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
* @param {function(serizalizer, size, name)} factory type builder factory
* @returns {Object} hex type
* @private
*/
function Digest(validator, serializer, factory) {
var size = 64;
var name = 'Digest';
validator = validator.bind(null, name, size);
serializer = serializer(validator);
return factory(serializer, function () {
return size;
}, name);
}
/**
* PublicKey type factory
*
* @param {function(name, size, value)} validator hexadecimal validator
* @param {function(validator, value, buffer, from)} encoder function accepting validator, value, buffer, position and returns modified buffer
* @param {function(serizalizer, size, name)} factory type builder factory
* @returns {Object} hex type
* @private
*/
function PublicKey(validator, serializer, factory) {
var name = 'PublicKey';
var boundValidator = function boundValidator(value) {
return validator(name, _crypto.PUBLIC_KEY_LENGTH, value);
};
serializer = serializer(boundValidator);
return factory(serializer, function () {
return _crypto.PUBLIC_KEY_LENGTH;
}, name);
}
var baseSerializer = serializer.bind(null, insertHexadecimalToByteArray);
var uuid = Uuid(validateHexadecimal, baseSerializer, hexTypeFactory);
exports.Uuid = uuid;
var hash = Hash(validateHexadecimal, baseSerializer, hexTypeFactory);
exports.Hash = hash;
var digest = Digest(validateHexadecimal, baseSerializer, hexTypeFactory);
exports.Digest = digest;
var publicKey = PublicKey(validateHexadecimal, baseSerializer, hexTypeFactory);
exports.PublicKey = publicKey;
},{"../crypto":100,"./validate":124,"@babel/runtime/helpers/interopRequireWildcard":12}],121:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _primitive = require("./primitive");
Object.keys(_primitive).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _primitive[key];
}
});
});
var _generic = require("./generic");
Object.keys(_generic).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _generic[key];
}
});
});
var _message = require("./message");
Object.keys(_message).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _message[key];
}
});
});
var _convert = require("./convert");
Object.keys(_convert).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _convert[key];
}
});
});
var _hexadecimal = require("./hexadecimal");
Object.keys(_hexadecimal).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _hexadecimal[key];
}
});
});
},{"./convert":118,"./generic":119,"./hexadecimal":120,"./message":122,"./primitive":123}],122:[function(require,module,exports){
(function (global,Buffer){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.chainIdToBytes = chainIdToBytes;
exports.isTransaction = isTransaction;
exports.Transaction = exports.Verified = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var crypto = _interopRequireWildcard(require("../crypto"));
var _helpers = require("../helpers");
var protobuf = _interopRequireWildcard(require("../../proto/protocol.js"));
var _convert = require("./convert");
var _protobuf$exonum$cons = protobuf.exonum.consensus,
CoreMessage = _protobuf$exonum$cons.CoreMessage,
SignedMessage = _protobuf$exonum$cons.SignedMessage;
function chainIdToBytes(chainId) {
var bigChainId = global.BigInt(chainId);
var chainIdBytes = new Uint8Array(8);
for (var x = 0; x < 8; x++) {
chainIdBytes.set([Number(bigChainId >> global.BigInt(8) * global.BigInt(x) & global.BigInt(255))], x);
}
return chainIdBytes;
}
var Verified =
/*#__PURE__*/
function () {
function Verified(schema, chainId, payload, author, signature) {
(0, _classCallCheck2["default"])(this, Verified);
if (chainId.length === 8) {
this.chainIdBytes = chainId;
} else {
this.chainIdBytes = chainIdToBytes(chainId);
}
this.schema = schema;
this.payload = payload;
this.author = author;
this.signature = signature;
this.bytes = SignedMessage.encode({
chain_id_bytes: this.chainIdBytes,
payload: schema.encode(payload).finish(),
author: {
data: (0, _convert.hexadecimalToUint8Array)(author)
},
signature: {
data: (0, _convert.hexadecimalToUint8Array)(signature)
}
}).finish();
}
(0, _createClass2["default"])(Verified, [{
key: "serialize",
value: function serialize() {
return this.bytes;
}
/**
* Gets the SHA-256 digest of the message.
* @returns {string}
*/
}, {
key: "hash",
value: function hash() {
var payloadBuffer = this.schema.encode(this.payload).finish();
var chainIdBytesBuffer = this.chainIdBytes;
var authorBuffer = (0, _convert.hexadecimalToUint8Array)(this.author);
var buffer = Buffer.concat([chainIdBytesBuffer, payloadBuffer, authorBuffer]);
return crypto.hash(buffer);
}
}], [{
key: "sign",
value: function () {
var _sign = (0, _asyncToGenerator2["default"])(
/*#__PURE__*/
_regenerator["default"].mark(function _callee(schema, chainId, payload, _ref) {
var publicKey, secretKey, signingKey, chainIdBytes, payloadBuf, signature;
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
publicKey = _ref.publicKey, secretKey = _ref.secretKey;
signingKey = secretKey;
chainIdBytes = chainIdToBytes(chainId);
payloadBuf = schema.encode(payload).finish();
_context.next = 6;
return crypto.sign(signingKey, Buffer.concat([chainIdBytes, payloadBuf]));
case 6:
signature = _context.sent;
return _context.abrupt("return", new this(schema, chainId, payload, publicKey, signature));
case 8:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function sign(_x, _x2, _x3, _x4) {
return _sign.apply(this, arguments);
}
return sign;
}()
}, {
key: "deserialize",
value: function deserialize(schema, bytes) {
var _SignedMessage$decode = SignedMessage.decode(bytes),
payload = _SignedMessage$decode.payload,
rawAuthor = _SignedMessage$decode.author,
rawSignature = _SignedMessage$decode.signature,
chainIdBytes = _SignedMessage$decode.chain_id_bytes;
if (!crypto.verifySignature((0, _convert.uint8ArrayToHexadecimal)(rawSignature.data), (0, _convert.uint8ArrayToHexadecimal)(rawAuthor.data), payload)) {
return null;
} else {
var decoded = schema.decode(payload);
var author = (0, _convert.uint8ArrayToHexadecimal)(rawAuthor.data);
var signature = (0, _convert.uint8ArrayToHexadecimal)(rawSignature.data);
return new this(schema, chainIdBytes, decoded, author, signature);
}
}
}]);
return Verified;
}();
/**
* @constructor
* @param {Object} type
*/
exports.Verified = Verified;
var Transaction =
/*#__PURE__*/
function () {
function Transaction(_ref2) {
var schema = _ref2.schema,
serviceId = _ref2.serviceId,
methodId = _ref2.methodId,
chainId = _ref2.chainId;
(0, _classCallCheck2["default"])(this, Transaction);
this.serviceId = serviceId;
this.methodId = methodId;
this.schema = schema;
this.chainId = chainId || 0;
}
/**
* Creates a signature transaction.
*
* @param {bigint} chainId
* chain identifier
* @param {Object} payload
* transaction payload
* @param {Uint8Array | {publicKey: string, secretKey: string}} authorOrKeypair
* author or keypair
* @param {Uint8Array?} signature
* transaction signature
* @returns {Verified}
* signature transaction message
*/
(0, _createClass2["default"])(Transaction, [{
key: "create",
value: function create(payload, authorOrKeypair, signature) {
var fullPayload = this._serializePayload(payload);
if (signature === undefined) {
return Verified.sign(CoreMessage, this.chainId, fullPayload, authorOrKeypair);
} else {
return new Verified(CoreMessage, this.chainId, fullPayload, authorOrKeypair, signature);
}
}
}, {
key: "_serializePayload",
value: function _serializePayload(payload) {
var args = this.schema.encode((0, _helpers.cleanZeroValuedFields)(payload, {})).finish();
var transaction = {
call_info: {
instance_id: this.serviceId,
method_id: this.methodId
},
arguments: args
};
return {
any_tx: transaction
};
}
}, {
key: "serialize",
value: function serialize(payload) {
return CoreMessage.encode(this._serializePayload(payload)).finish();
}
}, {
key: "deserialize",
value: function deserialize(bytes) {
var verified = Verified.deserialize(CoreMessage, bytes);
if (!verified) {
return null;
}
var payload = verified.payload.any_tx;
if (!payload) {
return null;
}
if (payload.call_info.instance_id !== this.serviceId || payload.call_info.method_id !== this.methodId) {
return null;
}
verified.payload = this.schema.decode(payload.arguments);
return verified;
}
}]);
return Transaction;
}();
/**
* Check if passed object is of type Transaction
* @param type
* @returns {boolean}
*/
exports.Transaction = Transaction;
function isTransaction(type) {
return type instanceof Transaction;
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"../../proto/protocol.js":89,"../crypto":100,"../helpers":102,"./convert":118,"@babel/runtime/helpers/asyncToGenerator":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":7,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/interopRequireWildcard":12,"@babel/runtime/regenerator":24,"buffer":62}],123:[function(require,module,exports){
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Bool = exports.Uint64 = exports.Uint32 = exports.Uint16 = exports.Uint8 = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _bigInteger = _interopRequireDefault(require("big-integer"));
var validate = _interopRequireWildcard(require("./validate"));
var MAX_UINT8 = 255;
var MAX_UINT16 = 65535;
var MAX_UINT32 = 4294967295;
var MAX_UINT64 = 18446744073709551615;
/**
* Insert number into array as little-endian or big-endian
* @param {number|bigInt} number
* @param {Array} buffer
* @param {number} from
* @param {number} size
* @param {boolean} isBigEndian
* @returns {Array}
*/
function insertIntegerToByteArray(number, buffer, from, size) {
var isBigEndian = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
var value = (0, _bigInteger["default"])(number); // convert a number-like object into a big integer
for (var pos = isBigEndian ? size - 1 : 0; isBigEndian ? pos >= 0 : pos < size; isBigEndian ? pos-- : pos++) {
var divmod = value.divmod(256);
buffer[from + pos] = divmod.remainder.toJSNumber();
value = divmod.quotient;
}
return buffer;
}
var Uint8 =
/*#__PURE__*/
function () {
function Uint8() {
(0, _classCallCheck2["default"])(this, Uint8);
}
(0, _createClass2["default"])(Uint8, null, [{
key: "size",
value: function size() {
return 1;
}
/**
* @param {number} value
* @param {Array} buffer
* @param {number} from
* @returns {Array}
*/
}, {
key: "serialize",
value: function serialize(value, buffer, from) {
if (!validate.validateInteger(value, 0, MAX_UINT8, from, this.size())) {
throw new TypeError('Uint8 of wrong type is passed: ' + value);
}
return insertIntegerToByteArray(value, buffer, from, this.size());
}
}]);
return Uint8;
}();
exports.Uint8 = Uint8;
var Uint16 =
/*#__PURE__*/
function () {
function Uint16() {
(0, _classCallCheck2["default"])(this, Uint16);
}
(0, _createClass2["default"])(Uint16, null, [{
key: "size",
value: function size() {
return 2;
}
/**
* @param {number} value
* @param {Array} buffer
* @param {number} from
* @param {boolean} isBigEndian
* @returns {Array}
*/
}, {
key: "serialize",
value: function serialize(value, buffer, from, isBigEndian) {
if (!validate.validateInteger(value, 0, MAX_UINT16, from, this.size())) {
throw new TypeError('Uint16 of wrong type is passed: ' + value);
}
return insertIntegerToByteArray(value, buffer, from, this.size(), isBigEndian);
}
}]);
return Uint16;
}();
exports.Uint16 = Uint16;
var Uint32 =
/*#__PURE__*/
function () {
function Uint32() {
(0, _classCallCheck2["default"])(this, Uint32);
}
(0, _createClass2["default"])(Uint32, null, [{
key: "size",
value: function size() {
return 4;
}
/**
* @param {number} value
* @param {Array} buffer
* @param {number} from
* @param {boolean} isBigEndian
* @returns {Array}
*/
}, {
key: "serialize",
value: function serialize(value, buffer, from, isBigEndian) {
if (!validate.validateInteger(value, 0, MAX_UINT32, from, this.size())) {
throw new TypeError('Uint32 of wrong type is passed: ' + value);
}
return insertIntegerToByteArray(value, buffer, from, this.size(), isBigEndian);
}
}]);
return Uint32;
}();
exports.Uint32 = Uint32;
var Uint64 =
/*#__PURE__*/
function () {
function Uint64() {
(0, _classCallCheck2["default"])(this, Uint64);
}
(0, _createClass2["default"])(Uint64, null, [{
key: "size",
value: function size() {
return 8;
}
/**
* @param {number} value
* @param {Array} buffer
* @param {number} from
* @param {boolean} isBigEndian
* @returns {Array}
*/
}, {
key: "serialize",
value: function serialize(value, buffer, from, isBigEndian) {
if (!validate.validateInteger(value, 0, MAX_UINT64, from, this.size())) {
throw new TypeError('Uint16 of wrong type is passed: ' + value);
}
return insertIntegerToByteArray(value, buffer, from, this.size(), isBigEndian);
}
}]);
return Uint64;
}();
exports.Uint64 = Uint64;
var Bool =
/*#__PURE__*/
function () {
function Bool() {
(0, _classCallCheck2["default"])(this, Bool);
}
(0, _createClass2["default"])(Bool, null, [{
key: "size",
value: function size() {
return 1;
}
/**
* @param {boolean} value
* @param {Array} buffer
* @param {number} from
* @returns {Array}
*/
}, {
key: "serialize",
value: function serialize(value, buffer, from) {
if (typeof value !== 'boolean') {
throw new TypeError('Wrong data type is passed as Boolean. Boolean is required');
}
return insertIntegerToByteArray(value ? 1 : 0, buffer, from, this.size());
}
}]);
return Bool;
}();
exports.Bool = Bool;
},{"./validate":124,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":7,"@babel/runtime/helpers/interopRequireDefault":11,"@babel/runtime/helpers/interopRequireWildcard":12,"big-integer":59}],124:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.validateInteger = validateInteger;
exports.validateHexadecimal = validateHexadecimal;
exports.validateBytesArray = validateBytesArray;
exports.validateBinaryString = validateBinaryString;
/**
* @param {number} value
* @param {number} min
* @param {number} max
* @param {number} from
* @param {number} length
* @returns {boolean}
*/
function validateInteger(value, min, max, from, length) {
if (typeof value !== 'number' || value < min || value > max) {
return false;
}
return true;
}
/**
* @param {string} hash
* @param {number} [bytes=32] - optional
* @returns {boolean}
*/
function validateHexadecimal(hash, bytes) {
bytes = bytes || 32;
if (typeof hash !== 'string') {
return false;
}
if (hash.length !== bytes * 2) {
// 'hexadecimal string is of wrong length
return false;
}
for (var i = 0; i < hash.length; i++) {
if (isNaN(parseInt(hash[i], 16))) {
// invalid symbol in hexadecimal string
return false;
}
}
return true;
}
/**
* @param {Array} arr
* @param {number} [bytes] - optional
* @returns {boolean}
*/
function validateBytesArray(arr, bytes) {
if (!Array.isArray(arr) && !(arr instanceof Uint8Array)) {
return false;
}
if (bytes && arr.length !== bytes) {
// array is of wrong length
return false;
}
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] !== 'number' || arr[i] < 0 || arr[i] > 255) {
return false;
}
}
return true;
}
/**
* @param {string} str
* @param {number} [bits] - optional
* @returns {*}
*/
function validateBinaryString(str, bits) {
if (bits !== undefined && str.length !== bits) {
return false;
}
for (var i = 0; i < str.length; i++) {
if (str[i] !== '0' && str[i] !== '1') {
// wrong bit
return false;
}
}
return true;
}
},{}]},{},[103])(103)
});