forked from sCrypt-Inc/boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.js
389 lines (331 loc) · 9.72 KB
/
helper.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
const path = require('path')
const {
readFileSync,
existsSync,
mkdirSync
} = require('fs')
const {
bsv,
compileContract: compileContractImpl,
getPreimage,
toHex
} = require('scryptlib')
const crypto = require('crypto');
const MSB_THRESHOLD = 0x7e;
const BN = bsv.crypto.BN
const Interpreter = bsv.Script.Interpreter
// number of bytes to denote some numeric value
const DataLen = 1
const axios = require('axios')
const API_PREFIX = 'https://api.whatsonchain.com/v1/bsv/test'
const inputIndex = 0
const inputSatoshis = 100000
const dummyTxId = crypto.randomBytes(32).toString('hex');
const reversedDummyTxId = Buffer.from(dummyTxId, 'hex').reverse().toString('hex');
const sighashType2Hex = s => s.toString(16)
function newTx() {
const utxo = {
txId: dummyTxId,
outputIndex: 0,
script: '', // placeholder
satoshis: inputSatoshis
};
return new bsv.Transaction().from(utxo);
}
// reverse hexStr byte order
function reverseEndian(hexStr) {
return hexStr.match(/../g).reverse().join('')
}
async function sendTx(tx) {
const hex = tx.toString();
// if(!tx.checkFeeRate(50)) {
// throw new Error(`checkFeeRate fail, transaction fee:${tx.getFee()} is too low`)
// }
try {
const {
data: txid
} = await axios.post(`${API_PREFIX}/tx/raw`, {
txhex: hex
});
return txid
} catch (error) {
if (error.response && error.response.data === '66: insufficient priority') {
throw new Error(`Rejected by miner. Transaction with fee is too low: expected Fee is ${expectedFee}, but got ${fee}, hex: ${hex}`)
}
throw error
}
}
function compileContract(fileName, options) {
const filePath = path.join(__dirname, 'contracts', fileName)
const out = path.join(__dirname, 'out')
const result = compileContractImpl(filePath, options ? options : {
out: out
});
if (result.errors.length > 0) {
console.log(`Compile contract ${filePath} failed: `, result.errors)
throw result.errors;
}
return result;
}
function compileTestContract(fileName) {
const filePath = path.join(__dirname, 'tests', 'testFixture', fileName)
const out = path.join(__dirname, 'tests', 'out')
if (!existsSync(out)) {
mkdirSync(out)
}
const result = compileContractImpl(filePath, {
out: out
});
if (result.errors.length > 0) {
console.log(`Compile contract ${filePath} fail: `, result.errors)
throw result.errors;
}
return result;
}
function loadDesc(fileName) {
let filePath = '';
if(!fileName.endsWith(".json")) {
filePath = path.join(__dirname, `out/${fileName}_desc.json`);
if (!existsSync(filePath)) {
filePath = path.join(__dirname, `out/${fileName}_debug_desc.json`);
}
} else {
filePath = path.join(__dirname, `out/${fileName}`);
}
if (!existsSync(filePath)) {
throw new Error(`Description file ${filePath} not exist!\nIf You already run 'npm run watch', maybe fix the compile error first!`)
}
return JSON.parse(readFileSync(filePath).toString());
}
function showError(error) {
// Error
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log('Failed - StatusCodeError: ' + error.response.status + ' - "' + error.response.data + '"');
// console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the
// browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error:', error.message);
if (error.context) {
console.log(error.context);
}
}
};
function padLeadingZero(hex, byteslen = 0) {
if(byteslen > 0) {
if(hex.length < byteslen * 2) {
return "0".repeat(byteslen * 2 - hex.length) + hex
}
}
if(hex.length % 2 === 0) return hex;
return "0" + hex;
}
// fixLowS increments the first input's sequence number until the sig hash is safe for low s.
function fixLowS(tx, lockingScript, inputSatoshis, inputIndex) {
for (i=0;i<25;i++) {
const preimage = getPreimage(tx, lockingScript, inputSatoshis, inputIndex);
const sighash = bsv.crypto.Hash.sha256sha256(Buffer.from(toHex(preimage), 'hex'));
const msb = sighash.readUInt8();
if (msb < MSB_THRESHOLD) {
return;
}
tx.inputs[0].sequenceNumber++;
}
}
// checkLowS returns true if the sig hash is safe for low s.
function checkLowS(tx, lockingScript, inputSatoshis, inputIndex) {
const preimage = getPreimage(tx, lockingScript, inputSatoshis, inputIndex);
const sighash = bsv.crypto.Hash.sha256sha256(Buffer.from(toHex(preimage), 'hex'));
const msb = sighash.readUInt8();
return (msb < MSB_THRESHOLD);
}
const sleep = async(seconds) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, seconds * 1000);
})
}
async function deployContract(contract, amount) {
const { privateKey } = require('./privateKey');
const address = privateKey.toAddress()
const tx = new bsv.Transaction()
tx.from(await fetchUtxos(address))
.addOutput(new bsv.Transaction.Output({
script: contract.lockingScript,
satoshis: amount,
}))
.change(address)
.sign(privateKey)
await sendTx(tx)
return tx
}
const metaFlag = '4d455441';
async function createMetaNetRootNode(root, contract, contractAmount) {
const { privateKey } = require('./privateKey');
const address = privateKey.toAddress()
const tx = new bsv.Transaction()
tx.from(await fetchUtxos(address))
.addOutput(new bsv.Transaction.Output({
script: bsv.Script.fromASM(`OP_0 OP_RETURN ${metaFlag} ${root} 0000000000000000000000000000000000000000000000000000000000000000`),
satoshis: 0,
}))
.addOutput(
new bsv.Transaction.Output({
script: contract.lockingScript,
satoshis: contractAmount,
})
)
.change(address)
.sign(privateKey)
await sendTx(tx)
return tx
}
async function createMetaNetChildNode(node, prevtx, metaData, lockingScript, contractAmount, callback ) {
const { privateKey } = require('./privateKey');
const address = privateKey.toAddress()
const tx = new bsv.Transaction()
tx.addInput(createInputFromPrevTx(prevtx, 1))
.from(await fetchUtxos(address))
.addOutput(new bsv.Transaction.Output({
script: bsv.Script.fromASM(`OP_0 OP_RETURN ${metaFlag} ${node} ${prevtx.id} ${metaData}`),
satoshis: 0,
}))
.addOutput(
new bsv.Transaction.Output({
script: lockingScript,
satoshis: contractAmount,
})
)
.setInputScript(0, (tx, output) => {
return callback(tx, output);
})
.change(address)
.sign(privateKey)
.seal()
await sendTx(tx)
return tx
}
//create an input spending from prevTx's output, with empty script
function createInputFromPrevTx(tx, outputIndex) {
const outputIdx = outputIndex || 0
return new bsv.Transaction.Input({
prevTxId: tx.id,
outputIndex: outputIdx,
script: new bsv.Script(), // placeholder
output: tx.outputs[outputIdx]
})
}
async function fetchUtxos(address) {
// step 1: fetch utxos
let {
data: utxos
} = await axios.get(`${API_PREFIX}/address/${address}/unspent`)
return utxos.map((utxo) => ({
txId: utxo.tx_hash,
outputIndex: utxo.tx_pos,
satoshis: utxo.value,
script: bsv.Script.buildPublicKeyHashOut(address).toHex(),
}))
}
const emptyPublicKey = '000000000000000000000000000000000000000000000000000000000000000000'
function toLittleIndian(hexstr) {
return reverseEndian(hexstr)
}
function toBigIndian(hexstr) {
return reverseEndian(hexstr)
}
function uint32Tobin(d) {
var s = (+d).toString(16);
if(s.length < 4) {
s = '0' + s;
}
return toLittleIndian(s);
}
function num2hex(d, padding) {
var s = Number(d).toString(16);
// add padding if needed.
while (s.length < padding) {
s = "0" + s;
}
return s;
}
/**
* inspired by : https://bigishdata.com/2017/11/13/how-to-build-a-blockchain-part-4-1-bitcoin-proof-of-work-difficulty-explained/
* @param {*} bitsHex bits of block header, in big endian
* @returns a target number
*/
function toTarget(bitsHex) {
const shift = bitsHex.substr(0, 2);
const exponent = parseInt(shift, 16);
const value = bitsHex.substr(2, bitsHex.length);
const coefficient = parseInt(value, 16);
const target = coefficient * 2 ** (8 * (exponent - 3));
return BigInt(target);
}
/**
* convert pool difficulty to a target number
* @param {*} difficulty which can fetch by api https://api.whatsonchain.com/v1/bsv/<network>/chain/info
* @returns target
*/
function pdiff2Target(difficulty) {
if (typeof difficulty === 'number') {
difficulty = BigInt(Math.floor(difficulty))
}
return BigInt(toTarget("1d00ffff") / difficulty);
}
// serialize Header to get raw header
function serializeHeader(header) {
return uint32Tobin(header.version)
+ toLittleIndian(header.previousblockhash)
+ toLittleIndian(header.merkleroot)
+ uint32Tobin(header.time)
+ toLittleIndian(header.bits)
+ uint32Tobin(header.nonce)
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
module.exports = {
inputIndex,
inputSatoshis,
sleep,
newTx,
DataLen,
dummyTxId,
reversedDummyTxId,
reverseEndian,
sendTx,
compileContract,
loadDesc,
sighashType2Hex,
showError,
compileTestContract,
padLeadingZero,
emptyPublicKey,
fixLowS,
checkLowS,
deployContract,
createInputFromPrevTx,
fetchUtxos,
toLittleIndian,
toBigIndian,
uint32Tobin,
num2hex,
toTarget,
pdiff2Target,
serializeHeader,
getRandomInt,
createMetaNetRootNode,
createMetaNetChildNode,
metaFlag
}