-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
234 lines (180 loc) · 7.03 KB
/
index.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
const Docker = require('dockerode')
const axios = require('axios')
const docker = new Docker()
const bitcoinjs = require('bitcoinjs-lib')
const bip65 = require('bip65')
// Dogecoin JSON RPC token
const token = Buffer.from('hello:world', 'utf8').toString('base64')
// Initialize Dogecoin testnet info
bitcoinjs.networks.dogecoin_regtest = {
messagePrefix: '\x18Dogecoin Signed Message:\n',
bech32: 'tdge',
bip32: {
public: 0x0432a9a8,
private: 0x0432a243
},
pubKeyHash: 0x6f,
scriptHash: 0xc4,
wif: 0xef,
}
function finalScriptsFunc (inputIndex, input, script, isSegwit, isP2SH, isP2WSH) {
return {
finalScriptSig: bitcoinjs.script.fromASM('OP_0 ' + input.partialSig[0].signature.toString('hex') + ' ' + input.partialSig[1].signature.toString('hex') + ' OP_0 ' + bitcoinjs.script.fromASM(multisigScript).toString('hex')),
finalScriptWitness: null,
}
}
function jsonRPC (command, params) {
return axios.post('http://127.0.0.1:18332', {
jsonrpc: '1.0',
id: 'wow',
method: command,
params: params
}, {
headers: {
'Authorization': `Basic ${token}`,
'Content-Type': 'application/json'
},
})
}
async function main () {
let result
const container = await docker.createContainer({
Image: 'xanimo/dogecoin-core:ubuntu',
name: 'dogecoind_regtest',
PortBindings: { ['18444/tcp']: [{ HostIp: '0.0.0.0', HostPort: '18444' }], ['18332/tcp']: [{ HostIp: '0.0.0.0', HostPort: '18332' }] },
NetworkMode: 'host',
Binds: ['/home/lola/Workspace/Dogecoin/doge-payment-channel/data/alert.log:/root/.dogecoin/alert.log'],
})
console.log('container created')
await container.start({})
console.log('container started')
// Wait 5 seconds
// Needed otherwise we try to connect when node is not ready
await new Promise(resolve => setTimeout(resolve, 5000));
// We need to change permissions because container is running root
container.exec({ Cmd: ['chown', '1000:1000', '/root/.dogecoin/', '-R'] }, async function (rep, exec) {
await exec.start({})
})
/*
Setup
*/
console.log('Generate 150 blocks')
result = await jsonRPC('generate', [150])
// Generate Alice key pair from private key
const keyPairA = bitcoinjs.ECPair.fromPrivateKey(Buffer.from('3b187fd3a10960efe5753c9851c174c05bcdb30db22fd9deab981fe1f0ec7b00', 'hex'))
keyPairA.network = bitcoinjs.networks.dogecoin_regtest
// Generate Bob key pair from private key
const keyPairB = bitcoinjs.ECPair.fromPrivateKey(Buffer.from('5cdc1bf38cd77f6a0f130d50e6e37b1d1e3eb59b78f3fde6c1572f44e7f709ed', 'hex'))
keyPairB.network = bitcoinjs.networks.dogecoin_regtest
// Fill Alice wallet with some regtest coins
const Alice = bitcoinjs.payments.p2pkh({ pubkey: keyPairA.publicKey, network: bitcoinjs.networks.dogecoin_regtest})
console.log(`Alice address : ${Alice.address}`)
// Send some funds to Alice
console.log('Send 150 Doges to Alice')
result = await jsonRPC('sendtoaddress', [Alice.address, 150])
const txid = result.data.result
console.log('Generate 50 blocks')
result = await jsonRPC('generate', [50])
/*
Start Payment Channel
*/
console.log('Create multisig p2sh address')
const locktime = Buffer.from(bip65.encode({ blocks: 300 }).toString(16), 'hex').reverse().toString('hex')
multisigScript = "OP_IF " +
locktime + "00" + " OP_CHECKLOCKTIMEVERIFY OP_DROP " +
keyPairA.publicKey.toString('hex') + " OP_CHECKSIGVERIFY OP_ELSE OP_2 OP_ENDIF " +
keyPairA.publicKey.toString('hex') + " " + keyPairB.publicKey.toString('hex') + " OP_2 OP_CHECKMULTISIG"
const p2sh = bitcoinjs.payments.p2sh({
redeem: { output: bitcoinjs.script.fromASM(multisigScript) },
network: bitcoinjs.networks.dogecoin_regtest
})
console.log(`P2SH address : ${p2sh.address}`)
// Create initial transaction that funds a multisig
result = await jsonRPC('getrawtransaction', [txid])
let transaction = await jsonRPC('decoderawtransaction', [result.data.result])
let index = 0
transaction.data.result.vout.map(function (output) {
if (output.scriptPubKey.addresses.includes(Alice.address)) {
index = output.n
}
})
const psbt = new bitcoinjs.Psbt()
psbt.addInput({
// if hash is string, txid, if hash is Buffer, is reversed compared to txid
hash: txid,
index: index,
// non-segwit inputs now require passing the whole previous tx as Buffer
nonWitnessUtxo: Buffer.from(result.data.result, 'hex')
})
psbt.addOutputs([{
script: bitcoinjs.script.fromASM('OP_HASH160 ' + p2sh.hash.toString('hex') + ' OP_EQUAL'),
value: 100*100000000
}])
psbt.signInput(0, keyPairA)
psbt.finalizeAllInputs()
const transactionMultisig = psbt.extractTransaction(true).toHex()
console.log('Send some money to alice')
result = await jsonRPC('sendrawtransaction', [transactionMultisig])
const txidMultisig = result.data.result
console.log('Generate 50 blocks')
result = await jsonRPC('generate', [50])
/*
Create ready to be broadcast transaction as payment (but don't broadcast them!)
*/
// Alice: 89, Bob: 10, fee: 1
const psbt2 = new bitcoinjs.Psbt()
// get raw transaction
result = await jsonRPC('getrawtransaction', [txidMultisig])
psbt2.addInput({
// if hash is string, txid, if hash is Buffer, is reversed compared to txid
hash: txidMultisig,
index: 0,
// non-segwit inputs now require passing the whole previous tx as Buffer
nonWitnessUtxo: Buffer.from(result.data.result, 'hex'),
redeemScript: bitcoinjs.script.fromASM(multisigScript)
})
psbt2.addOutputs([{
address: bitcoinjs.payments.p2pkh({ pubkey: keyPairA.publicKey }).address,
value: 89*100000000
}, {
address: bitcoinjs.payments.p2pkh({ pubkey: keyPairB.publicKey }).address,
value: 10*100000000
}])
psbt2.signInput(0, keyPairA)
psbt2.signInput(0, keyPairB)
psbt2.finalizeInput(0, finalScriptsFunc)
console.log(psbt2.extractTransaction(true).toHex())
console.log('FIRST PAYMENT DONE!')
/*
Create second payment (and broadcast it to close payment channel)
*/
// Alice: 79, Bob: 20, fee: 1
const psbt3 = new bitcoinjs.Psbt()
psbt3.addInput({
// if hash is string, txid, if hash is Buffer, is reversed compared to txid
hash: txidMultisig,
index: 0,
// non-segwit inputs now require passing the whole previous tx as Buffer
nonWitnessUtxo: Buffer.from(result.data.result, 'hex'),
redeemScript: bitcoinjs.script.fromASM(multisigScript)
})
psbt3.addOutputs([{
address: bitcoinjs.payments.p2pkh({ pubkey: keyPairA.publicKey }).address,
value: 79*100000000
}, {
address: bitcoinjs.payments.p2pkh({ pubkey: keyPairB.publicKey }).address,
value: 20*100000000
}])
psbt3.signInput(0, keyPairA)
psbt3.signInput(0, keyPairB)
psbt3.finalizeInput(0, finalScriptsFunc)
const finalTransaction = psbt3.extractTransaction(true).toHex()
console.log(finalTransaction)
result = await jsonRPC('sendrawtransaction', [finalTransaction])
console.log(result.data)
console.log('PAYMENT CHANNEL CLOSE!')
await container.stop()
await container.remove()
console.log('container stop')
}
main()