@dashevo/dash-spv 0.23.0-alpha.1
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/.eslintignore +2 -0
- package/.eslintrc.json +7 -0
- package/LICENSE +21 -0
- package/README.md +7 -0
- package/config/config.js +51 -0
- package/index.js +7 -0
- package/lib/blockstore.js +56 -0
- package/lib/consensus.js +65 -0
- package/lib/merkleproofs.js +21 -0
- package/lib/spvchain.js +339 -0
- package/lib/utils.js +62 -0
- package/package.json +27 -0
- package/test/data/headers.js +216 -0
- package/test/data/merkleproofs.js +36 -0
- package/test/data/rawHeaders.js +5531 -0
- package/test/index.js +455 -0
package/.eslintignore
ADDED
package/.eslintrc.json
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017-2022 Dash Core Group, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
package/README.md
ADDED
package/config/config.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const DashUtil = require('@dashevo/dash-util');
|
|
2
|
+
const utils = require('../lib/utils');
|
|
3
|
+
|
|
4
|
+
module.exports = {
|
|
5
|
+
getLowDiffGenesis() {
|
|
6
|
+
// Custom genesis to test with lower difficulty
|
|
7
|
+
return utils.normalizeHeader({
|
|
8
|
+
version: 1,
|
|
9
|
+
previousblockhash: '0000000000000000000000000000000000000000000000000000000000000000',
|
|
10
|
+
merkleroot: DashUtil.nullHash.toString('hex'),
|
|
11
|
+
time: 1504510163,
|
|
12
|
+
bits: '1fffffff',
|
|
13
|
+
nonce: 2307,
|
|
14
|
+
});
|
|
15
|
+
},
|
|
16
|
+
getTestnetGenesis() {
|
|
17
|
+
// Custom genesis to test with lower difficulty
|
|
18
|
+
return utils.normalizeHeader({
|
|
19
|
+
version: 1,
|
|
20
|
+
previousblockhash: '0000000000000000000000000000000000000000000000000000000000000000',
|
|
21
|
+
merkleroot: 'e0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7',
|
|
22
|
+
time: 1390666206,
|
|
23
|
+
bits: '1e0ffff0',
|
|
24
|
+
nonce: 3861367235,
|
|
25
|
+
});
|
|
26
|
+
},
|
|
27
|
+
getDevnetGenesis() {
|
|
28
|
+
// Custom genesis to test with lower difficulty
|
|
29
|
+
return utils.normalizeHeader({
|
|
30
|
+
version: 1,
|
|
31
|
+
previousblockhash: '0000000000000000000000000000000000000000000000000000000000000000',
|
|
32
|
+
merkleroot: 'e0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7',
|
|
33
|
+
time: 1390666206,
|
|
34
|
+
bits: '1e0ffff0',
|
|
35
|
+
nonce: 3861367235,
|
|
36
|
+
});
|
|
37
|
+
},
|
|
38
|
+
getRegtestGenesis() {
|
|
39
|
+
return utils.normalizeHeader({
|
|
40
|
+
version: 1,
|
|
41
|
+
previousblockhash: '0000000000000000000000000000000000000000000000000000000000000000',
|
|
42
|
+
merkleroot: 'e0028eb9648db56b1ac77cf090b99048a8007e2bb64b68f092c03c7f56a662c7',
|
|
43
|
+
time: 1390666206,
|
|
44
|
+
bits: '1e0ffff0',
|
|
45
|
+
nonce: 3861367235,
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
getLivenetGenesis() {
|
|
49
|
+
throw Error('Livenet genesis not yet implemented');
|
|
50
|
+
},
|
|
51
|
+
};
|
package/index.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const levelup = require('levelup');
|
|
2
|
+
const memdown = require('memdown');
|
|
3
|
+
const dashcore = require('@dashevo/dashcore-lib');
|
|
4
|
+
|
|
5
|
+
class BlockStore {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.db = levelup(memdown(), {
|
|
8
|
+
keyAsBuffer: false,
|
|
9
|
+
valueAsBuffer: false,
|
|
10
|
+
valueEncoding: 'json',
|
|
11
|
+
});
|
|
12
|
+
this.block = dashcore.BlockHeader;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
put(header) {
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
this.db.put(header.hash, JSON.stringify(header.toObject()), (err) => {
|
|
18
|
+
if (!err) {
|
|
19
|
+
resolve(header.hash);
|
|
20
|
+
} else {
|
|
21
|
+
reject(err);
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
get(hash) {
|
|
28
|
+
const self = this;
|
|
29
|
+
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
self.db.get(hash, (err, data) => {
|
|
32
|
+
if (err && err.name === 'NotFoundError') {
|
|
33
|
+
resolve(null);
|
|
34
|
+
} else if (err) {
|
|
35
|
+
reject(err.message);
|
|
36
|
+
} else {
|
|
37
|
+
resolve(JSON.parse(data.toString()));
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
close() {
|
|
44
|
+
this.db.close();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
isClosed() {
|
|
48
|
+
return this.db.isClosed();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
isOpen() {
|
|
52
|
+
return this.db.isOpen();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
module.exports = BlockStore;
|
package/lib/consensus.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
const { hasValidTarget } = require('@dashevo/dark-gravity-wave');
|
|
2
|
+
const merkleProofs = require('./merkleproofs');
|
|
3
|
+
const utils = require('./utils');
|
|
4
|
+
|
|
5
|
+
const MIN_TIMESTAMP_HEADERS = 11;
|
|
6
|
+
const MIN_DGW_HEADERS = 24;
|
|
7
|
+
|
|
8
|
+
function getMedianTimestamp(headers) {
|
|
9
|
+
const timestamps = headers.map((h) => h.time);
|
|
10
|
+
const median = (arr) => {
|
|
11
|
+
const mid = Math.floor(arr.length / 2);
|
|
12
|
+
const nums = [...arr].sort((a, b) => a - b);
|
|
13
|
+
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
|
14
|
+
};
|
|
15
|
+
return median(timestamps);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Must be strictly greater than the median time of the previous 11 blocks.
|
|
19
|
+
// https://dash-docs.github.io/en/developer-reference#block-headers
|
|
20
|
+
function hasGreaterThanMedianTimestamp(newHeader, previousHeaders) {
|
|
21
|
+
if (previousHeaders.length < MIN_TIMESTAMP_HEADERS) return true;
|
|
22
|
+
const headerNormalised = utils.normalizeHeader(newHeader);
|
|
23
|
+
const normalizedLatestHeaders = previousHeaders.slice(
|
|
24
|
+
Math.max(previousHeaders.length - MIN_TIMESTAMP_HEADERS, 0),
|
|
25
|
+
).map((h) => utils.normalizeHeader(h));
|
|
26
|
+
return getMedianTimestamp(normalizedLatestHeaders) < headerNormalised.time;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isValidBlockHeader(newHeader, previousHeaders, network = 'mainnet') {
|
|
30
|
+
if (previousHeaders.length > MIN_DGW_HEADERS) {
|
|
31
|
+
return newHeader.validProofOfWork()
|
|
32
|
+
&& newHeader.validTimestamp()
|
|
33
|
+
&& hasGreaterThanMedianTimestamp(newHeader, previousHeaders)
|
|
34
|
+
&& hasValidTarget(
|
|
35
|
+
utils.getDgwBlock(newHeader), previousHeaders.map((h) => utils.getDgwBlock(h)), network,
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
return newHeader.validProofOfWork()
|
|
39
|
+
&& newHeader.validTimestamp()
|
|
40
|
+
&& hasGreaterThanMedianTimestamp(newHeader, previousHeaders);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* validates an array of tx hashes or Transaction instances
|
|
45
|
+
* against a merkleblock and the local header chain
|
|
46
|
+
* @param {Transaction[]|string[]} transactions
|
|
47
|
+
* @param {MerkleBlock} merkleBlock - a MerkleBlock instance
|
|
48
|
+
* @param {SpvChain} headerChain - an instance of an SpvChain
|
|
49
|
+
* @return {boolean}
|
|
50
|
+
*/
|
|
51
|
+
async function areValidTransactions(transactions, merkleBlock, headerChain) {
|
|
52
|
+
if (!Array.isArray(transactions) || transactions.length <= 0) {
|
|
53
|
+
throw new Error('Please check that transactions parameter is a non-empty array');
|
|
54
|
+
}
|
|
55
|
+
const localHeader = await headerChain.getHeader(merkleBlock.header.hash);
|
|
56
|
+
if (!localHeader) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
return merkleProofs.validateTxProofs(merkleBlock, transactions);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = {
|
|
63
|
+
isValidBlockHeader,
|
|
64
|
+
areValidTransactions,
|
|
65
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const DashUtil = require('@dashevo/dash-util');
|
|
2
|
+
|
|
3
|
+
const merkleproofs = {
|
|
4
|
+
/**
|
|
5
|
+
* validates an array of tx hashes or Transaction instances
|
|
6
|
+
* against a merkleblock
|
|
7
|
+
* @param {MerkleBlock} merkleBlock - a MerkleBlock instance
|
|
8
|
+
* @param {Transaction[]|string[]} transactions
|
|
9
|
+
* @return {boolean}
|
|
10
|
+
*/
|
|
11
|
+
validateTxProofs: (merkleBlock, transactions) => {
|
|
12
|
+
let txToFilter = transactions.slice();
|
|
13
|
+
if (typeof transactions[0] === 'string') {
|
|
14
|
+
txToFilter = txToFilter.map((tx) => DashUtil.toHash(tx).toString('hex'));
|
|
15
|
+
}
|
|
16
|
+
return merkleBlock.validMerkleTree
|
|
17
|
+
&& txToFilter.filter((tx) => merkleBlock.hasTransaction(tx)).length === transactions.length;
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
module.exports = merkleproofs;
|
package/lib/spvchain.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
const BlockStore = require('./blockstore');
|
|
2
|
+
const config = require('../config/config');
|
|
3
|
+
const Consensus = require('./consensus');
|
|
4
|
+
const utils = require('./utils');
|
|
5
|
+
|
|
6
|
+
const SpvChain = class {
|
|
7
|
+
constructor(chainType, confirms = 100, startBlock) {
|
|
8
|
+
this.root = null;
|
|
9
|
+
this.allBranches = [];
|
|
10
|
+
this.orphanBlocks = [];
|
|
11
|
+
this.orphanChunks = [];
|
|
12
|
+
this.confirmsBeforeFinal = confirms;
|
|
13
|
+
this.init(chainType, startBlock);
|
|
14
|
+
this.store = new BlockStore();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
init(chainType, startBlock) {
|
|
18
|
+
switch (chainType) {
|
|
19
|
+
case 'testnet':
|
|
20
|
+
this.network = 'testnet';
|
|
21
|
+
if (startBlock) {
|
|
22
|
+
this.root = startBlock;
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
this.root = config.getTestnetGenesis();
|
|
26
|
+
break;
|
|
27
|
+
case 'devnet':
|
|
28
|
+
this.network = 'devnet';
|
|
29
|
+
if (startBlock) {
|
|
30
|
+
this.root = startBlock;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
this.root = config.getDevnetGenesis();
|
|
34
|
+
break;
|
|
35
|
+
case 'regtest':
|
|
36
|
+
this.network = 'regtest';
|
|
37
|
+
if (startBlock) {
|
|
38
|
+
this.root = startBlock;
|
|
39
|
+
break;
|
|
40
|
+
}
|
|
41
|
+
this.root = config.getRegtestGenesis();
|
|
42
|
+
break;
|
|
43
|
+
case 'livenet':
|
|
44
|
+
this.network = 'mainnet';
|
|
45
|
+
if (startBlock) {
|
|
46
|
+
this.root = startBlock;
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
this.root = config.getLivenetGenesis();
|
|
50
|
+
break;
|
|
51
|
+
case 'mainnet':
|
|
52
|
+
this.network = 'mainnet';
|
|
53
|
+
if (startBlock) {
|
|
54
|
+
this.root = startBlock;
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
this.root = config.getLivenetGenesis();
|
|
58
|
+
break;
|
|
59
|
+
case 'lowdiff':
|
|
60
|
+
this.network = 'regtest';
|
|
61
|
+
if (startBlock) {
|
|
62
|
+
this.root = startBlock;
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
this.root = config.getLowDiffGenesis();
|
|
66
|
+
break;
|
|
67
|
+
default:
|
|
68
|
+
if (startBlock) {
|
|
69
|
+
this.root = startBlock;
|
|
70
|
+
this.network = 'mainnet';
|
|
71
|
+
} else {
|
|
72
|
+
throw new Error('Unhandled chaintype or startBlock not provided');
|
|
73
|
+
}
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
this.root.children = [];
|
|
77
|
+
this.setAllBranches();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @private */
|
|
81
|
+
checkPruneBlocks() {
|
|
82
|
+
const longestChain = this.getLongestChain();
|
|
83
|
+
|
|
84
|
+
while (longestChain.length > this.confirmsBeforeFinal) {
|
|
85
|
+
const pruneBlock = longestChain.splice(0, 1)[0];
|
|
86
|
+
// Children discarded as stale branches
|
|
87
|
+
delete pruneBlock.orphan;
|
|
88
|
+
this.store.put(pruneBlock);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @private */
|
|
93
|
+
findConnection(newHeader) {
|
|
94
|
+
const stack = [this.root];
|
|
95
|
+
while (stack.length > 0) {
|
|
96
|
+
const node = stack.pop();
|
|
97
|
+
if (node.hash === utils.getCorrectedHash(newHeader.prevHash)) {
|
|
98
|
+
return node;
|
|
99
|
+
}
|
|
100
|
+
node.children.forEach((c) => { stack.push(c); });
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @private */
|
|
106
|
+
setAllBranches(node = this.root, branch = []) {
|
|
107
|
+
this.allBranches = [];
|
|
108
|
+
branch.push(node);
|
|
109
|
+
|
|
110
|
+
node.children.forEach((c) => {
|
|
111
|
+
this.setAllBranches(c, Array.from(branch));
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
if (node.children.length === 0) {
|
|
115
|
+
this.allBranches.push(branch);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** @private */
|
|
120
|
+
appendHeadersToLongestChain(headers) {
|
|
121
|
+
const newLongestChain = this.getLongestChain().concat(headers);
|
|
122
|
+
this.allBranches = [];
|
|
123
|
+
this.allBranches.push(newLongestChain);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @private */
|
|
127
|
+
getAllBranches() {
|
|
128
|
+
return this.allBranches;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @private */
|
|
132
|
+
isDuplicate(compareHash) {
|
|
133
|
+
return this.getAllBranches().map((branch) => branch.map((node) => node.hash))
|
|
134
|
+
.concat(this.orphanBlocks.map((orphan) => orphan.hash))
|
|
135
|
+
.filter((hash) => hash === compareHash).length > 0;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** @private */
|
|
139
|
+
orphanReconnect() {
|
|
140
|
+
for (let i = 0; i < this.orphanBlocks.length; i += 1) {
|
|
141
|
+
const connectionTip = this.findConnection(this.orphanBlocks[i]);
|
|
142
|
+
if (connectionTip) {
|
|
143
|
+
connectionTip.children.push(this.orphanBlocks[i]);
|
|
144
|
+
this.orphanBlocks.splice(i, 1);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** @private */
|
|
150
|
+
orphanChunksReconnect() {
|
|
151
|
+
this.orphanChunks.sort((a, b) => a[0].timestamp - b[0].timestamp);
|
|
152
|
+
this.orphanChunks.slice().forEach((chunk, index) => {
|
|
153
|
+
if (this.getTipHash() === utils.getCorrectedHash(chunk[0].prevHash)) {
|
|
154
|
+
this.appendHeadersToLongestChain(chunk);
|
|
155
|
+
this.orphanChunks.splice(index, 1);
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** @private */
|
|
161
|
+
getOrphans() {
|
|
162
|
+
return this.orphanBlocks;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** @private */
|
|
166
|
+
getOrphanChunks() {
|
|
167
|
+
return this.orphanChunks;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** @private */
|
|
171
|
+
processValidHeader(header) {
|
|
172
|
+
const connection = this.findConnection(header);
|
|
173
|
+
if (connection) {
|
|
174
|
+
connection.children.push(header);
|
|
175
|
+
this.orphanReconnect();
|
|
176
|
+
} else {
|
|
177
|
+
this.orphanBlocks.push(header);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** @private
|
|
182
|
+
* validates a dashcore.BlockHeader object
|
|
183
|
+
*
|
|
184
|
+
* @param {Object} header
|
|
185
|
+
* @param {Object[]} previousHeaders
|
|
186
|
+
* @return {boolean}
|
|
187
|
+
*/
|
|
188
|
+
isValid(header, previousHeaders) {
|
|
189
|
+
return !!(Consensus.isValidBlockHeader(header, previousHeaders, this.network)
|
|
190
|
+
&& !this.isDuplicate(header.hash));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/* eslint-disable no-param-reassign */
|
|
194
|
+
/**
|
|
195
|
+
* verifies the parent child connection
|
|
196
|
+
* between two adjacent dashcore.BlockHeader objects
|
|
197
|
+
*
|
|
198
|
+
* @param {Object} header
|
|
199
|
+
* @param {Object} previousHeader
|
|
200
|
+
* @return {boolean}
|
|
201
|
+
*/
|
|
202
|
+
static isParentChild(header, previousHeader) {
|
|
203
|
+
if (utils.getCorrectedHash(header.prevHash) !== previousHeader.hash) {
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
if (!header.children) {
|
|
207
|
+
header.children = [];
|
|
208
|
+
}
|
|
209
|
+
if (!previousHeader.children) {
|
|
210
|
+
previousHeader.children = [];
|
|
211
|
+
}
|
|
212
|
+
previousHeader.children.push(header);
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
/* eslint-enable no-param-reassign */
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* gets the longest chain
|
|
219
|
+
*
|
|
220
|
+
* @return {Object[]}
|
|
221
|
+
*/
|
|
222
|
+
getLongestChain() {
|
|
223
|
+
return this.allBranches.sort((b1, b2) => b1 < b2)[0];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* gets the block hash of the longest chain tip
|
|
228
|
+
*
|
|
229
|
+
* @return {string} hash
|
|
230
|
+
*/
|
|
231
|
+
getTipHash() {
|
|
232
|
+
return this.getLongestChain().slice(-1)[0].hash;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* gets the dashcore.BlockHeader object the longest chain tip
|
|
237
|
+
*
|
|
238
|
+
* @return {Object} header
|
|
239
|
+
*/
|
|
240
|
+
getTipHeader() {
|
|
241
|
+
return this.getLongestChain().slice(-1)[0];
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* gets the dashcore.BlockHeader object for a specific block hash
|
|
246
|
+
*
|
|
247
|
+
* @param {string} hash
|
|
248
|
+
* @return {Object} header
|
|
249
|
+
*/
|
|
250
|
+
getHeader(hash) {
|
|
251
|
+
return this.store.get(hash)
|
|
252
|
+
.then((blockInDB) => {
|
|
253
|
+
if (blockInDB) {
|
|
254
|
+
return blockInDB;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return this.getLongestChain().filter((h) => h.hash === hash)[0];
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* adds a valid header to the tip of the longest spv chain.
|
|
263
|
+
* If it cannot be connected to the tip it gets temporarily
|
|
264
|
+
* added to an orphan array for possible later reconnection
|
|
265
|
+
*
|
|
266
|
+
* @param {Object[]|string[]|buffer[]} header
|
|
267
|
+
* @return {boolean}
|
|
268
|
+
*/
|
|
269
|
+
addHeader(header) {
|
|
270
|
+
const headerNormalised = utils.normalizeHeader(header);
|
|
271
|
+
|
|
272
|
+
if (this.isValid(headerNormalised, this.getLongestChain())) {
|
|
273
|
+
headerNormalised.children = [];
|
|
274
|
+
this.processValidHeader(headerNormalised);
|
|
275
|
+
this.setAllBranches();
|
|
276
|
+
this.checkPruneBlocks();
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* adds an array of valid headers to the longest spv chain.
|
|
284
|
+
* If they cannot be connected to last tip they get temporarily
|
|
285
|
+
* added to an orphan array for possible later reconnection
|
|
286
|
+
*
|
|
287
|
+
* @param {Object[]|string[]|buffer[]} headers
|
|
288
|
+
* @return {boolean}
|
|
289
|
+
*/
|
|
290
|
+
addHeaders(headers) {
|
|
291
|
+
if (headers.length === 1) {
|
|
292
|
+
if (!this.addHeader(headers[0])) {
|
|
293
|
+
throw new Error('Some headers are invalid');
|
|
294
|
+
} else {
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const normalizedHeaders = headers.map((h) => utils.normalizeHeader(h));
|
|
299
|
+
const isOrphan = !SpvChain.isParentChild(normalizedHeaders[0], this.getTipHeader());
|
|
300
|
+
|
|
301
|
+
const allValid = normalizedHeaders.reduce(
|
|
302
|
+
(acc, header, index, array) => {
|
|
303
|
+
const previousHeaders = normalizedHeaders.slice(0, index);
|
|
304
|
+
if (index !== 0) {
|
|
305
|
+
if (!SpvChain.isParentChild(header, array[index - 1])
|
|
306
|
+
|| !this.isValid(header, previousHeaders)) {
|
|
307
|
+
throw new Error('Some headers are invalid');
|
|
308
|
+
}
|
|
309
|
+
return acc && true;
|
|
310
|
+
}
|
|
311
|
+
if (isOrphan) {
|
|
312
|
+
if (!this.isValid(header, previousHeaders)) {
|
|
313
|
+
throw new Error('Some headers are invalid');
|
|
314
|
+
}
|
|
315
|
+
return acc && true;
|
|
316
|
+
}
|
|
317
|
+
if (!this.isValid(header, this.getLongestChain())) {
|
|
318
|
+
throw new Error('Some headers are invalid');
|
|
319
|
+
}
|
|
320
|
+
return acc && true;
|
|
321
|
+
}, true,
|
|
322
|
+
);
|
|
323
|
+
if (!allValid) {
|
|
324
|
+
throw new Error('Some headers are invalid');
|
|
325
|
+
}
|
|
326
|
+
if (isOrphan) {
|
|
327
|
+
this.orphanChunks.push(normalizedHeaders);
|
|
328
|
+
} else {
|
|
329
|
+
this.appendHeadersToLongestChain(normalizedHeaders);
|
|
330
|
+
}
|
|
331
|
+
if (this.orphanChunks.length > 0) {
|
|
332
|
+
this.orphanChunksReconnect();
|
|
333
|
+
}
|
|
334
|
+
this.checkPruneBlocks();
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
module.exports = SpvChain;
|
package/lib/utils.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/* eslint no-underscore-dangle: ["error", { "allow": ["_getHash"] }] */
|
|
2
|
+
/* eslint-disable no-bitwise */
|
|
3
|
+
const DashUtil = require('@dashevo/dash-util');
|
|
4
|
+
const dashcore = require('@dashevo/dashcore-lib');
|
|
5
|
+
|
|
6
|
+
module.exports = {
|
|
7
|
+
|
|
8
|
+
getCorrectedHash(reversedHashObj) {
|
|
9
|
+
const clone = Buffer.alloc(32);
|
|
10
|
+
reversedHashObj.copy(clone);
|
|
11
|
+
return clone.reverse().toString('hex');
|
|
12
|
+
},
|
|
13
|
+
normalizeHeader(header) {
|
|
14
|
+
if (header instanceof dashcore.BlockHeader) {
|
|
15
|
+
return header;
|
|
16
|
+
}
|
|
17
|
+
if (Buffer.isBuffer(header) && header.length === 80) {
|
|
18
|
+
return new dashcore.BlockHeader(header);
|
|
19
|
+
}
|
|
20
|
+
if (typeof header === 'string' && header.length === 160) {
|
|
21
|
+
const buffer = Buffer.from(header, 'hex');
|
|
22
|
+
return new dashcore.BlockHeader(buffer);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const el = JSON.parse(JSON.stringify(header));
|
|
26
|
+
|
|
27
|
+
return new dashcore.BlockHeader({
|
|
28
|
+
version: el.version,
|
|
29
|
+
prevHash: DashUtil.toHash(el.previousblockhash || el.prevHash),
|
|
30
|
+
merkleRoot: (el.merkleroot || el.merkleRoot),
|
|
31
|
+
time: el.time,
|
|
32
|
+
bits: parseInt(el.bits, 16),
|
|
33
|
+
nonce: el.nonce,
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
getDgwBlock(header) {
|
|
37
|
+
return {
|
|
38
|
+
timestamp: header.timestamp,
|
|
39
|
+
target: header.bits,
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
validProofOfWork(header) {
|
|
43
|
+
const target = DashUtil.expandTarget(header.bits);
|
|
44
|
+
const hash = header._getHash().reverse();
|
|
45
|
+
return hash.compare(target) === -1;
|
|
46
|
+
},
|
|
47
|
+
createBlock(prev, bits) {
|
|
48
|
+
let i = 0;
|
|
49
|
+
let header = null;
|
|
50
|
+
do {
|
|
51
|
+
header = new dashcore.BlockHeader({
|
|
52
|
+
version: 2,
|
|
53
|
+
prevHash: prev ? prev._getHash() : DashUtil.nullHash,
|
|
54
|
+
merkleRoot: DashUtil.nullHash,
|
|
55
|
+
time: prev ? (prev.time + 1) : Math.floor(Date.now() / 1000),
|
|
56
|
+
bits,
|
|
57
|
+
nonce: i += 1,
|
|
58
|
+
});
|
|
59
|
+
} while (!this.validProofOfWork(header));
|
|
60
|
+
return header;
|
|
61
|
+
},
|
|
62
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dashevo/dash-spv",
|
|
3
|
+
"version": "0.23.0-alpha.1",
|
|
4
|
+
"description": "Repository containing SPV functions used by @dashevo",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "mocha test/ --no-timeouts --recursive",
|
|
8
|
+
"lint": "eslint .",
|
|
9
|
+
"lint:fix": "eslint . --fix"
|
|
10
|
+
},
|
|
11
|
+
"author": "",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@dashevo/dark-gravity-wave": "^1.1.1",
|
|
15
|
+
"@dashevo/dash-util": "^2.0.3",
|
|
16
|
+
"@dashevo/dashcore-lib": "~0.19.44",
|
|
17
|
+
"levelup": "^4.4.0",
|
|
18
|
+
"memdown": "^5.1.0"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"eslint": "^7.32.0",
|
|
22
|
+
"eslint-config-airbnb-base": "^14.2.1",
|
|
23
|
+
"eslint-plugin-import": "^2.24.2",
|
|
24
|
+
"mocha": "^9.1.2",
|
|
25
|
+
"should": "^13.2.3"
|
|
26
|
+
}
|
|
27
|
+
}
|