madeline-ton
Version:
Pure JS client-side implementation of the Telegram TON blockchain protocol
87 lines (68 loc) • 2.48 kB
JavaScript
;
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 _long = _interopRequireDefault(require("../lib/bigint/long"));
var MessageIdHandler =
/*#__PURE__*/
function () {
function MessageIdHandler() {
(0, _classCallCheck2["default"])(this, MessageIdHandler);
this.maxIncoming = new _long["default"](0, 0);
this.maxOutgoing = new _long["default"](0, 0);
}
/**
* Check incoming message ID
* @param {number[]} id
* @param {boolean} container Whether the message ID is from a container
* @returns Long
*/
(0, _createClass2["default"])(MessageIdHandler, [{
key: "check",
value: function check(id, container) {
id = new _long["default"](id[0], id[1]);
var min = new _long["default"](0, Date.now() / 1000 - 300);
if (min.compare(id) > 0) {
throw new Error("Given message ID (".concat(id, ") is too old compared to the min value (").concat(min, ")"));
}
var max = new _long["default"](0, Date.now() / 1000 + 30);
if (max.compare(id) < 0) {
throw new Error("Given message ID (".concat(id, ") is too new compared to the max value (").concat(max, ")"));
}
var and = id.and(_long["default"].THREE);
if (and.high_ !== 0 && and.low_ !== 1 && and.low_ !== 3) {
throw new Error("Given message ID mod 4 != 1 or 3");
}
if (container) {
if (id.compare(this.maxIncoming) >= 0) {
throw new Error("Wrong container message ID (".concat(id, ")"));
}
} else {
if (id.compare(this.maxIncoming) <= 0) {
throw new Error("Duplicate message ID (".concat(id, ")"));
}
}
return this.maxIncoming = id;
}
/**
* Generate outgoing message ID
* @returns Long
*/
}, {
key: "generate",
value: function generate() {
var id = new _long["default"](0, Date.now() / 1000);
if (id.compare(this.maxOutgoing) <= 0) {
id = this.maxOutgoing.add(_long["default"].FOUR);
}
return this.maxOutgoing = id;
}
}]);
return MessageIdHandler;
}();
var _default = MessageIdHandler;
exports["default"] = _default;