-
Notifications
You must be signed in to change notification settings - Fork 1
/
scrypt_helper.js
273 lines (235 loc) · 6.88 KB
/
scrypt_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
const path = require('path')
const { readFileSync, existsSync, mkdirSync } = require('fs')
const { mvc, compile, compileContract: compileContractImpl } = require('mvc-scrypt')
const { exit } = require('process')
const minimist = require('minimist')
const Signature = mvc.crypto.Signature
const BN = mvc.crypto.BN
const Interpreter = mvc.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/mvc/test'
const inputIndex = 0
const inputSatoshis = 100100
const flags =
Interpreter.SCRIPT_VERIFY_MINIMALDATA |
Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID |
Interpreter.SCRIPT_ENABLE_MAGNETIC_OPCODES |
Interpreter.SCRIPT_ENABLE_MONOLITH_OPCODES
const minFee = 546
const dummyTxId = 'a477af6b2667c29670467e4e0728b685ee07b240235771862318e29ddbe58458'
const reversedDummyTxId = '5884e5db9de218238671572340b207ee85b628074e7e467096c267266baf77a4'
const sighashType2Hex = (s) => s.toString(16)
function newTx() {
const utxo = {
txId: 'a477af6b2667c29670467e4e0728b685ee07b240235771862318e29ddbe58458',
outputIndex: 0,
script: '', // placeholder
satoshis: inputSatoshis,
}
return new mvc.Transaction().from(utxo)
}
// reverse hexStr byte order
function reverseEndian(hexStr) {
let num = new BN(hexStr, 'hex')
let buf = num.toBuffer()
return buf.toString('hex').match(/.{2}/g).reverse().join('')
}
async function createPayByOthersTx(address) {
// step 1: fetch utxos
let { data: utxos } = await axios.get(`${API_PREFIX}/address/${address}/unspent`)
utxos = utxos.map((utxo) => ({
txId: utxo.tx_hash,
outputIndex: utxo.tx_pos,
satoshis: utxo.value,
script: mvc.Script.buildPublicKeyHashOut(address).toHex(),
}))
// step 2: build the tx
const tx = new mvc.Transaction().from(utxos)
return tx
}
async function createLockingTx(address, amountInContract, fee) {
// step 1: fetch utxos
let { data: utxos } = await axios.get(`${API_PREFIX}/address/${address}/unspent`)
utxos = utxos.map((utxo) => ({
txId: utxo.tx_hash,
outputIndex: utxo.tx_pos,
satoshis: utxo.value,
script: mvc.Script.buildPublicKeyHashOut(address).toHex(),
}))
// step 2: build the tx
const tx = new mvc.Transaction().from(utxos)
tx.addOutput(
new mvc.Transaction.Output({
script: new mvc.Script(), // place holder
satoshis: amountInContract,
})
)
tx.change(address).fee(fee || minFee)
return tx
}
async function anyOnePayforTx(tx, address, fee) {
// step 1: fetch utxos
let { data: utxos } = await axios.get(`${API_PREFIX}/address/${address}/unspent`)
utxos.map((utxo) => {
tx.addInput(
new mvc.Transaction.Input({
prevTxId: utxo.tx_hash,
outputIndex: utxo.tx_pos,
script: new mvc.Script(), // placeholder
}),
mvc.Script.buildPublicKeyHashOut(address).toHex(),
utxo.value
)
})
tx.change(address).fee(fee)
return tx
}
function createUnlockingTx(
prevTxId,
inputAmount,
inputLockingScriptASM,
outputAmount,
outputLockingScriptASM
) {
const tx = new mvc.Transaction()
tx.addInput(
new mvc.Transaction.Input({
prevTxId,
outputIndex: inputIndex,
script: new mvc.Script(), // placeholder
}),
mvc.Script.fromASM(inputLockingScriptASM),
inputAmount
)
tx.addOutput(
new mvc.Transaction.Output({
script: mvc.Script.fromASM(outputLockingScriptASM || inputLockingScriptASM),
satoshis: outputAmount,
})
)
tx.fee(inputAmount - outputAmount)
return tx
}
function unlockP2PKHInput(privateKey, tx, inputIndex, sigtype) {
const sig = new mvc.Transaction.Signature({
publicKey: privateKey.publicKey,
prevTxId: tx.inputs[inputIndex].prevTxId,
outputIndex: tx.inputs[inputIndex].outputIndex,
inputIndex,
signature: mvc.Transaction.Sighash.sign(
tx,
privateKey,
sigtype,
inputIndex,
tx.inputs[inputIndex].output.script,
tx.inputs[inputIndex].output.satoshisBN
),
sigtype,
})
tx.inputs[inputIndex].setScript(
mvc.Script.buildPublicKeyHashIn(sig.publicKey, sig.signature.toDER(), sig.sigtype)
)
}
async function sendTx(tx) {
const { data: txid } = await axios.post(`${API_PREFIX}/tx/raw`, {
txhex: tx.serialize(),
})
return txid
}
function compileContract(fileName, options) {
const filePath = path.join(__dirname, 'contracts', fileName)
const out = path.join(__dirname, 'deployments/fixture/autoGen')
const result = compileContractImpl(
filePath,
options
? options
: {
out: out,
}
)
if (result.errors.length > 0) {
console.log(`Compile contract ${filePath} fail: `, 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) {
const filePath = path.join(__dirname, `deployments/fixture/autoGen/${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)
}
}
console.log('Error stack ', error.stack)
if (error.context) {
console.log('Error context: ', error.context)
}
}
function padLeadingZero(hex) {
if (hex.length % 2 === 0) return hex
return '0' + hex
}
const emptyPublicKey = '000000000000000000000000000000000000000000000000000000000000000000'
module.exports = {
inputIndex,
inputSatoshis,
newTx,
createPayByOthersTx,
createLockingTx,
createUnlockingTx,
DataLen,
dummyTxId,
reversedDummyTxId,
reverseEndian,
unlockP2PKHInput,
sendTx,
compileContract,
loadDesc,
sighashType2Hex,
showError,
compileTestContract,
padLeadingZero,
anyOnePayforTx,
emptyPublicKey,
}