forked from SpendBCH/bch-stresstest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stresstest.js
338 lines (272 loc) · 9.93 KB
/
stresstest.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
// Use below bitbox settings for broadcasting directly to a local node over RPC -- use bitbox-cli version 0.7.21 for this
// let BITBOXCli = require('bitbox-cli/lib/bitboxcli').default
// Set connection details for a BCH node with RPC access
// let BITBOX = new BITBOXCli({
// protocol: 'http',
// host: '127.0.0.1',
// port: 8332,
// username: 'your rpc username',
// password: 'your rpc password',
// corsproxy: false,
// })
// Use below bitbox settings to connect to bitbox rest instance, modify source to rate limit to 1 request/3.5 seconds
// Use latest bitbox version with these settings
let BITBOXCli = require('bitbox-cli/lib/bitbox-cli').default
let BITBOX = new BITBOXCli()
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
let data = "stresstestbitcoin.cash";
let buf = BITBOX.Script.nullData.output.encode(Buffer.from(data, 'ascii'));
let sendTxAsync = async (hex) => {
return new Promise((resolve, reject) => {
BITBOX.RawTransactions.sendRawTransaction(hex).then((result) => {
console.log('txid:', result)
if (result.length != 64) { // Very rough txid size check for failure
reject("sendTxAsync failure: " + result)
}
else {
resolve(result)
}
}, (err) => {
reject(err)
})
})
}
let sendTxChainAsync = async (hexList) => {
return new Promise(async (resolve, reject) => {
let totalSent = 0
for (let i = 0; i < hexList.length; i++) {
try {
await sendTxAsync(hexList[i])
totalSent += 1
await sleep(200)
} catch (ex) {
console.log("sendTxChainAsync, chain " + i + " ex:", ex)
reject(ex)
break
}
}
resolve(totalSent)
})
}
let getUtxos = async (address) => {
return new Promise((resolve, reject) => {
BITBOX.Address.utxo(address).then((result) => {
console.log("utxo: ", result)
resolve(result)
}, (err) => {
console.log(err)
reject(err)
})
})
}
let pollForUtxo = async (address) => {
// poll for utxo
try {
while (true) {
// rate limit
await sleep(20 * 1000)
let utxos = await getUtxos(address)
// return highest value utxo when first utxo is found
if (utxos && utxos.length > 0)
return utxos.sort((a, b) => { return a.satoshis - b.satoshis })[utxos.length - 1]
else
console.log("Waiting for funding...")
}
} catch (ex) {
console.log("Poll for utxo ex: ", ex)
}
}
let getTxDetails = async (txid) => {
return new Promise((resolve, reject) => {
BITBOX.Transaction.details(txid).then((result) => {
console.log("tx details", result)
resolve(result)
}, (err) => {
reject(err)
})
})
}
let pollForConfirmation = async (txid) => {
// poll for utxo
while (true) {
try {
// rate limit
await sleep(60 * 1000)
let txDetails = await getTxDetails(txid)
// return highest value utxo when first utxo is found
if (txDetails && txDetails.confirmations > 0)
return txDetails
else
console.log("Waiting for split tx confirmation...")
} catch (ex) {
console.log("Poll for confirmation ex: ", ex)
}
}
}
let main = async () => {
let mnemonic = BITBOX.Mnemonic.generate(256)
let rootSeed = BITBOX.Mnemonic.toSeed(mnemonic)
let masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, 'bitcoincash')
let hdNode = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
// derive the first external change address HDNode which is going to spend utxo
let node0 = BITBOX.HDNode.derivePath(hdNode, "1/0")
let node0CashAddress = BITBOX.HDNode.toCashAddress(node0)
let node0LegacyAddress = BITBOX.HDNode.toLegacyAddress(node0)
let node0WIF = BITBOX.ECPair.toWIF(BITBOX.HDNode.toKeyPair(node0))
let msg = "stresstestbitcoin.cash";
let signature = BITBOX.BitcoinCash.signMessageWithPrivKey(node0WIF, msg);
console.log("Write down your mnemonic in case of a problem where a manual recovery is required")
console.log("Your mnemonic: " + mnemonic)
console.log("Your wif: " + node0WIF)
console.log(`Send BCH to ${node0CashAddress} to start`)
console.log("Write down the following message, address and signature to prove you sent these transactions")
console.log(`Message: ${msg}, signed from address: ${node0CashAddress}, signature: ${signature}`)
// Wait for utxo to arrive to build starting wallet
let utxo = await pollForUtxo(node0LegacyAddress)
// TODO: Get refund address from tx details
let refundAddress = utxo.legacyAddress
console.log("UTXO found. Change will be sent to:", refundAddress)
let wallet = {
satoshis: utxo.satoshis,
txid: utxo.txid,
vout: utxo.vout
}
let dustLimitSats = 546
let maxTxChain = 24
let feePerTx = BITBOX.BitcoinCash.getByteCount({ P2PKH: 1 }, { P2PKH: 3 })
let satsPerAddress = feePerTx * maxTxChain + dustLimitSats
let numAddresses = Math.floor(wallet.satoshis / (satsPerAddress + feePerTx))
// Calculate splitTx fee and change to return to refundAddress
let byteCount = BITBOX.BitcoinCash.getByteCount({ P2PKH: 1 }, { P2PKH: numAddresses + 3 })
let satsChange = wallet.satoshis - byteCount - (numAddresses * satsPerAddress)
console.log(`Creating ${numAddresses} addresses to send ${numAddresses * maxTxChain} transactions with ${satsChange} sats change to be refunded`)
let splitAddressResult = splitAddress(wallet, numAddresses, satsPerAddress, hdNode, node0, refundAddress, satsChange, maxTxChain)
let splitTxHex = splitAddressResult.hex
let walletChains = splitAddressResult.wallets
// Generate transactions for each address
let hexListByAddress = createChainedTransactions(walletChains, maxTxChain, refundAddress)
// Broadcast split tx
let splitTxid = await sendTxAsync(splitTxHex)
console.log("Split txid: ", splitTxid)
// Wait for first confirmation before stress testing to avoid mempool chain limit
console.log("Split tx completed. Waiting for first confirmation...")
await pollForConfirmation(splitTxid)
console.log("Split tx confirmed. Starting stress test in 10 seconds...")
await sleep(10 * 1000)
// Use below to send each tx chain in serial
let totalSent = 0
for (let i = 0; i < hexListByAddress.length; i++) {
try {
let sent = await sendTxChainAsync(hexListByAddress[i])
totalSent += sent
} catch (ex) {
console.log(`Wallet chain_${i} exception:`, ex)
}
}
console.log("Sent " + totalSent + " transactions successfully")
// Use below to send each tx chain in parallel
// await Promise.all(hexListByAddress.map(async (hexList) => {
// try {
// await sendTxChainAsync(hexList)
// } catch (ex) {
// console.log(ex)
// }
// }))
// TODO: Merge final UTXOs
console.log("Broadcast complete")
}
let txidFromHex = (hex) => {
let buffer = Buffer.from(hex, "hex")
let hash = BITBOX.Crypto.hash256(buffer).toString('hex')
return hash.match(/[a-fA-F0-9]{2}/g).reverse().join('')
}
let splitAddress = (wallet, numAddresses, satsPerAddress, hdNode, node0, changeAddress, satsChange, maxTxChain) => {
let transactionBuilder = new BITBOX.TransactionBuilder('bitcoincash');
transactionBuilder.addInput(wallet.txid, wallet.vout);
let walletChains = []
for (let i = 0; i < numAddresses; i++) {
let walletChain = []
let firstNode = BITBOX.HDNode.derivePath(hdNode, `1/${i + 1}`)
let firstNodeLegacyAddress = BITBOX.HDNode.toLegacyAddress(firstNode)
walletChain.push({
vout: i,
address: firstNodeLegacyAddress,
satoshis: satsPerAddress,
keyPair: BITBOX.HDNode.toKeyPair(firstNode)
})
transactionBuilder.addOutput(firstNodeLegacyAddress, satsPerAddress)
// Derive next maxTxChain-1 addresses and keypairs for this chain
for (let j = 0; j < maxTxChain - 1; j++) {
let nextNode = BITBOX.HDNode.derivePath(hdNode, `0/${i * maxTxChain + j}`)
let nextNodeLegacyAddress = BITBOX.HDNode.toLegacyAddress(nextNode)
walletChain.push({
keyPair: BITBOX.HDNode.toKeyPair(nextNode),
address: nextNodeLegacyAddress
})
}
walletChains.push(walletChain)
}
// write stresstestbitcoin.cash to the chain w/ OP_RETURN
transactionBuilder.addOutput(buf, 0);
// Check change against dust limit
if (satsChange > 600) {
transactionBuilder.addOutput(changeAddress, satsChange)
}
let keyPair = BITBOX.HDNode.toKeyPair(node0);
let redeemScript
transactionBuilder.sign(0, keyPair, redeemScript, transactionBuilder.hashTypes.SIGHASH_ALL, wallet.satoshis)
let hex = transactionBuilder.build().toHex()
// txid of this split/fanout tx
let splitTxid = txidFromHex(hex)
let walletsWithTxid = walletChains.map((wc) => {
wc[0].txid = splitTxid
return wc
})
return {
hex: hex,
wallets: walletsWithTxid,
}
}
let createChainedTransactions = (walletChains, numTxToChain, refundAddress) => {
let hexByAddress = []
for (let i = 0; i < walletChains.length; i++) {
let walletChain = walletChains[i]
let hexList = []
let wallet = walletChain[0]
for (let j = 0; j < numTxToChain; j++) {
// Update keyPair to sign current tx
wallet.keyPair = walletChain[j].keyPair
// Send tx to next address until last tx, then send back to refundAddress
let targetAddress
if (j == numTxToChain - 1)
targetAddress = refundAddress
else
targetAddress = walletChain[j + 1].address
let txResult = createTx(wallet, targetAddress)
// Update wallet for next send
wallet.txid = txResult.txid
wallet.satoshis = txResult.satoshis
wallet.vout = txResult.vout
hexList.push(txResult.hex)
}
hexByAddress.push(hexList.slice())
}
return hexByAddress
}
let createTx = (wallet, targetAddress) => {
let transactionBuilder = new BITBOX.TransactionBuilder('bitcoincash')
transactionBuilder.addInput(wallet.txid, wallet.vout)
// Calculate fee @ 1 sat/byte
let byteCount = BITBOX.BitcoinCash.getByteCount({ P2PKH: 1 }, { P2PKH: 3 })
let satoshisAfterFee = wallet.satoshis - byteCount
transactionBuilder.addOutput(targetAddress, satoshisAfterFee)
// write stresstestbitcoin.cash to the chain w/ OP_RETURN
transactionBuilder.addOutput(buf, 0);
let redeemScript
transactionBuilder.sign(0, wallet.keyPair, redeemScript, transactionBuilder.hashTypes.SIGHASH_ALL, wallet.satoshis)
let hex = transactionBuilder.build().toHex()
let txid = txidFromHex(hex)
return { txid: txid, satoshis: satoshisAfterFee, vout: 0, hex: hex }
}
// Launch app
main()