forked from LTEX-DEV/cb-wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
360 lines (289 loc) · 10.1 KB
/
index.js
File metadata and controls
360 lines (289 loc) · 10.1 KB
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
"use strict";
var API = require('cb-altcoins')
var bitcoin = require('bitcoinjs-lib')
var TxGraph = require('bitcoin-tx-graph')
var assert = require('assert')
var discoverAddresses = require('./network').discoverAddresses
var fetchTransactions = require('./network').fetchTransactions
var fetchUnspents = require('./network').fetchUnspents
var validate = require('./validator')
function Wallet(externalAccount, internalAccount, networkName, done, unspentsDone, balanceDone) {
if(arguments.length === 0) return this;
if(unspentsDone == null) {
unspentsDone = function() {
//no-op
}
}
if(balanceDone == null) {
balanceDone = function() {
//no-op
}
}
try {
if(typeof externalAccount === 'string') {
this.externalAccount = bitcoin.HDNode.fromBase58(externalAccount)
} else {
this.externalAccount = externalAccount
}
if(typeof internalAccount === 'string') {
this.internalAccount = bitcoin.HDNode.fromBase58(internalAccount)
} else {
this.internalAccount = internalAccount
}
assert(this.externalAccount != null, 'externalAccount cannot be null')
assert(this.internalAccount != null, 'internalAccount cannot be null')
} catch(err) {
return doneError(err)
}
this.networkName = networkName
this.api = new API(networkName, process.env.PROXY_URL)
this.txGraph = new TxGraph()
var that = this
discoverAddresses(this.api, this.externalAccount, this.internalAccount,
function(err, addresses, changeAddresses, balance, unspentAddresses) {
if(err) {
return doneError(err)
}
that.addresses = addresses
that.changeAddresses = changeAddresses
balanceDone(null, balance)
fetchUnspents(that.api, unspentAddresses, unspentsDone)
var addresses = addresses.concat(changeAddresses)
fetchTransactions(that.api, addresses, function(err, txs, metadata) {
if(err) return done(err);
txs.forEach(function(tx) { that.txGraph.addTx(tx) })
var feesAndValues = that.txGraph.calculateFeesAndValues(addresses, bitcoin.networks[that.networkName])
that.txMetadata = mergeMetadata(feesAndValues, metadata)
done(null, that)
})
})
function doneError(err) {
done(err)
unspentsDone(err)
balanceDone(err)
}
}
Wallet.prototype.getBalance = function(minConf) {
minConf = minConf || 0
var network = bitcoin.networks[this.networkName]
var myAddresses = this.addresses.concat(this.changeAddresses)
var utxos = getCandidateOutputs(this.txGraph.getAllNodes(), this.txMetadata, network, myAddresses, minConf)
return utxos.reduce(function(balance, unspent) {
return balance + unspent.value
}, 0)
}
Wallet.prototype.getNextChangeAddress = function() {
return this.internalAccount.derive(this.changeAddresses.length).getAddress().toString()
}
Wallet.prototype.getNextAddress = function() {
return this.externalAccount.derive(this.addresses.length).getAddress().toString()
}
Wallet.prototype.getPrivateKeyForAddress = function(address) {
var index
if((index = this.addresses.indexOf(address)) > -1) {
return this.externalAccount.derive(index).privKey
} else if((index = this.changeAddresses.indexOf(address)) > -1) {
return this.internalAccount.derive(index).privKey
} else {
throw new Error('Unknown address. Make sure the address is from the keychain and has been generated.')
}
}
// param: `txObj` or
// `[{tx: txObj1, confirmations: n1, timestamp: t1}, {tx: txObj2, confirmations: n2, timestamp: t2}]`
Wallet.prototype.processTx = function(txs) {
if(!Array.isArray(txs)) {
txs = [{tx: txs}]
}
var foundUsed = true
while(foundUsed) {
foundUsed = addToAddresses.bind(this)(this.getNextAddress(), this.getNextChangeAddress())
}
txs.forEach(function(obj) {
var tx = obj.tx
this.txGraph.addTx(tx)
var id = tx.getId()
this.txMetadata[id] = this.txMetadata[id] || { confirmations: null }
if(obj.confirmations != null) {
this.txMetadata[id].confirmations = obj.confirmations
}
if(obj.timestamp != null) {
this.txMetadata[id].timestamp = obj.timestamp
}
}, this)
//FIXME: make me more effecient
var myAddresses = this.addresses.concat(this.changeAddresses)
var feesAndValues = this.txGraph.calculateFeesAndValues(myAddresses, bitcoin.networks[this.networkName])
this.txMetadata = mergeMetadata(feesAndValues, this.txMetadata)
function addToAddresses(nextAddress, nextChangeAddress) {
for(var i=0; i<txs.length; i++) {
var tx = txs[i].tx
var found = tx.outs.some(function(out){
var address = bitcoin.Address.fromOutputScript(out.script, bitcoin.networks[this.networkName]).toString()
if(nextChangeAddress === address) {
this.changeAddresses.push(address)
return true
} else if(nextAddress === address) {
this.addresses.push(address)
return true
}
}, this)
if(found) return true
}
}
}
Wallet.prototype.createTx = function(to, value, fee, minConf, unspents) {
var addresses = []
var builder = this._createUnsignedTx(to, value, fee, minConf, unspents, addresses)
addresses.forEach(function(address, i) {
builder.sign(i, this.getPrivateKeyForAddress(address))
}, this)
return builder.build()
}
Wallet.prototype._createUnsignedTx = function(to, value, fee, minConf, unspents, addresses) {
var network = bitcoin.networks[this.networkName]
validate.preCreateTx(to, value, network)
if(minConf == null) {
minConf = 1
}
var utxos = null
if(unspents != null) {
validate.utxos(unspents)
utxos = unspents.filter(function(unspent) {
return unspent.confirmations >= minConf
})
} else {
var myAddresses = this.addresses.concat(this.changeAddresses)
utxos = getCandidateOutputs(this.txGraph.getAllNodes(), this.txMetadata, network, myAddresses, minConf)
}
utxos = utxos.sort(function(o1, o2){
return o2.value - o1.value
})
var accum = 0
var subTotal = value
var builder = new bitcoin.TransactionBuilder()
builder.addOutput(to, value)
var that = this
utxos.some(function(unspent) {
builder.addInput(unspent.txId, unspent.vout)
addresses.push(unspent.address)
var estimatedFee
if(fee == undefined) {
estimatedFee = estimateFeePadChangeOutput(builder.buildIncomplete(), network)
} else {
estimatedFee = fee
}
accum += unspent.value
subTotal = value + estimatedFee
if (accum >= subTotal) {
var change = accum - subTotal
if (change > network.dustThreshold) {
builder.addOutput(that.getNextChangeAddress(), change)
}
return true
}
})
validate.postCreateTx(subTotal, accum, this.getBalance(0))
return builder
}
Wallet.prototype.sendTx = function(tx, done) {
var that = this
this.api.transactions.propagate(tx.toHex(), function(err){
if(err) return done(err);
that.processTx(tx)
done()
})
}
function getCandidateOutputs(allNodes, metadata, network, myAddresses, minConf) {
var confirmedNodes = allNodes.filter(function(n) {
var meta = metadata[n.id]
return meta && meta.confirmations >= minConf
})
return confirmedNodes.reduce(function(unspentOutputs, node) {
node.tx.outs.forEach(function(out, i) {
var address = bitcoin.Address.fromOutputScript(out.script, network).toString()
if(myAddresses.indexOf(address) >= 0 && node.nextNodes[i] == null) {
unspentOutputs.push({
txId: node.id,
address: address,
value: out.value,
vout: i
})
}
})
return unspentOutputs
}, [])
}
function estimateFeePadChangeOutput(tx, network) {
var tmpTx = tx.clone()
var tmpAddress = bitcoin.Address.fromOutputScript(tx.outs[0].script, network)
var dummyAmount = network.dustSoftThreshold == null ? 0 : (network.dustSoftThreshold - 1)
tmpTx.addOutput(tmpAddress, dummyAmount)
return network.estimateFee(tmpTx)
}
Wallet.prototype.getTransactionHistory = function() {
var txGraph = this.txGraph
var metadata = this.txMetadata
var nodes = txGraph.getAllNodes().filter(function(n) {
return n.tx != null && metadata[n.id].value != null
}).sort(function(a, b) {
var confDiff = metadata[a.id].confirmations - metadata[b.id].confirmations
if(confDiff !== 0) {
return confDiff
}
return txGraph.compareNodes(a, b)
})
return nodes.map(function(n) {
return n.tx
})
}
Wallet.prototype.serialize = function() {
var txs = this.txGraph.getAllNodes().reduce(function(memo, node) {
var tx = node.tx
if(tx == null) return memo;
memo.push(tx.toHex())
return memo
}, [])
return JSON.stringify({
externalAccount: this.externalAccount.toBase58(),
internalAccount: this.internalAccount.toBase58(),
addressIndex: this.addresses.length,
changeAddressIndex: this.changeAddresses.length,
networkName: this.networkName,
txs: txs,
txMetadata: this.txMetadata
})
}
Wallet.deserialize = function(json) {
var wallet = new Wallet()
var deserialized = JSON.parse(json)
wallet.externalAccount = bitcoin.HDNode.fromBase58(deserialized.externalAccount)
wallet.internalAccount = bitcoin.HDNode.fromBase58(deserialized.internalAccount)
wallet.addresses = deriveAddresses(wallet.externalAccount, deserialized.addressIndex)
wallet.changeAddresses = deriveAddresses(wallet.internalAccount, deserialized.changeAddressIndex)
wallet.networkName = deserialized.networkName
wallet.api = new API(deserialized.networkName)
wallet.txMetadata = deserialized.txMetadata
wallet.txGraph = new TxGraph()
deserialized.txs.forEach(function(hex) {
wallet.txGraph.addTx(bitcoin.Transaction.fromHex(hex))
})
return wallet
}
function mergeMetadata(feesAndValues, metadata) {
for(var id in metadata) {
var fee = feesAndValues[id].fee
if(fee != null) metadata[id].fee = fee
var value = feesAndValues[id].value
if(value < 0) value += fee
if(value != null) metadata[id].value = value
}
return metadata
}
function deriveAddresses(account, untilId) {
var addresses = []
for(var i=0; i<untilId; i++) {
addresses.push(account.derive(i).getAddress().toString())
}
return addresses
}
module.exports = Wallet