@dashevo/dash-spv 6.0.2 → 6.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.ultra.cache.json CHANGED
@@ -1 +1 @@
1
- {"files":{".gitignore":"095d365a56f423d4fab2345c95c137e7c6ea45c0",".mocharc.yml":"f6d924f143da5bc22530e55dcec6922aff69d8e1","LICENSE":"95bf3c7cb642fb61c1bbbb319fd3c83e47a5af96","README.md":"3659fd1bfb44b5e6916679ae586ccbff18683e59","config/config.js":"267c3536b5fe54c88080a56241c34d7393a54ac2","eslint.config.mjs":"cdf50e57d0d206e17f37b855643f55f73717fcd2","index.js":"4413accedb71ffb73ea7ce4ad45a2035c2ce92ca","lib/blockstore.js":"1ed82a8c1cfb4bc3aa96f0669a27c94d2e76b164","lib/consensus.js":"8e9bbb54c55ae3cf3d4caceca6f299635d1904bf","lib/errors/SPVError.js":"08b7af972c146bcdf29ffaa06eb90ca2c5660914","lib/merkleproofs.js":"1bba2c774e52e3cdfd4b99973c11229e6cf2cf6d","lib/spvchain.js":"314adc7f2e810bcceb5f30f4c90b6e566cf7650a","lib/test/bootstrap.js":"e2b2b2b17a9bf0ebff7721d8cb1e5cb75efb0f0f","lib/utils.js":"4ca99de11dd84867be29f1bab1ef09000fa8b5df","lib/x11.js":"d85e555bad579a8b3e2e92447331933ce9b0c4b1","package.json":"909707591582c7a01466fceb362cd7e6a38c7dc3","test/data/headers.js":"eb9cae85ee11027338fbf1f69e373d22388286d6","test/data/merkleproofs.js":"49ea4c29fb1f0cf6378ed7ee46b0a1db3bb555c1","test/data/rawHeaders.js":"03fed6ca2f8c2d1b63cfa13743431a2d551c7ad9","test/index.js":"00e843c3cd1f055dc3b9004a28e3a77dbb58db1a","test/spvchain.js":"f6441870e91b7faf2e6b23d034f40d007a697652"},"deps":{}}
1
+ {"files":{".gitignore":"095d365a56f423d4fab2345c95c137e7c6ea45c0",".mocharc.yml":"f6d924f143da5bc22530e55dcec6922aff69d8e1","LICENSE":"95bf3c7cb642fb61c1bbbb319fd3c83e47a5af96","README.md":"3659fd1bfb44b5e6916679ae586ccbff18683e59","config/config.js":"267c3536b5fe54c88080a56241c34d7393a54ac2","eslint.config.mjs":"cdf50e57d0d206e17f37b855643f55f73717fcd2","index.js":"4413accedb71ffb73ea7ce4ad45a2035c2ce92ca","lib/blockstore.js":"1ed82a8c1cfb4bc3aa96f0669a27c94d2e76b164","lib/consensus.js":"ebe1560f51946ce43f877839f4309b2dd6848d66","lib/errors/SPVError.js":"08b7af972c146bcdf29ffaa06eb90ca2c5660914","lib/merkleproofs.js":"1bba2c774e52e3cdfd4b99973c11229e6cf2cf6d","lib/pow.js":"4e67d46ad8f781944313d6848ee3d757541081ee","lib/spvchain.js":"c9b5ea181e77894c347b3efc12ceaf6e4e178be9","lib/test/bootstrap.js":"e2b2b2b17a9bf0ebff7721d8cb1e5cb75efb0f0f","lib/utils.js":"fa8af5df5f540bbe61a6c34c223d3d8d86c40481","lib/x11.js":"d85e555bad579a8b3e2e92447331933ce9b0c4b1","package.json":"5546c214e63a4a045371aaeb70ff4b69045d695d","test/data/difficulty.js":"b90be3791894be797ec26e00ba35bde45fcc0703","test/data/headers.js":"eb9cae85ee11027338fbf1f69e373d22388286d6","test/data/merkleproofs.js":"49ea4c29fb1f0cf6378ed7ee46b0a1db3bb555c1","test/data/rawHeaders.js":"03fed6ca2f8c2d1b63cfa13743431a2d551c7ad9","test/index.js":"05d843e5fa9ec7a6a41be26fac22e5eb60b42375","test/pow.js":"08a32b2f4a0becedfee579c610af19b39a3d6933","test/spvchain.js":"f6441870e91b7faf2e6b23d034f40d007a697652"},"deps":{}}
package/lib/consensus.js CHANGED
@@ -1,88 +1,58 @@
1
- const { hasValidTarget } = require('@dashevo/dark-gravity-wave');
2
- const DashUtil = require('@dashevo/dash-util');
3
1
  const merkleProofs = require('./merkleproofs');
