-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockUtils.js
121 lines (79 loc) · 2.44 KB
/
blockUtils.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
const DIFF_ADJUSTMENT_PERIOD = 2016;
function divInPlace(arr, divisor) {
let remainder = 0;
for(let i=0;i<32;i++) {
const val = arr[i] + remainder;
const result = Math.floor(val/divisor);
remainder = (val % divisor) << 8;
arr[i] = result;
}
}
function addInPlace(arr, add) {
let remainder = 0;
for(let i=0;i<32;i++) {
const pos = 31-i;
const val = arr[pos] + add[pos] + remainder;
const byte = val & 0xFF;
remainder = val >> 8;
arr[pos] = byte;
}
}
function nbitsToTarget(nbits) {
const target = Buffer.alloc(32, 0);
const nSize = (nbits>>24) & 0xFF;
const nWord = [
((nbits >> 16) & 0x7F),
((nbits >> 8) & 0xFF),
((nbits) & 0xFF)
];
const start = 32-nSize;
for(let i=0;i<3;i++) {
if(start+i<32) {
target[start+i] = nWord[i];
}
}
return target;
}
function getDifficulty(nbits) {
const target = nbitsToTarget(nbits);
let start = 0;
for(let i=0;i<32;i++) {
if(target[i]>0) {
start = i;
break;
}
}
const shift = 32 - start - 3;
let num = 0;
for(let i=0;i<3;i++) {
num |= target[start+i] << ((2-i)*8);
}
const arr = Buffer.from("00000000FFFF0000000000000000000000000000000000000000000000000000", "hex");
divInPlace(arr, num);
const result = Buffer.alloc(32, 0);
for(let i=0;i<32-shift;i++) {
result[i+shift] = arr[i];
}
return result;
}
function computeCommitedHeader(initialCommitedHeader, submittedHeaders) {
const committedHeader = {...initialCommitedHeader};
committedHeader.chainWork = [...committedHeader.chainWork];
committedHeader.prevBlockTimestamps = [...committedHeader.prevBlockTimestamps];
for(let header of submittedHeaders) {
committedHeader.blockheight++;
for(let i=1;i<10;i++) {
committedHeader.prevBlockTimestamps[i-1] = committedHeader.prevBlockTimestamps[i];
}
committedHeader.prevBlockTimestamps[9] = committedHeader.header.timestamp;
if(committedHeader.blockheight % DIFF_ADJUSTMENT_PERIOD === 0) {
committedHeader.lastDiffAdjustment = header.timestamp;
}
addInPlace(committedHeader.chainWork, getDifficulty(header.nbits));
committedHeader.header = header;
}
return committedHeader;
}
module.exports = {
computeCommitedHeader
};