-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
doginals.js
632 lines (491 loc) · 17.1 KB
/
doginals.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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
#!/usr/bin/env node
const dogecore = require('bitcore-lib-doge')
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 = 100000000
}
const WALLET_PATH = process.env.WALLET || '.wallet.json'
async function main() {
let cmd = process.argv[2]
if (fs.existsSync('pending-txs.json')) {
console.log('found pending-txs.json. rebroadcasting...')
const txs = JSON.parse(fs.readFileSync('pending-txs.json'))
await broadcastAll(txs.map(tx => new Transaction(tx)), false)
return
}
if (cmd == 'mint') {
await mint()
} else if (cmd == 'wallet') {
await wallet()
} else if (cmd == 'server') {
await server()
} else if (cmd == 'drc-20') {
await doge20()
} else {
throw new Error(`unknown command: ${cmd}`)
}
}
async function doge20() {
let subcmd = process.argv[3]
if (subcmd === 'mint') {
await doge20Transfer("mint")
} else if (subcmd === 'transfer') {
await doge20Transfer()
} else if (subcmd === 'deploy') {
await doge20Deploy()
} else {
throw new Error(`unknown subcommand: ${subcmd}`)
}
}
async function doge20Deploy() {
const argAddress = process.argv[4]
const argTicker = process.argv[5]
const argMax = process.argv[6]
const argLimit = process.argv[7]
const doge20Tx = {
p: "drc-20",
op: "deploy",
tick: `${argTicker.toLowerCase()}`,
max: `${argMax}`,
lim: `${argLimit}`
};
const parsedDoge20Tx = JSON.stringify(doge20Tx);
// encode the doge20Tx as hex string
const encodedDoge20Tx = Buffer.from(parsedDoge20Tx).toString('hex');
console.log("Deploying drc-20 token...");
await mint(argAddress, "text/plain;charset=utf-8", encodedDoge20Tx);
}
async function doge20Transfer() {
const argAddress = process.argv[4]
const argTicker = process.argv[5]
const argAmount = process.argv[6]
const argRepeat = Number(process.argv[7]) || 1;
const doge20Tx = {
p: "drc-20",
op: "transfer",
tick: `${argTicker.toLowerCase()}`,
amt: `${argAmount}`
};
const parsedDoge20Tx = JSON.stringify(doge20Tx);
// encode the doge20Tx as hex string
const encodedDoge20Tx = Buffer.from(parsedDoge20Tx).toString('hex');
for (let i = 0; i < argRepeat; i++) {
console.log("Minting drc-20 token...", i + 1, "of", argRepeat, "times");
await mint(argAddress, "text/plain;charset=utf-8", encodedDoge20Tx);
}
}
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() {
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH))
console.log('syncing utxos with local Dogecoin node via RPC')
const body = {
jsonrpc: "1.0",
id: "walletsync",
method: "listunspent",
params: [0, 9999999, [wallet.address]] // [minconf, maxconf, [addresses]]
}
const options = {
auth: {
username: process.env.NODE_RPC_USER,
password: process.env.NODE_RPC_PASS
}
}
let response = await axios.post(process.env.NODE_RPC_URL, body, options)
let utxos = response.data.result
wallet.utxos = utxos.map(utxo => {
return {
txid: utxo.txid,
vout: utxo.vout,
script: utxo.scriptPubKey,
satoshis: utxo.amount * 1e8 // Convert from DOGE to Satoshis
}
})
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 mint(paramAddress, paramContentTypeOrFilename, paramHexData) {
const argAddress = paramAddress || process.argv[3]
const argContentTypeOrFilename = paramContentTypeOrFilename || process.argv[4]
const argHexData = paramHexData || process.argv[5]
let address = new Address(argAddress)
let contentType
let data
if (fs.existsSync(argContentTypeOrFilename)) {
contentType = mime.contentType(mime.lookup(argContentTypeOrFilename))
data = fs.readFileSync(argContentTypeOrFilename)
} else {
contentType = argContentTypeOrFilename
if (!/^[a-fA-F0-9]*$/.test(argHexData)) throw new Error('data must be hex')
data = Buffer.from(argHexData, 'hex')
}
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++) {
console.log(`broadcasting tx ${i + 1} of ${txs.length}`)
try {
await broadcast(txs[i], retry)
} catch (e) {
console.log('broadcast failed', e?.response.data)
if (e?.response?.data.error?.message?.includes("bad-txns-inputs-spent") || e?.response?.data.error?.message?.includes("already in block chain")) {
console.log('tx already sent, skipping')
continue;
}
console.log('saving pending txs to pending-txs.json')
console.log('to reattempt broadcast, re-run the command')
fs.writeFileSync('pending-txs.json', JSON.stringify(txs.slice(i).map(tx => tx.toString())))
process.exit(1)
}
}
try {
fs.unlinkSync('pending-txs.json')
} catch (err) {
// ignore
}
if (txs.length > 1) {
console.log('inscription txid:', txs[1].hash)
}
}
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: output.script.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) throw 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) {
const body = {
jsonrpc: "1.0",
id: "extract",
method: "getrawtransaction",
params: [txid, true] // [txid, verbose=true]
}
const options = {
auth: {
username: process.env.NODE_RPC_USER,
password: process.env.NODE_RPC_PASS
}
}
let response = await axios.post(process.env.NODE_RPC_URL, body, options)
let transaction = response.data.result
let inputs = transaction.vin
let scriptHex = inputs[0].scriptSig.hex
let script = Script.fromHex(scriptHex)
let chunks = script.chunks
let prefix = chunks.shift().buf.toString('utf-8')
if (prefix != 'ord') {
throw new Error('not a doginal')
}
let pieces = chunkToNumber(chunks.shift())
let contentType = chunks.shift().buf.toString('utf-8')
let data = Buffer.alloc(0)
let remaining = pieces
while (remaining && chunks.length) {
let n = chunkToNumber(chunks.shift())
if (n !== remaining - 1) {
txid = transaction.vout[0].spent.hash
response = await axios.post(process.env.NODE_RPC_URL, body, options)
transaction = response.data.result
inputs = transaction.vin
scriptHex = inputs[0].scriptSig.hex
script = Script.fromHex(scriptHex)
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)
})