2
+ const pow = require('./pow');
4
3
  const utils = require('./utils');
5
4
 
6
- const MIN_TIMESTAMP_HEADERS = 11;
7
- const MIN_DGW_HEADERS = 24;
8
-
9
- const NETWORK_POW_LIMITS = {
10
- mainnet: 0x1e0ffff0,
11
- testnet: 0x1e0fffff,
12
- devnet: 0x207fffff,
13
- regtest: 0x207fffff,
14
- };
15
-
16
- function getMedianTimestamp(headers) {
17
- const timestamps = headers.map((h) => h.time).sort((a, b) => a - b);
18
- return timestamps[Math.floor(timestamps.length / 2)];
19
- }
20
-
21
- // Must be strictly greater than the median time of the previous 11 blocks.
22
- // https://dash-docs.github.io/en/developer-reference#block-headers
23
- function hasGreaterThanMedianTimestamp(newHeader, previousHeaders) {
24
- if (previousHeaders.length < MIN_TIMESTAMP_HEADERS) {
25
- return true;
26
- }
27
- const normalizedHeader = utils.normalizeHeader(newHeader);
28
- const latestHeaders = previousHeaders
29
- .slice(-MIN_TIMESTAMP_HEADERS)
30
- .map((header) => utils.normalizeHeader(header));
31
- return getMedianTimestamp(latestHeaders) < normalizedHeader.time;
32
- }
33
-
34
- function hasCanonicalTarget(header, network) {
35
- const powLimit = NETWORK_POW_LIMITS[network];
36
- if (!powLimit || !Number.isInteger(header.bits)) {
37
- return false;
38
- }
39
-
40
- try {
41
- const target = DashUtil.expandTarget(header.bits);
42
- const canonicalBits = DashUtil.compressTarget(target);
43
- const maximumTarget = DashUtil.expandTarget(powLimit);
44
-
45
- return canonicalBits === header.bits && target.compare(maximumTarget) <= 0;
46
- } catch {
47
- return false;
48
- }
49
- }
50
-
51
5
  function isValidBlockHeaderWithoutContext(newHeader, network = 'mainnet') {
52
6
  const normalizedHeader = utils.normalizeHeader(newHeader);
53
7
 
54
- return hasCanonicalTarget(normalizedHeader, network)
55
- && utils.validProofOfWork(normalizedHeader)
8
+ // BlockHeader memoizes its hash, which a changed field doesn't refresh:
9
+ // check the hash of the header as it is now, and that it matches
10
+ const hash = utils.getHeaderHash(normalizedHeader);
11
+ return normalizedHeader.hash === hash
12
+ && pow.checkProofOfWork(hash, normalizedHeader.bits, network)
56
13
  && normalizedHeader.validTimestamp();
57
14
  }
58
15
 
