forked from nasa8x/node-genesis-block
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.js
78 lines (67 loc) · 1.73 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use strict";
var crypto = require('crypto');
function swapHex(value) {
let s = value.toString(16);
s = s.replace(/^(.(..)*)$/, "0$1");
var a = s.match(/../g);
a.reverse();
var s2 = a.join("");
return s2;
}
function intToHex(integer) {
let number = integer.toString(16).toUpperCase()
if( (number.length % 2) > 0 ) { number= "0" + number }
return number
}
function numToBytes(num, bytes) {
if (bytes === undefined) bytes = 8;
if (bytes == 0) return [];
else return [num % 256].concat(numToBytes(Math.floor(num / 256), bytes - 1));
}
function numToVarInt(num) {
if (num < 253) return [num];
else if (num < 65536) return [253].concat(numToBytes(num, 2));
else if (num < 4294967296) return [254].concat(numToBytes(num, 4));
else return [253].concat(numToBytes(num, 8));
}
function hexToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
function bytesToHex(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xf).toString(16));
}
return hex.join("");
}
function bytesLen(num) {
return Math.ceil(num.toString(2).length / 8);
}
function sha256(buffer) {
var hash1 = crypto.createHash('sha256');
hash1.update(buffer);
return hash1.digest();
};
function sha256d(buffer) {
return sha256(sha256(buffer));
};
function reverseBuffer(buff) {
var reversed = Buffer.alloc(buff.length);
for (var i = buff.length - 1; i >= 0; i--)
reversed[buff.length - i - 1] = buff[i];
return reversed;
};
module.exports = {
intToHex,
swapHex,
numToBytes,
numToVarInt,
hexToBytes,
bytesToHex,
bytesLen,
sha256,
sha256d,
reverseBuffer
};