-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlibconvert.js
306 lines (272 loc) · 9.23 KB
/
libconvert.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
'use strict';
/**
* Tools module.
* @module Utils
* @author EternityWall
* @license LPGL3
*/
// Dependencies
const crypto = require('crypto');
const OpenTimestamps = require('javascript-opentimestamps');
const Insight = require('./insight.js');
const Tools = require('./tools.js');
const Bitcoin = require('./bitcoin.js');
// OpenTimestamps shortcuts
const Timestamp = OpenTimestamps.Timestamp;
const Ops = OpenTimestamps.Ops;
const Utils = OpenTimestamps.Utils;
const Notary = OpenTimestamps.Notary;
// Check chainpoint receipt
exports.checkValidHeader = function (chainpoint) {
if (chainpoint['@context'] !== 'https://w3id.org/chainpoint/v2') {
console.error('Support only chainpoint v2');
return false;
}
if (chainpoint.type !== 'ChainpointSHA256v2') {
console.error('Support only ChainpointSHA256v2');
return false;
}
if (chainpoint.anchors === undefined) {
console.error('Support only timestamps with attestations');
return false;
}
return true;
};
// Migrate proofs
exports.migrationMerkle = function (targetHash, proof) {
let timestamp = new Timestamp(Tools.hexToBytes(targetHash));
const tip = timestamp;
for (let i = 0; i < proof.length; i++) {
const item = proof[i];
let op;
if (item.left !== undefined) {
op = new Ops.OpPrepend(Tools.hexToBytes(item.left));
} else if (item.right !== undefined) {
op = new Ops.OpAppend(Tools.hexToBytes(item.right));
}
timestamp = timestamp.add(op);
const opSHA256 = new Ops.OpSHA256();
timestamp = timestamp.add(opSHA256);
}
return tip;
};
// Add OTS attestation
exports.addAttestation = function (timestamp, attestation) {
if (timestamp.ops.size === 0) {
timestamp.attestations.push(attestation);
return true;
}
timestamp.ops.forEach(stamp => {
this.addAttestation(stamp, attestation);
});
};
// Migrate attestation
exports.migrationAttestations = function (anchors, timestamp) {
const self = this;
anchors.forEach(anchor => {
let attestation;
if (anchor.type === 'BTCOpReturn') {
const tag = [0x68, 0x7F, 0xE3, 0xFE, 0x79, 0x5E, 0x9A, 0x0D];
attestation = new Notary.UnknownAttestation(tag, Tools.hexToBytes(anchor.sourceId));
self.addAttestation(timestamp, attestation);
}
})
;
};
// Bitcoin node verification
exports.nodeVerify = function () {
return new Promise((resolve, reject) => {
Bitcoin.BitcoinNode.readBitcoinConf().then(properties => {
const bitcoin = new Bitcoin.BitcoinNode(properties);
resolve(bitcoin);
}).catch(err => {
reject(err);
});
});
};
// Lite verification with Insight
exports.liteVerify = function () {
return new Promise(resolve => {
resolve(new Insight.MultiInsight());
});
};
// Resolve attestation
exports.resolveAttestation = function (txHash, timestamp, noBitcoinNode) {
const self = this;
if (!noBitcoinNode) {
return new Promise((resolve, reject) => {
console.log('Bitcoin node verification');
this.nodeVerify().then(explorer => {
return self.verify(txHash, timestamp, explorer);
}).then(status => {
console.log('Bitcoin node verification success');
resolve(status);
}).catch(() => {
console.log('Bitcoin node verification failure: ');
// Reject('Bitcoin node verification failure: ');
// Fallback
this.liteVerify().then(explorer => {
console.log('Lite verification');
return self.verify(txHash, timestamp, explorer);
}).then(status => {
console.log('Lite verification success');
resolve(status);
}).catch(() => {
console.log('Lite verification failure: ');
reject(Error('Lite verification failure: '));
});
});
});
}
if (noBitcoinNode) {
return new Promise((resolve, reject) => {
console.log('Lite verification');
this.liteVerify().then(explorer => {
return self.verify(txHash, timestamp, explorer);
}).then(status => {
console.log('Lite verification success');
resolve(status);
}).catch(() => {
console.log('Lite verification failure: ');
reject(Error('Lite verification failure: '));
});
});
}
};
exports.verify = function (txHash, timestamp, explorer) {
const self = this;
return new Promise((resolve, reject) => {
explorer.rawtx(txHash)
.then(rawtx => {
const opReturn = Tools.bytesToHex(timestamp.msg);
const pos = rawtx.indexOf(opReturn);
if (pos === -1) {
throw String('Invalid tx');
}
const append = Tools.hexToBytes(rawtx.substring(0, pos));
const prepend = Tools.hexToBytes(rawtx.substring(pos + txHash.length, rawtx.length));
let subStamp = timestamp.add(new Ops.OpPrepend(append));
subStamp = subStamp.add(new Ops.OpAppend(prepend));
subStamp = subStamp.add(new Ops.OpSHA256());
subStamp.add(new Ops.OpSHA256());
return explorer.tx(txHash);
})
.then(tx => {
return explorer.block(tx.blockhash);
})
.then(block => {
// Prepare digest tx list
const digests = [];
const merkleRoots = [];
block.tx.forEach(hash => {
const bytes = Tools.hexToBytes(hash).reverse();
const digest = OpenTimestamps.DetachedTimestampFile.fromHash(new Ops.OpSHA256(), bytes);
merkleRoots.push(digest.timestamp);
digests.push(digest);
});
// Build merkle tree
const merkleTip = self.makeMerkleTree(merkleRoots);
if (merkleTip === undefined) {
throw String('Invalid merkle tree');
} else if (!Tools.arrEq(merkleTip.msg, Tools.hexToBytes(block.merkleroot).reverse())) {
throw String('Not match merkle tree');
}
// Add bitcoin attestation
const attestation = new Notary.BitcoinBlockHeaderAttestation(block.height);
merkleTip.attestations.push(attestation);
// Check chainpoint anchor to merge
digests.forEach(digest => {
if (Tools.arrEq(digest.timestamp.msg, Tools.hexToBytes(txHash).reverse())) {
timestamp.attestations = []; // Remove unknown attestation
let subStamp = timestamp.ops.values().next().value;
subStamp = subStamp.ops.values().next().value;
subStamp = subStamp.ops.values().next().value;
subStamp = subStamp.ops.values().next().value;
subStamp.ops = digest.timestamp.ops;
}
});
resolve();
})
.catch(err => {
reject(err);
});
});
};
exports.makeMerkleTree = function (timestamps) {
let stamps = timestamps;
let prevStamp;
for (;;) {
stamps = stamps[Symbol.iterator]();
prevStamp = stamps.next().value;
const nextStamps = [];
for (const stamp of stamps) {
if (prevStamp === undefined) {
prevStamp = stamp;
} else {
nextStamps.push(this.catSha256d(prevStamp, stamp));
prevStamp = undefined;
}
}
if (nextStamps.length === 0) {
return prevStamp;
}
if (prevStamp !== undefined) {
nextStamps.push(this.catSha256d(prevStamp, prevStamp));
}
stamps = nextStamps;
}
};
exports.catThenUnaryOp = function (UnaryOpCls, left, right) {
if (!(left instanceof Timestamp)) {
left = new Timestamp(left);
}
if (!(right instanceof Timestamp)) {
right = new Timestamp(right);
}
const opAppend = new Ops.OpAppend(right.msg);
const opPrepend = new Ops.OpPrepend(left.msg);
left.add(opAppend);
const rightPrependStamp = right.add(opPrepend);
// Left and right should produce the same thing, so we can set the timestamp
// of the left to the right
// left.ops[OpAppend(right.msg)] = right_prepend_stamp
left.ops.forEach((subStamp, subOp) => {
if (Utils.arrEq(opAppend.arg, subOp.arg)) {
subStamp.msg = rightPrependStamp.msg;
subStamp.ops = rightPrependStamp.ops;
subStamp.attestations = rightPrependStamp.attestations;
}
});
if (Utils.arrEq(right.msg, left.msg)) {
right.ops.delete(opPrepend);
}
// Return right_prepend_stamp.ops.add(unaryOpCls())
const res = rightPrependStamp.add(new Ops.OpSHA256());
return res;
};
exports.catSha256 = function (left, right) {
return this.catThenUnaryOp(Ops.OpSHA256, left, right);
};
exports.catSha256d = function (left, right) {
const sha256Timestamp = this.catSha256(left, right);
return sha256Timestamp.add(new Ops.OpSHA256());
};
// Proof functions
exports.calculateMerkleRoot = function (targetHash, proof) {
let left;
let right;
let prev = targetHash;
for (let i = 0; i < proof.length; i++) {
const item = proof[i];
if (item.left !== undefined) {
left = item.left;
right = prev;
} else if (item.right !== undefined) {
left = prev;
right = item.right;
}
const result = crypto.createHash('sha256').update(Tools.hexToString(left)).update(Tools.hexToString(right)).digest('hex');
prev = result;
}
return prev;
};