59
- function isValidBlockHeader(newHeader, previousHeaders, network = 'mainnet') {
16
+ /**
17
+ * Validates a header against the headers before it, as Dash Core's
18
+ * ContextualCheckBlockHeader does for proof of work and time.
19
+ *
20
+ * Rules that need headers from before a trusted checkpoint the chain started
21
+ * at are skipped; proof of work and the network limit still apply.
22
+ *
23
+ * @param {BlockHeader} newHeader
24
+ * @param {BlockHeader[]} previousHeaders - oldest first, ending with the parent
25
+ * of newHeader. Only the last pow.MAX_HISTORY are read.
26
+ * @param {string} network
27
+ * @param {number} height - height of newHeader
28
+ * @param {number} [rootHeight] - height of the first header the chain has,
29
+ * by default the first of previousHeaders
30
+ * @return {boolean}
31
+ */
32
+ function isValidBlockHeader(newHeader, previousHeaders, network, height, rootHeight) {
33
+ if (!Number.isInteger(height) || height < 1) {
34
+ throw new Error(`Invalid header height ${height}`);
35
+ }
36
+
60
37
  const normalizedHeader = utils.normalizeHeader(newHeader);
61
- const normalizedPreviousHeaders = previousHeaders.map((header) => utils.normalizeHeader(header));
62
38
 
63
- if (!isValidBlockHeaderWithoutContext(normalizedHeader, network)
64
- || !hasGreaterThanMedianTimestamp(normalizedHeader, normalizedPreviousHeaders)) {
39
+ if (!isValidBlockHeaderWithoutContext(normalizedHeader, network)) {
65
40
  return false;
66
41
  }
67
42
 
68
- // Dash Core disables difficulty retargeting on regtest.
69
- if (network === 'regtest' && normalizedPreviousHeaders.length > 0) {
70
- const previousHeader = normalizedPreviousHeaders[normalizedPreviousHeaders.length - 1];
71
- return normalizedHeader.bits === previousHeader.bits;
72
- }
73
-
74
- // A trusted checkpoint may contain fewer than a full DGW window. Proof of
75
- // work, the network pow limit, and timestamp rules still apply immediately;
76
- // exact difficulty validation begins as soon as the required history exists.
77
- if (normalizedPreviousHeaders.length < MIN_DGW_HEADERS) {
78
- return true;
43
+ // Must be strictly greater than the median time of the previous 11 blocks
44
+ const medianTimePast = pow.getMedianTimePast(previousHeaders, height);
45
+ if (medianTimePast !== null && normalizedHeader.time <= medianTimePast) {
46
+ return false;
79
47
  }
80
48
 
81
- return hasValidTarget(
82
- utils.getDgwBlock(normalizedHeader),
83
- normalizedPreviousHeaders.map((header) => utils.getDgwBlock(header)),
49
+ return pow.hasValidDifficulty(
50
+ normalizedHeader,
51
+ previousHeaders,
52
+ height,
84
53
  network,
85
- );
54
+ rootHeight,
55
+ ) !== false;
86
56
  }
87
57
 
88
58
  /**
package/lib/pow.js ADDED
@@ -0,0 +1,513 @@
1
+ /* eslint-disable no-bitwise */
2
+ const utils = require('./utils');
3
+
4
+ // Difficulty rules ported from Dash Core: src/pow.cpp, the bad-diffbits check
5
+ // in ContextualCheckBlockHeader (src/validation.cpp), and the per-network
6
+ // consensus parameters in src/chainparams.cpp. Targets are BigInts that wrap
7
+ // at 256 bits, like Core's arith_uint256.
8
+
9
+ const UINT256_MASK = (1n << 256n) - 1n;
10
+
11
+ const TARGET_SPACING = 150; // nPowTargetSpacing: 2.5 minutes
12
+ const TARGET_TIMESPAN = 24 * 60 * 60; // nPowTargetTimespan: 1 day
13
+
14
+ const DGW_PAST_BLOCKS = 24;
15
+ const MEDIAN_TIME_SPAN = 11;
16
+
17
+ /**
18
+ * How many headers before a new one difficulty validation may read
19
+ * (KimotoGravityWell looks back the furthest)
20
+ */
21
+ const MAX_HISTORY = Math.floor((TARGET_TIMESPAN * 7) / TARGET_SPACING);
22
+
23
+ const POW_LIMIT = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn; // ~uint256(0) >> 20
24
+ const POW_LIMIT_LOW_DIFFICULTY = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn; // ~uint256(0) >> 1
25
+
26
+ const NETWORK_PARAMS = {
27
+ mainnet: {
28
+ powLimit: POW_LIMIT,
29
+ targetSpacing: TARGET_SPACING,
30
+ minimumDifficultyBlocks: 0,
31
+ kgwHeight: 15200,
32
+ dgwHeight: 34140,
33
+ allowMinDifficultyBlocks: false,
34
+ noRetargeting: false,
35
+ // Blocks up to this height only need bits within 50% of the expected
36
+ // difficulty ("architecture issues with DGW v1 and v2")
37
+ laxDifficultyMaxHeight: 68589,
38
+ },
39
+ testnet: {
40
+ powLimit: POW_LIMIT,
41
+ targetSpacing: TARGET_SPACING,
42
+ minimumDifficultyBlocks: 0,
43
+ kgwHeight: 4002,
44
+ dgwHeight: 4002,
45
+ allowMinDifficultyBlocks: true,
46
+ noRetargeting: false,
47
+ },
48
+ devnet: {
49
+ powLimit: POW_LIMIT_LOW_DIFFICULTY,
50
+ // Core's defaults; a devnet started with -powtargetspacing or
51
+ // -minimumdifficultyblocks must pass the same values to SpvChain
52
+ targetSpacing: TARGET_SPACING,
53
+ minimumDifficultyBlocks: 0,
54
+ kgwHeight: 4001,
55
+ dgwHeight: 4001,
56
+ allowMinDifficultyBlocks: true,
57
+ noRetargeting: false,
58
+ },
59
+ regtest: {
60
+ powLimit: POW_LIMIT_LOW_DIFFICULTY,
61
+ targetSpacing: TARGET_SPACING,
62
+ minimumDifficultyBlocks: 0,
63
+ kgwHeight: 15200,
64
+ dgwHeight: 34140,
65
+ allowMinDifficultyBlocks: true,
66
+ noRetargeting: true,
67
+ },
68
+ };
69
+
70
+ /**
71
+ * @param {string|{ network: string, powTargetSpacing?: number, minimumDifficultyBlocks?: number }} network -
72
+ * a network name, or a devnet with the settings it was started with
73
+ * @return {object}
74
+ */
75
+ function getNetworkParams(network) {
76
+ const name = typeof network === 'string' ? network : network && network.network;
77
+ const params = NETWORK_PARAMS[name];
78
+ if (!params) {
79
+ throw new Error(`Unsupported network ${name}`);
80
+ }
81
+ if (typeof network === 'string') {
82
+ return params;
83
+ }
84
+
85
+ const { powTargetSpacing = params.targetSpacing, minimumDifficultyBlocks = params.minimumDifficultyBlocks } = network;
86
+ if ((powTargetSpacing !== params.targetSpacing || minimumDifficultyBlocks !== params.minimumDifficultyBlocks)
87
+ && name !== 'devnet') {
88
+ throw new Error('Only devnets set their own block spacing and minimum-difficulty blocks');
89
+ }
90
+ if (!Number.isInteger(powTargetSpacing) || powTargetSpacing < 1
91
+ || Math.trunc(TARGET_TIMESPAN / powTargetSpacing) > MAX_HISTORY) {
92
+ throw new Error(`Unsupported block spacing ${powTargetSpacing}`);
93
+ }
94
+ if (!Number.isInteger(minimumDifficultyBlocks) || minimumDifficultyBlocks < 0) {
95
+ throw new Error(`Invalid minimum difficulty blocks ${minimumDifficultyBlocks}`);
96
+ }
97
+ return { ...params, targetSpacing: powTargetSpacing, minimumDifficultyBlocks };
98
+ }
99
+
100
+ /**
101
+ * arith_uint256::SetCompact
102
+ * @param {number} compact
103
+ * @return {{ target: bigint, negative: boolean, overflow: boolean }}
104
+ */
105
+ function decodeCompact(compact) {
106
+ const size = compact >>> 24;
107
+ let word = compact & 0x007fffff;
108
+ let target;
109
+ if (size <= 3) {
110
+ word >>>= 8 * (3 - size);
111
+ target = BigInt(word);
112
+ } else {
113
+ target = (BigInt(word) << BigInt(8 * (size - 3))) & UINT256_MASK;
114
+ }
115
+
116
+ return {
117
+ target,
118
+ negative: word !== 0 && (compact & 0x00800000) !== 0,
119
+ overflow: word !== 0 && (size > 34 || (word > 0xff && size > 33) || (word > 0xffff && size > 32)),
120
+ };
121
+ }
122
+
123
+ /**
124
+ * arith_uint256::GetCompact for a non-negative target
125
+ * @param {bigint} target
126
+ * @return {number}
127
+ */
128
+ function encodeCompact(target) {
129
+ let size = Math.ceil(target.toString(2).length / 8);
130
+ if (target === 0n) {
131
+ size = 0;
132
+ }
133
+
134
+ let compact = size <= 3
135
+ ? Number(target << BigInt(8 * (3 - size)))
136
+ : Number(target >> BigInt(8 * (size - 3)));
137
+
138
+ if (compact & 0x00800000) {
139
+ compact >>>= 8;
140
+ size += 1;
141
+ }
142
+
143
+ return (compact | (size << 24)) >>> 0;
144
+ }
145
+
146
+ /**
147
+ * CheckProofOfWork: bits must decode to a positive target within the network
148
+ * limit, and the header hash must not exceed it
149
+ * @param {string} hash - header hash as big-endian hex
150
+ * @param {number} bits
151
+ * @param {string|object} network - see getNetworkParams
152
+ * @return {boolean}
153
+ */
154
+ function checkProofOfWork(hash, bits, network) {
155
+ const { powLimit } = getNetworkParams(network);
156
+ if (!Number.isInteger(bits) || bits < 0 || bits > 0xffffffff) {
157
+ return false;
158
+ }
159
+
160
+ const { target, negative, overflow } = decodeCompact(bits);
161
+ if (negative || overflow || target === 0n || target > powLimit) {
162
+ return false;
163
+ }
164
+
165
+ return BigInt(`0x${hash}`) <= target;
166
+ }
167
+
168
+ /**
169
+ * ConvertBitsToDouble (difficulty as a double)
170
+ * @param {number} bits
171
+ * @return {number}
172
+ */
173
+ function convertBitsToDouble(bits) {
174
+ let shift = (bits >>> 24) & 0xff;
175
+ let diff = 0x0000ffff / (bits & 0x00ffffff);
176
+ while (shift < 29) {
177
+ diff *= 256.0;
178
+ shift += 1;
179
+ }
180
+ while (shift > 29) {
181
+ diff /= 256.0;
182
+ shift -= 1;
183
+ }
184
+ return diff;
185
+ }
186
+
187
+ class MissingHistoryError extends Error {
188
+ constructor(height) {
189
+ super(`Header at height ${height} is not in the validation history`);
190
+ this.height = height;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * The headers before a new one: `history` ends with the previous header, at
196
+ * `lastHeight`, and earlier ones are looked up by height
197
+ * @param {BlockHeader[]} history
198
+ * @param {number} lastHeight
199
+ */
200
+ function createAncestors(history, lastHeight) {
201
+ return {
202
+ history,
203
+ lastHeight,
204
+ last: history.length ? utils.normalizeHeader(history[history.length - 1]) : undefined,
205
+ };
206
+ }
207
+
208
+ function ancestorAt({ history, lastHeight }, height) {
209
+ const index = history.length - 1 - (lastHeight - height);
210
+ if (index < 0 || height > lastHeight) {
211
+ throw new MissingHistoryError(height);
212
+ }
213
+ return utils.normalizeHeader(history[index]);
214
+ }
215
+
216
+ function compactTarget(header) {
217
+ return decodeCompact(header.bits).target;
218
+ }
219
+
220
+ /** DifficultyAdjustmentInterval */
221
+ function getDifficultyAdjustmentInterval(params) {
222
+ return Math.trunc(TARGET_TIMESPAN / params.targetSpacing);
223
+ }
224
+
225
+ /** CalculateNextWorkRequired */
226
+ function calculateNextWorkRequired(last, firstBlockTime, params) {
227
+ if (params.noRetargeting) {
228
+ return last.bits;
229
+ }
230
+
231
+ let actualTimespan = last.time - firstBlockTime;
232
+ if (actualTimespan < TARGET_TIMESPAN / 4) {
233
+ actualTimespan = TARGET_TIMESPAN / 4;
234
+ }
235
+ if (actualTimespan > TARGET_TIMESPAN * 4) {
236
+ actualTimespan = TARGET_TIMESPAN * 4;
237
+ }
238
+
239
+ let target = (compactTarget(last) * BigInt(actualTimespan)) & UINT256_MASK;
240
+ target /= BigInt(TARGET_TIMESPAN);
241
+
242
+ if (target > params.powLimit) {
243
+ target = params.powLimit;
244
+ }
245
+
246
+ return encodeCompact(target);
247
+ }
248
+
249
+ /** GetNextWorkRequiredBTC */
250
+ function getNextWorkRequiredBTC(ancestors, newHeader, params) {
251
+ const { last, lastHeight } = ancestors;
252
+ const powLimitCompact = encodeCompact(params.powLimit);
253
+
254
+ const interval = getDifficultyAdjustmentInterval(params);
255
+
256
+ // Only change once per interval
257
+ if ((lastHeight + 1) % interval !== 0) {
258
+ if (params.allowMinDifficultyBlocks) {
259
+ // A block more than two spacings after the previous one may be mined
260
+ // at minimum difficulty
261
+ if (newHeader.time > last.time + params.targetSpacing * 2) {
262
+ return powLimitCompact;
263
+ }
264
+
265
+ // Return the last non-special-min-difficulty-rules block
266
+ let height = lastHeight;
267
+ let header = last;
268
+ while (height > 0
269
+ && height % interval !== 0
270
+ && header.bits === powLimitCompact) {
271
+ height -= 1;
272
+ header = ancestorAt(ancestors, height);
273
+ }
274
+ return header.bits;
275
+ }
276
+ return last.bits;
277
+ }
278
+
279
+ // Go back by what we want to be 1 day worth of blocks
280
+ const first = ancestorAt(ancestors, lastHeight - (interval - 1));
281
+ return calculateNextWorkRequired(last, first.time, params);
282
+ }
283
+
284
+ /** KimotoGravityWell */
285
+ function kimotoGravityWell(ancestors, params) {
286
+ const { last: blockLastSolved, lastHeight } = ancestors;
287
+ const pastBlocksMin = Math.floor(Math.floor(TARGET_TIMESPAN * 0.025) / params.targetSpacing);
288
+ const pastBlocksMax = Math.floor((TARGET_TIMESPAN * 7) / params.targetSpacing);
289
+
290
+ if (lastHeight === 0 || lastHeight < pastBlocksMin) {
291
+ return encodeCompact(params.powLimit);
292
+ }
293
+
294
+ let pastBlocksMass = 0;
295
+ let pastRateActualSeconds = 0;
296
+ let pastRateTargetSeconds = 0;
297
+ let pastDifficultyAverage = 0n;
298
+ let pastDifficultyAveragePrev = 0n;
299
+
300
+ for (let i = 1, height = lastHeight; height > 0; i += 1, height -= 1) {
301
+ if (i > pastBlocksMax) {
302
+ break;
303
+ }
304
+ const blockReading = ancestorAt(ancestors, height);
305
+ pastBlocksMass += 1;
306
+
307
+ pastDifficultyAverage = compactTarget(blockReading);
308
+ if (i > 1) {
309
+ // handle negative arith_uint256
310
+ if (pastDifficultyAverage >= pastDifficultyAveragePrev) {
311
+ pastDifficultyAverage = ((pastDifficultyAverage - pastDifficultyAveragePrev) / BigInt(i))
312
+ + pastDifficultyAveragePrev;
313
+ } else {
314
+ pastDifficultyAverage = pastDifficultyAveragePrev
315
+ - ((pastDifficultyAveragePrev - pastDifficultyAverage) / BigInt(i));
316
+ }
317
+ }
318
+ pastDifficultyAveragePrev = pastDifficultyAverage;
319
+
320
+ pastRateActualSeconds = blockLastSolved.time - blockReading.time;
321
+ pastRateTargetSeconds = params.targetSpacing * pastBlocksMass;
322
+ let pastRateAdjustmentRatio = 1;
323
+ if (pastRateActualSeconds < 0) {
324
+ pastRateActualSeconds = 0;
325
+ }
326
+ if (pastRateActualSeconds !== 0 && pastRateTargetSeconds !== 0) {
327
+ pastRateAdjustmentRatio = pastRateTargetSeconds / pastRateActualSeconds;
328
+ }
329
+ const eventHorizonDeviation = 1 + (0.7084 * ((pastBlocksMass / 28.2) ** -1.228));
330
+ const eventHorizonDeviationFast = eventHorizonDeviation;
331
+ const eventHorizonDeviationSlow = 1 / eventHorizonDeviation;
332
+
333
+ if (pastBlocksMass >= pastBlocksMin
334
+ && (pastRateAdjustmentRatio <= eventHorizonDeviationSlow
335
+ || pastRateAdjustmentRatio >= eventHorizonDeviationFast)) {
336
+ break;
337
+ }
338
+ }
339
+
340
+ let target = pastDifficultyAverage;
341
+ if (pastRateActualSeconds !== 0 && pastRateTargetSeconds !== 0) {
342
+ target = (target * BigInt(pastRateActualSeconds)) & UINT256_MASK;
343
+ target /= BigInt(pastRateTargetSeconds);
344
+ }
345
+
346
+ if (target > params.powLimit) {
347
+ target = params.powLimit;
348
+ }
349
+
350
+ return encodeCompact(target);
351
+ }
352
+
353
+ /** DarkGravityWave */
354
+ function darkGravityWave(ancestors, params) {
355
+ const { last, lastHeight } = ancestors;
356
+
357
+ // make sure we have at least (DGW_PAST_BLOCKS + 1) blocks
358
+ if (lastHeight < DGW_PAST_BLOCKS) {
359
+ return encodeCompact(params.powLimit);
360
+ }
361
+
362
+ let pastTargetAverage;
363
+ let first;
364
+ for (let countBlocks = 1; countBlocks <= DGW_PAST_BLOCKS; countBlocks += 1) {
365
+ first = ancestorAt(ancestors, lastHeight - countBlocks + 1);
366
+ const target = compactTarget(first);
367
+ if (countBlocks === 1) {
368
+ pastTargetAverage = target;
369
+ } else {
370
+ // Core notes this is not really an average; the exact integer steps matter
371
+ pastTargetAverage = ((pastTargetAverage * BigInt(countBlocks) + target) & UINT256_MASK)
372
+ / BigInt(countBlocks + 1);
373
+ }
374
+ }
375
+
376
+ let actualTimespan = last.time - first.time;
377
+ // Spans DGW_PAST_BLOCKS - 1 intervals; Core keeps this off-by-one
378
+ const targetTimespan = DGW_PAST_BLOCKS * params.targetSpacing;
379
+ if (actualTimespan < Math.trunc(targetTimespan / 3)) {
380
+ actualTimespan = Math.trunc(targetTimespan / 3);
381
+ }
382
+ if (actualTimespan > targetTimespan * 3) {
383
+ actualTimespan = targetTimespan * 3;
384
+ }
385
+
386
+ let target = (pastTargetAverage * BigInt(actualTimespan)) & UINT256_MASK;
387
+ target /= BigInt(targetTimespan);
388
+
389
+ if (target > params.powLimit) {
390
+ target = params.powLimit;
391
+ }
392
+
393
+ return encodeCompact(target);
394
+ }
395
+
396
+ /** GetNextWorkRequired */
397
+ function getNextWorkRequired(ancestors, newHeader, params) {
398
+ const { last, lastHeight } = ancestors;
399
+
400
+ // only active on devnets
401
+ if (lastHeight < params.minimumDifficultyBlocks) {
402
+ return encodeCompact(params.powLimit);
403
+ }
404
+
405
+ if (lastHeight + 1 < params.kgwHeight) {
406
+ return getNextWorkRequiredBTC(ancestors, newHeader, params);
407
+ }
408
+
409
+ if (params.noRetargeting) {
410
+ return encodeCompact(params.powLimit);
411
+ }
412
+
413
+ if (params.allowMinDifficultyBlocks) {
414
+ // recent block is more than 2 hours old
415
+ if (newHeader.time > last.time + 2 * 60 * 60) {
416
+ return encodeCompact(params.powLimit);
417
+ }
418
+ // recent block is more than 10 minutes old
419
+ if (newHeader.time > last.time + params.targetSpacing * 4) {
420
+ const target = (compactTarget(last) * 10n) & UINT256_MASK;
421
+ return encodeCompact(target > params.powLimit ? params.powLimit : target);
422
+ }
423
+ }
424
+
425
+ if (lastHeight + 1 < params.dgwHeight) {
426
+ return kimotoGravityWell(ancestors, params);
427
+ }
428
+
429
+ return darkGravityWave(ancestors, params);
430
+ }
431
+
432
+ /**
433
+ * The bits Core requires of a new header (GetNextWorkRequired)
434
+ *
435
+ * @param {BlockHeader} newHeader
436
+ * @param {BlockHeader[]} history - headers before newHeader, oldest first,
437
+ * ending with its parent. Only the last MAX_HISTORY are read.
438
+ * @param {number} height - height of newHeader
439
+ * @param {string|object} network - see getNetworkParams
440
+ * @param {number} [rootHeight] - height of the first header the chain has,
441
+ * by default the first one in history
442
+ * @return {number|null} null when the rules need headers from before the
443
+ * trusted checkpoint the chain starts at
444
+ */
445
+ function getExpectedBits(newHeader, history, height, network, rootHeight = height - history.length) {
446
+ const params = getNetworkParams(network);
447
+ if (history.length === 0) {
448
+ throw new Error(`No headers before height ${height} to validate its difficulty with`);
449
+ }
450
+
451
+ try {
452
+ return getNextWorkRequired(createAncestors(history, height - 1), newHeader, params);
453
+ } catch (e) {
454
+ if (!(e instanceof MissingHistoryError)) {
455
+ throw e;
456
+ }
457
+ if (e.height >= rootHeight) {
458
+ // The chain has this header; only a too-short history leaves it out
459
+ throw new Error(`Difficulty at height ${height} needs the header at ${e.height}, which the validation history leaves out`);
460
+ }
461
+ return null;
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Checks a header's bits the way Core's ContextualCheckBlockHeader does.
467
+ * Takes the arguments of getExpectedBits.
468
+ *
469
+ * @return {boolean|null} null when the rules can't be applied
470
+ */
471
+ function hasValidDifficulty(newHeader, history, height, network, rootHeight) {
472
+ const params = getNetworkParams(network);
473
+ const expectedBits = getExpectedBits(newHeader, history, height, network, rootHeight);
474
+ if (expectedBits === null) {
475
+ return null;
476
+ }
477
+
478
+ if (params.laxDifficultyMaxHeight !== undefined && height <= params.laxDifficultyMaxHeight) {
479
+ const difficulty = convertBitsToDouble(newHeader.bits);
480
+ const expectedDifficulty = convertBitsToDouble(expectedBits);
481
+ return Math.abs(difficulty - expectedDifficulty) <= difficulty * 0.5;
482
+ }
483
+
484
+ return newHeader.bits === expectedBits;
485
+ }
486
+
487
+ /**
488
+ * Median time of the up to 11 headers before a new one (GetMedianTimePast)
489
+ * @param {BlockHeader[]} history - ends with the parent of the new header
490
+ * @param {number} height - height of the new header
491
+ * @return {number|null} null when the history is too short to tell
492
+ */
493
+ function getMedianTimePast(history, height) {
494
+ const count = Math.min(MEDIAN_TIME_SPAN, height);
495
+ if (history.length < count) {
496
+ return null;
497
+ }
498
+ const times = history.slice(-count)
499
+ .map((header) => utils.normalizeHeader(header).time)
500
+ .sort((a, b) => a - b);
501
+ return times[Math.floor(times.length / 2)];
502
+ }
503
+
504
+ module.exports = {
505
+ MAX_HISTORY,
506
+ getNetworkParams,
507
+ checkProofOfWork,
508
+ getExpectedBits,
509
+ hasValidDifficulty,
510
+ getMedianTimePast,
511
+ decodeCompact,
512
+ encodeCompact,
513
+ };