forked from ordinals-wallet/bellscriptions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bellscriptions.js
executable file
·535 lines (432 loc) · 13.1 KB
/
bellscriptions.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#!/usr/bin/env node
const dogecore = require('./bitcore-lib-bells')
const axios = require('axios')
const fs = require('fs')
const dotenv = require('dotenv')
const mime = require('mime-types')
const express = require('express')
const { PrivateKey, Address, Transaction, Script, Opcode } = dogecore
const { Hash, Signature } = dogecore.crypto
dotenv.config()
if (process.env.TESTNET == 'true') {
dogecore.Networks.defaultNetwork = dogecore.Networks.testnet
}
if (process.env.FEE_PER_KB) {
Transaction.FEE_PER_KB = parseInt(process.env.FEE_PER_KB)
} else {
Transaction.FEE_PER_KB = 100000
}
const WALLET_PATH = process.env.WALLET || '.wallet.json'
const PENDING_PATH = WALLET_PATH.replace('wallet', 'pending-txs')
async function main() {
let cmd = process.argv[2]
if (cmd == 'mint') {
if (fs.existsSync(PENDING_PATH)) {
console.log('found pending-txs.json. rebroadcasting...')
const txs = JSON.parse(fs.readFileSync(PENDING_PATH))
await broadcastAll(
txs.map((tx) => new Transaction(tx)),
false
)
return
}
const count = parseInt(process.argv[5], 10)
if (!isNaN(count)) {
for (let i = 0; i < count; i++) {
await mint()
}
} else {
await mint()
}
} else if (cmd == 'mint-bellmap') {
await mintBellmap()
} else if (cmd == 'wallet') {
await wallet()
} else if (cmd == 'server') {
await server()
} else {
throw new Error(`unknown command: ${cmd}`)
}
}
async function wallet() {
let subcmd = process.argv[3]
if (subcmd == 'new') {
walletNew()
} else if (subcmd == 'sync') {
await walletSync()
} else if (subcmd == 'balance') {
walletBalance()
} else if (subcmd == 'send') {
await walletSend()
} else if (subcmd == 'split') {
await walletSplit()
} else {
throw new Error(`unknown subcommand: ${subcmd}`)
}
}
function walletNew() {
if (!fs.existsSync(WALLET_PATH)) {
const privateKey = new PrivateKey()
const privkey = privateKey.toWIF()
const address = privateKey.toAddress().toString()
const json = { privkey, address, utxos: [] }
fs.writeFileSync(WALLET_PATH, JSON.stringify(json, 0, 2))
console.log('address', address)
} else {
throw new Error('wallet already exists')
}
}
async function walletSync() {
if (process.env.TESTNET == 'true') throw new Error('no testnet api')
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
console.log('syncing utxos with bells.quark.blue api')
let response = await axios.get(`https://bells.quark.blue/api/address/${wallet.address}/utxo`)
wallet.utxos = response.data.map((e) => ({
txid: e.txid,
vout: e.vout,
satoshis: e.value,
script: Script(new Address(wallet.address)).toHex()
}))
fs.writeFileSync(WALLET_PATH, JSON.stringify(wallet, 0, 2))
let balance = wallet.utxos.reduce((acc, curr) => acc + curr.satoshis, 0)
console.log('balance', balance)
}
function walletBalance() {
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
let balance = wallet.utxos.reduce((acc, curr) => acc + curr.satoshis, 0)
console.log(wallet.address, balance)
}
async function walletSend() {
const argAddress = process.argv[4]
const argAmount = process.argv[5]
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
let balance = wallet.utxos.reduce((acc, curr) => acc + curr.satoshis, 0)
if (balance == 0) throw new Error('no funds to send')
let receiver = new Address(argAddress)
let amount = parseInt(argAmount)
let tx = new Transaction()
if (amount) {
tx.to(receiver, amount)
fund(wallet, tx)
} else {
tx.from(wallet.utxos)
tx.change(receiver)
tx.sign(wallet.privkey)
}
await broadcast(tx, true)
console.log(tx.hash)
}
async function walletSplit() {
let splits = parseInt(process.argv[4])
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
let balance = wallet.utxos.reduce((acc, curr) => acc + curr.satoshis, 0)
if (balance == 0) throw new Error('no funds to split')
let tx = new Transaction()
tx.from(wallet.utxos)
for (let i = 0; i < splits - 1; i++) {
tx.to(wallet.address, Math.floor(balance / splits))
}
tx.change(wallet.address)
tx.sign(wallet.privkey)
await broadcast(tx, true)
console.log(tx.hash)
}
const MAX_SCRIPT_ELEMENT_SIZE = 520
async function mintBellmap() {
const argAddress = process.argv[3]
const start = parseInt(process.argv[4], 10)
const end = parseInt(process.argv[5], 10)
let address = new Address(argAddress)
for (let i = start; i <= end; i++) {
const data = Buffer.from(`${i}.bellmap`, 'utf8')
const contentType = 'text/plain'
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
let txs = inscribe(wallet, address, contentType, data)
console.log(`${i}.bellmap`)
await broadcastAll(txs, false)
}
}
async function mint() {
const argAddress = process.argv[3]
const argContentTypeOrFilename = process.argv[4]
let address = new Address(argAddress)
let contentType
let data
if (fs.existsSync(argContentTypeOrFilename)) {
contentType = mime.contentType(mime.lookup(argContentTypeOrFilename))
data = fs.readFileSync(argContentTypeOrFilename)
} else {
process.exit()
}
if (data.length == 0) {
throw new Error('no data to mint')
}
if (contentType.length > MAX_SCRIPT_ELEMENT_SIZE) {
throw new Error('content type too long')
}
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
let txs = inscribe(wallet, address, contentType, data)
await broadcastAll(txs, false)
}
async function broadcastAll(txs, retry) {
for (let i = 0; i < txs.length; i++) {
try {
await broadcast(txs[i], retry)
} catch (e) {
console.log('❌ broadcast failed', e)
fs.writeFileSync(PENDING_PATH, JSON.stringify(txs.slice(i).map((tx) => tx.toString())))
process.exit(1)
}
}
try {
fs.rmSync(PENDING_PATH)
} catch (e) {}
console.log('✅ inscription txid:', txs[1].hash)
return true
}
function bufferToChunk(b, type) {
b = Buffer.from(b, type)
return {
buf: b.length ? b : undefined,
len: b.length,
opcodenum: b.length <= 75 ? b.length : b.length <= 255 ? 76 : 77
}
}
function numberToChunk(n) {
return {
buf: n <= 16 ? undefined : n < 128 ? Buffer.from([n]) : Buffer.from([n % 256, n / 256]),
len: n <= 16 ? 0 : n < 128 ? 1 : 2,
opcodenum: n == 0 ? 0 : n <= 16 ? 80 + n : n < 128 ? 1 : 2
}
}
function opcodeToChunk(op) {
return { opcodenum: op }
}
const MAX_CHUNK_LEN = 240
const MAX_PAYLOAD_LEN = 1500
function inscribe(wallet, address, contentType, data) {
let txs = []
let privateKey = new PrivateKey(wallet.privkey)
let publicKey = privateKey.toPublicKey()
let parts = []
while (data.length) {
let part = data.slice(0, Math.min(MAX_CHUNK_LEN, data.length))
data = data.slice(part.length)
parts.push(part)
}
let inscription = new Script()
inscription.chunks.push(bufferToChunk('ord'))
inscription.chunks.push(numberToChunk(parts.length))
inscription.chunks.push(bufferToChunk(contentType))
parts.forEach((part, n) => {
inscription.chunks.push(numberToChunk(parts.length - n - 1))
inscription.chunks.push(bufferToChunk(part))
})
let p2shInput
let lastLock
let lastPartial
while (inscription.chunks.length) {
let partial = new Script()
if (txs.length == 0) {
partial.chunks.push(inscription.chunks.shift())
}
while (partial.toBuffer().length <= MAX_PAYLOAD_LEN && inscription.chunks.length) {
partial.chunks.push(inscription.chunks.shift())
partial.chunks.push(inscription.chunks.shift())
}
if (partial.toBuffer().length > MAX_PAYLOAD_LEN) {
inscription.chunks.unshift(partial.chunks.pop())
inscription.chunks.unshift(partial.chunks.pop())
}
let lock = new Script()
lock.chunks.push(bufferToChunk(publicKey.toBuffer()))
lock.chunks.push(opcodeToChunk(Opcode.OP_CHECKSIGVERIFY))
partial.chunks.forEach(() => {
lock.chunks.push(opcodeToChunk(Opcode.OP_DROP))
})
lock.chunks.push(opcodeToChunk(Opcode.OP_TRUE))
let lockhash = Hash.ripemd160(Hash.sha256(lock.toBuffer()))
let p2sh = new Script()
p2sh.chunks.push(opcodeToChunk(Opcode.OP_HASH160))
p2sh.chunks.push(bufferToChunk(lockhash))
p2sh.chunks.push(opcodeToChunk(Opcode.OP_EQUAL))
let p2shOutput = new Transaction.Output({
script: p2sh,
satoshis: 100000
})
let tx = new Transaction()
if (p2shInput) tx.addInput(p2shInput)
tx.addOutput(p2shOutput)
fund(wallet, tx)
if (p2shInput) {
let signature = Transaction.sighash.sign(tx, privateKey, Signature.SIGHASH_ALL, 0, lastLock)
let txsignature = Buffer.concat([signature.toBuffer(), Buffer.from([Signature.SIGHASH_ALL])])
let unlock = new Script()
unlock.chunks = unlock.chunks.concat(lastPartial.chunks)
unlock.chunks.push(bufferToChunk(txsignature))
unlock.chunks.push(bufferToChunk(lastLock.toBuffer()))
tx.inputs[0].setScript(unlock)
}
updateWallet(wallet, tx)
txs.push(tx)
p2shInput = new Transaction.Input({
prevTxId: tx.hash,
outputIndex: 0,
output: tx.outputs[0],
script: ''
})
p2shInput.clearSignatures = () => {}
p2shInput.getSignatures = () => {}
lastLock = lock
lastPartial = partial
}
let tx = new Transaction()
tx.addInput(p2shInput)
tx.to(address, 100000)
fund(wallet, tx)
let signature = Transaction.sighash.sign(tx, privateKey, Signature.SIGHASH_ALL, 0, lastLock)
let txsignature = Buffer.concat([signature.toBuffer(), Buffer.from([Signature.SIGHASH_ALL])])
let unlock = new Script()
unlock.chunks = unlock.chunks.concat(lastPartial.chunks)
unlock.chunks.push(bufferToChunk(txsignature))
unlock.chunks.push(bufferToChunk(lastLock.toBuffer()))
tx.inputs[0].setScript(unlock)
updateWallet(wallet, tx)
txs.push(tx)
return txs
}
function fund(wallet, tx) {
tx.change(wallet.address)
delete tx._fee
for (const utxo of wallet.utxos) {
if (tx.inputs.length && tx.outputs.length && tx.inputAmount >= tx.outputAmount + tx.getFee()) {
break
}
delete tx._fee
tx.from(utxo)
tx.change(wallet.address)
tx.sign(wallet.privkey)
}
if (tx.inputAmount < tx.outputAmount + tx.getFee()) {
throw new Error('not enough funds')
}
}
function updateWallet(wallet, tx) {
wallet.utxos = wallet.utxos.filter((utxo) => {
for (const input of tx.inputs) {
if (input.prevTxId.toString('hex') == utxo.txid && input.outputIndex == utxo.vout) {
return false
}
}
return true
})
tx.outputs.forEach((output, vout) => {
if (output.script.toAddress().toString() == wallet.address) {
wallet.utxos.push({
txid: tx.hash,
vout,
script: Script(new Address(wallet.address)).toHex(),
satoshis: output.satoshis
})
}
})
}
async function broadcast(tx, retry) {
const body = {
jsonrpc: '1.0',
id: 0,
method: 'sendrawtransaction',
params: [tx.toString()]
}
const options = {
auth: {
username: process.env.NODE_RPC_USER,
password: process.env.NODE_RPC_PASS
}
}
while (true) {
try {
await axios.post(process.env.NODE_RPC_URL, body, options)
break
} catch (e) {
if (!retry) {
let m = e && e.response && e.response.data
throw m ? JSON.stringify(m) : e
}
let msg =
e.response && e.response.data && e.response.data.error && e.response.data.error.message
if (msg && msg.includes('too-long-mempool-chain')) {
console.warn('retrying, too-long-mempool-chain')
await new Promise((resolve) => setTimeout(resolve, 1000))
} else {
throw e
}
}
}
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
updateWallet(wallet, tx)
fs.writeFileSync(WALLET_PATH, JSON.stringify(wallet, 0, 2))
}
function chunkToNumber(chunk) {
if (chunk.opcodenum == 0) return 0
if (chunk.opcodenum == 1) return chunk.buf[0]
if (chunk.opcodenum == 2) return chunk.buf[1] * 255 + chunk.buf[0]
if (chunk.opcodenum > 80 && chunk.opcodenum <= 96) return chunk.opcodenum - 80
return undefined
}
async function extract(txid) {
let resp = await axios.get(`https://dogechain.info/api/v1/transaction/${txid}`)
let transaction = resp.data.transaction
let script = Script.fromHex(transaction.inputs[0].scriptSig.hex)
let chunks = script.chunks
let prefix = chunks.shift().buf.toString('utf8')
if (prefix != 'ord') {
throw new Error('not a doginal')
}
let pieces = chunkToNumber(chunks.shift())
let contentType = chunks.shift().buf.toString('utf8')
let data = Buffer.alloc(0)
let remaining = pieces
while (remaining && chunks.length) {
let n = chunkToNumber(chunks.shift())
if (n !== remaining - 1) {
txid = transaction.outputs[0].spent.hash
resp = await axios.get(`https://dogechain.info/api/v1/transaction/${txid}`)
transaction = resp.data.transaction
script = Script.fromHex(transaction.inputs[0].scriptSig.hex)
chunks = script.chunks
continue
}
data = Buffer.concat([data, chunks.shift().buf])
remaining -= 1
}
return {
contentType,
data
}
}
function server() {
const app = express()
const port = process.env.SERVER_PORT ? parseInt(process.env.SERVER_PORT) : 3000
app.get('/tx/:txid', (req, res) => {
extract(req.params.txid)
.then((result) => {
res.setHeader('content-type', result.contentType)
res.send(result.data)
})
.catch((e) => res.send(e.message))
})
app.listen(port, () => {
console.log(`Listening on port ${port}`)
console.log()
console.log(`Example:`)
console.log(
`http://localhost:${port}/tx/15f3b73df7e5c072becb1d84191843ba080734805addfccb650929719080f62e`
)
})
}
main().catch((e) => {
let reason =
e.response && e.response.data && e.response.data.error && e.response.data.error.message
console.error(reason ? e.message + ':' + reason : e.message)
})