ethereumjs-util
Version:
A collection of utility functions for Ethereum
333 lines • 10.8 kB
JavaScript
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufArrToArr = exports.arrToBufArr = exports.validateNoLeadingZeroes = exports.baToJSON = exports.toUtf8 = exports.addHexPrefix = exports.toUnsigned = exports.fromSigned = exports.bufferToHex = exports.bufferToInt = exports.toBuffer = exports.unpadHexString = exports.unpadArray = exports.unpadBuffer = exports.setLengthRight = exports.setLengthLeft = exports.zeros = exports.intToBuffer = exports.intToHex = void 0;
var externals_1 = require("./externals");
var internal_1 = require("./internal");
var helpers_1 = require("./helpers");
/**
* Converts a `Number` into a hex `String`
* @param {Number} i
* @return {String}
*/
var intToHex = function (i) {
if (!Number.isSafeInteger(i) || i < 0) {
throw new Error("Received an invalid integer type: ".concat(i));
}
return "0x".concat(i.toString(16));
};
exports.intToHex = intToHex;
/**
* Converts an `Number` to a `Buffer`
* @param {Number} i
* @return {Buffer}
*/
var intToBuffer = function (i) {
var hex = (0, exports.intToHex)(i);
return Buffer.from((0, internal_1.padToEven)(hex.slice(2)), 'hex');
};
exports.intToBuffer = intToBuffer;
/**
* Returns a buffer filled with 0s.
* @param bytes the number of bytes the buffer should be
*/
var zeros = function (bytes) {
return Buffer.allocUnsafe(bytes).fill(0);
};
exports.zeros = zeros;
/**
* Pads a `Buffer` with zeros till it has `length` bytes.
* Truncates the beginning or end of input if its length exceeds `length`.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @param right whether to start padding form the left or right
* @return (Buffer)
*/
var setLength = function (msg, length, right) {
var buf = (0, exports.zeros)(length);
if (right) {
if (msg.length < length) {
msg.copy(buf);
return buf;
}
return msg.slice(0, length);
}
else {
if (msg.length < length) {
msg.copy(buf, length - msg.length);
return buf;
}
return msg.slice(-length);
}
};
/**
* Left Pads a `Buffer` with leading zeros till it has `length` bytes.
* Or it truncates the beginning if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
var setLengthLeft = function (msg, length) {
(0, helpers_1.assertIsBuffer)(msg);
return setLength(msg, length, false);
};
exports.setLengthLeft = setLengthLeft;
/**
* Right Pads a `Buffer` with trailing zeros till it has `length` bytes.
* it truncates the end if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
var setLengthRight = function (msg, length) {
(0, helpers_1.assertIsBuffer)(msg);
return setLength(msg, length, true);
};
exports.setLengthRight = setLengthRight;
/**
* Trims leading zeros from a `Buffer`, `String` or `Number[]`.
* @param a (Buffer|Array|String)
* @return (Buffer|Array|String)
*/
var stripZeros = function (a) {
var first = a[0];
while (a.length > 0 && first.toString() === '0') {
a = a.slice(1);
first = a[0];
}
return a;
};
/**
* Trims leading zeros from a `Buffer`.
* @param a (Buffer)
* @return (Buffer)
*/
var unpadBuffer = function (a) {
(0, helpers_1.assertIsBuffer)(a);
return stripZeros(a);
};
exports.unpadBuffer = unpadBuffer;
/**
* Trims leading zeros from an `Array` (of numbers).
* @param a (number[])
* @return (number[])
*/
var unpadArray = function (a) {
(0, helpers_1.assertIsArray)(a);
return stripZeros(a);
};
exports.unpadArray = unpadArray;
/**
* Trims leading zeros from a hex-prefixed `String`.
* @param a (String)
* @return (String)
*/
var unpadHexString = function (a) {
(0, helpers_1.assertIsHexString)(a);
a = (0, internal_1.stripHexPrefix)(a);
return stripZeros(a);
};
exports.unpadHexString = unpadHexString;
/**
* Attempts to turn a value into a `Buffer`.
* Inputs supported: `Buffer`, `String` (hex-prefixed), `Number`, null/undefined, `BN` and other objects
* with a `toArray()` or `toBuffer()` method.
* @param v the value
*/
var toBuffer = function (v) {
if (v === null || v === undefined) {
return Buffer.allocUnsafe(0);
}
if (Buffer.isBuffer(v)) {
return Buffer.from(v);
}
if (Array.isArray(v) || v instanceof Uint8Array) {
return Buffer.from(v);
}
if (typeof v === 'string') {
if (!(0, internal_1.isHexString)(v)) {
throw new Error("Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: ".concat(v));
}
return Buffer.from((0, internal_1.padToEven)((0, internal_1.stripHexPrefix)(v)), 'hex');
}
if (typeof v === 'number') {
return (0, exports.intToBuffer)(v);
}
if (externals_1.BN.isBN(v)) {
if (v.isNeg()) {
throw new Error("Cannot convert negative BN to buffer. Given: ".concat(v));
}
return v.toArrayLike(Buffer);
}
if (v.toArray) {
// converts a BN to a Buffer
return Buffer.from(v.toArray());
}
if (v.toBuffer) {
return Buffer.from(v.toBuffer());
}
throw new Error('invalid type');
};
exports.toBuffer = toBuffer;
/**
* Converts a `Buffer` to a `Number`.
* @param buf `Buffer` object to convert
* @throws If the input number exceeds 53 bits.
*/
var bufferToInt = function (buf) {
return new externals_1.BN((0, exports.toBuffer)(buf)).toNumber();
};
exports.bufferToInt = bufferToInt;
/**
* Converts a `Buffer` into a `0x`-prefixed hex `String`.
* @param buf `Buffer` object to convert
*/
var bufferToHex = function (buf) {
buf = (0, exports.toBuffer)(buf);
return '0x' + buf.toString('hex');
};
exports.bufferToHex = bufferToHex;
/**
* Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers.
* @param num Signed integer value
*/
var fromSigned = function (num) {
return new externals_1.BN(num).fromTwos(256);
};
exports.fromSigned = fromSigned;
/**
* Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers.
* @param num
*/
var toUnsigned = function (num) {
return Buffer.from(num.toTwos(256).toArray());
};
exports.toUnsigned = toUnsigned;
/**
* Adds "0x" to a given `String` if it does not already start with "0x".
*/
var addHexPrefix = function (str) {
if (typeof str !== 'string') {
return str;
}
return (0, internal_1.isHexPrefixed)(str) ? str : '0x' + str;
};
exports.addHexPrefix = addHexPrefix;
/**
* Returns the utf8 string representation from a hex string.
*
* Examples:
*
* Input 1: '657468657265756d000000000000000000000000000000000000000000000000'
* Input 2: '657468657265756d'
* Input 3: '000000000000000000000000000000000000000000000000657468657265756d'
*
* Output (all 3 input variants): 'ethereum'
*
* Note that this method is not intended to be used with hex strings
* representing quantities in both big endian or little endian notation.
*
* @param string Hex string, should be `0x` prefixed
* @return Utf8 string
*/
var toUtf8 = function (hex) {
var zerosRegexp = /^(00)+|(00)+$/g;
hex = (0, internal_1.stripHexPrefix)(hex);
if (hex.length % 2 !== 0) {
throw new Error('Invalid non-even hex string input for toUtf8() provided');
}
var bufferVal = Buffer.from(hex.replace(zerosRegexp, ''), 'hex');
return bufferVal.toString('utf8');
};
exports.toUtf8 = toUtf8;
/**
* Converts a `Buffer` or `Array` to JSON.
* @param ba (Buffer|Array)
* @return (Array|String|null)
*/
var baToJSON = function (ba) {
if (Buffer.isBuffer(ba)) {
return "0x".concat(ba.toString('hex'));
}
else if (ba instanceof Array) {
var array = [];
for (var i = 0; i < ba.length; i++) {
array.push((0, exports.baToJSON)(ba[i]));
}
return array;
}
};
exports.baToJSON = baToJSON;
/**
* Checks provided Buffers for leading zeroes and throws if found.
*
* Examples:
*
* Valid values: 0x1, 0x, 0x01, 0x1234
* Invalid values: 0x0, 0x00, 0x001, 0x0001
*
* Note: This method is useful for validating that RLP encoded integers comply with the rule that all
* integer values encoded to RLP must be in the most compact form and contain no leading zero bytes
* @param values An object containing string keys and Buffer values
* @throws if any provided value is found to have leading zero bytes
*/
var validateNoLeadingZeroes = function (values) {
var e_1, _a;
try {
for (var _b = __values(Object.entries(values)), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), k = _d[0], v = _d[1];
if (v !== undefined && v.length > 0 && v[0] === 0) {
throw new Error("".concat(k, " cannot have leading zeroes, received: ").concat(v.toString('hex')));
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
};
exports.validateNoLeadingZeroes = validateNoLeadingZeroes;
function arrToBufArr(arr) {
if (!Array.isArray(arr)) {
return Buffer.from(arr);
}
return arr.map(function (a) { return arrToBufArr(a); });
}
exports.arrToBufArr = arrToBufArr;
function bufArrToArr(arr) {
if (!Array.isArray(arr)) {
return Uint8Array.from(arr !== null && arr !== void 0 ? arr : []);
}
return arr.map(function (a) { return bufArrToArr(a); });
}
exports.bufArrToArr = bufArrToArr;
//# sourceMappingURL=bytes.js.map
;