1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.hexUtils = void 0;
|
4 | const crypto = require("crypto");
|
5 | const ethUtil = require("ethereumjs-util");
|
6 | const configured_bignumber_1 = require("./configured_bignumber");
|
7 |
|
8 | const WORD_LENGTH = 32;
|
9 | const WORD_CEIL = new configured_bignumber_1.BigNumber(2).pow(WORD_LENGTH * 8);
|
10 | exports.hexUtils = {
|
11 | concat,
|
12 | random,
|
13 | leftPad,
|
14 | rightPad,
|
15 | invert,
|
16 | slice,
|
17 | hash,
|
18 | size,
|
19 | toHex,
|
20 | isHex,
|
21 | };
|
22 |
|
23 |
|
24 |
|
25 | function concat(...args) {
|
26 | return ethUtil.bufferToHex(Buffer.concat(args.map(h => ethUtil.toBuffer(h))));
|
27 | }
|
28 |
|
29 |
|
30 |
|
31 | function random(_size = WORD_LENGTH) {
|
32 | return ethUtil.bufferToHex(crypto.randomBytes(_size));
|
33 | }
|
34 |
|
35 |
|
36 |
|
37 | function leftPad(n, _size = WORD_LENGTH) {
|
38 | return ethUtil.bufferToHex(ethUtil.setLengthLeft(ethUtil.toBuffer(exports.hexUtils.toHex(n)), _size));
|
39 | }
|
40 |
|
41 |
|
42 |
|
43 | function rightPad(n, _size = WORD_LENGTH) {
|
44 | return ethUtil.bufferToHex(ethUtil.setLengthRight(ethUtil.toBuffer(exports.hexUtils.toHex(n)), _size));
|
45 | }
|
46 |
|
47 |
|
48 |
|
49 | function invert(n, _size = WORD_LENGTH) {
|
50 | const buf = ethUtil.setLengthLeft(ethUtil.toBuffer(exports.hexUtils.toHex(n)), _size);
|
51 |
|
52 | return ethUtil.bufferToHex(Buffer.from(buf.map(b => ~b)));
|
53 | }
|
54 |
|
55 |
|
56 |
|
57 | function slice(n, start, end) {
|
58 | const hex = exports.hexUtils.toHex(n).substr(2);
|
59 | const sliceStart = start >= 0 ? start * 2 : Math.max(0, hex.length + start * 2);
|
60 | let sliceEnd = hex.length;
|
61 | if (end !== undefined) {
|
62 | sliceEnd = end >= 0 ? end * 2 : Math.max(0, hex.length + end * 2);
|
63 | }
|
64 | return '0x'.concat(hex.substring(sliceStart, sliceEnd));
|
65 | }
|
66 |
|
67 |
|
68 |
|
69 | function hash(n) {
|
70 | const buf = Buffer.isBuffer(n) ? n : ethUtil.toBuffer(exports.hexUtils.toHex(n));
|
71 | return ethUtil.bufferToHex(ethUtil.keccak256(buf));
|
72 | }
|
73 |
|
74 |
|
75 |
|
76 | function size(hex) {
|
77 | return Math.ceil((hex.length - 2) / 2);
|
78 | }
|
79 |
|
80 |
|
81 |
|
82 |
|
83 | function toHex(n, _size = WORD_LENGTH) {
|
84 | if (Buffer.isBuffer(n)) {
|
85 | return `0x${n.toString('hex')}`;
|
86 | }
|
87 | if (typeof n === 'string' && isHex(n)) {
|
88 |
|
89 | return n;
|
90 | }
|
91 | let _n = new configured_bignumber_1.BigNumber(n);
|
92 | if (_n.isNegative()) {
|
93 |
|
94 |
|
95 | _n = new configured_bignumber_1.BigNumber(invert(toHex(_n.abs()), _size).substr(2), 16).plus(1).mod(WORD_CEIL);
|
96 | }
|
97 | return `0x${_n.toString(16)}`;
|
98 | }
|
99 |
|
100 |
|
101 |
|
102 | function isHex(s) {
|
103 | return /^0x[0-9a-f]*$/i.test(s);
|
104 | }
|
105 |
|
\ | No newline at end of file |