Browse Source

Merge pull request #258 from dcousens/wallclean

Wallet clean
hk-custom-address
Wei Lu 11 years ago
parent
commit
2386253ea0
  1. 404
      src/wallet.js
  2. 241
      test/wallet.js

404
src/wallet.js

@ -5,32 +5,35 @@ var networks = require('./networks')
var Address = require('./address') var Address = require('./address')
var HDNode = require('./hdnode') var HDNode = require('./hdnode')
var Transaction = require('./transaction') var Transaction = require('./transaction')
var Script = require('./script')
function Wallet(seed, network) { function Wallet(seed, network, unspents) {
seed = seed || crypto.randomBytes(32)
network = network || networks.bitcoin network = network || networks.bitcoin
// Stored in a closure to make accidental serialization less likely // Stored in a closure to make accidental serialization less likely
var masterkey = null var masterKey = HDNode.fromSeedBuffer(seed, network)
var me = this
var accountZero = null // HD first-level child derivation method should be hardened
var internalAccount = null // See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254
var externalAccount = null var accountZero = masterKey.deriveHardened(0)
var externalAccount = accountZero.derive(0)
var internalAccount = accountZero.derive(1)
// Addresses
this.addresses = [] this.addresses = []
this.changeAddresses = [] this.changeAddresses = []
this.network = network
this.outputs = unspents ? processUnspentOutputs(unspents) : {}
// Transaction output data // FIXME: remove in 2.x.y
this.outputs = {} var me = this
// Make a new master key
this.newMasterKey = function(seed) { this.newMasterKey = function(seed) {
console.warn('newMasterKey is deprecated, please make a new Wallet instance instead')
seed = seed || crypto.randomBytes(32) seed = seed || crypto.randomBytes(32)
masterkey = HDNode.fromSeedBuffer(seed, network) masterKey = HDNode.fromSeedBuffer(seed, network)
// HD first-level child derivation method should be hardened accountZero = masterKey.deriveHardened(0)
// See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254
accountZero = masterkey.deriveHardened(0)
externalAccount = accountZero.derive(0) externalAccount = accountZero.derive(0)
internalAccount = accountZero.derive(1) internalAccount = accountZero.derive(1)
@ -40,196 +43,206 @@ function Wallet(seed, network) {
me.outputs = {} me.outputs = {}
} }
this.newMasterKey(seed) this.getMasterKey = function() { return masterKey }
this.getAccountZero = function() { return accountZero }
this.getExternalAccount = function() { return externalAccount }
this.getInternalAccount = function() { return internalAccount }
}
this.generateAddress = function() { Wallet.prototype.createTx = function(to, value, fixedFee, changeAddress) {
var key = externalAccount.derive(this.addresses.length) assert(value > this.network.dustThreshold, value + ' must be above dust threshold (' + this.network.dustThreshold + ' Satoshis)')
this.addresses.push(key.getAddress().toString())
return this.addresses[this.addresses.length - 1]
}
this.generateChangeAddress = function() { var utxos = getCandidateOutputs(this.outputs, value)
var key = internalAccount.derive(this.changeAddresses.length) var accum = 0
this.changeAddresses.push(key.getAddress().toString()) var subTotal = value
return this.changeAddresses[this.changeAddresses.length - 1] var addresses = []
}
this.getBalance = function() { var tx = new Transaction()
return this.getUnspentOutputs().reduce(function(memo, output){ tx.addOutput(to, value)
return memo + output.value
}, 0)
}
this.getUnspentOutputs = function() { for (var i = 0; i < utxos.length; ++i) {
var utxo = [] var utxo = utxos[i]
addresses.push(utxo.address)
for(var key in this.outputs){ var outpoint = utxo.from.split(':')
var output = this.outputs[key] tx.addInput(outpoint[0], parseInt(outpoint[1]))
if(!output.to) utxo.push(outputToUnspentOutput(output))
var fee = fixedFee == undefined ? estimatePaddedFee(tx, this.network) : fixedFee
accum += utxo.value
subTotal = value + fee
if (accum >= subTotal) {
var change = accum - subTotal
if (change > this.network.dustThreshold) {
tx.addOutput(changeAddress || this.getChangeAddress(), change)
} }
return utxo break
}
} }
this.setUnspentOutputs = function(utxo) { assert(accum >= subTotal, 'Not enough funds (incl. fee): ' + accum + ' < ' + subTotal)
var outputs = {}
utxo.forEach(function(uo){ this.signWith(tx, addresses)
validateUnspentOutput(uo) return tx
var o = unspentOutputToOutput(uo) }
outputs[o.from] = o
})
this.outputs = outputs Wallet.prototype.processPendingTx = function(tx){
} processTx.bind(this)(tx, true)
}
function outputToUnspentOutput(output){ Wallet.prototype.processConfirmedTx = function(tx){
var hashAndIndex = output.from.split(":") processTx.bind(this)(tx, false)
}
return { Wallet.prototype.generateAddress = function() {
hash: hashAndIndex[0], var k = this.addresses.length
outputIndex: parseInt(hashAndIndex[1]), var address = this.getExternalAccount().derive(k).getAddress()
address: output.address,
value: output.value,
pending: output.pending
}
}
function unspentOutputToOutput(o) { this.addresses.push(address.toString())
var hash = o.hash
var key = hash + ":" + o.outputIndex
return {
from: key,
address: o.address,
value: o.value,
pending: o.pending
}
}
function validateUnspentOutput(uo) { return this.getReceiveAddress()
var missingField }
if (isNullOrUndefined(uo.hash)) { Wallet.prototype.generateChangeAddress = function() {
missingField = "hash" var k = this.changeAddresses.length
} var address = this.getInternalAccount().derive(k).getAddress()
var requiredKeys = ['outputIndex', 'address', 'value'] this.changeAddresses.push(address.toString())
requiredKeys.forEach(function (key) {
if (isNullOrUndefined(uo[key])){
missingField = key
}
})
if (missingField) { return this.getChangeAddress()
var message = [ }
'Invalid unspent output: key', missingField, 'is missing.',
'A valid unspent output must contain'
]
message.push(requiredKeys.join(', '))
message.push("and hash")
throw new Error(message.join(' '))
}
}
function isNullOrUndefined(value) { Wallet.prototype.getBalance = function() {
return value == undefined return this.getUnspentOutputs().reduce(function(accum, output) {
} return accum + output.value
}, 0)
}
this.processPendingTx = function(tx){ Wallet.prototype.getChangeAddress = function() {
processTx(tx, true) if (this.changeAddresses.length === 0) {
this.generateChangeAddress()
} }
this.processConfirmedTx = function(tx){ return this.changeAddresses[this.changeAddresses.length - 1]
processTx(tx, false) }
}
function processTx(tx, isPending) { Wallet.prototype.getInternalPrivateKey = function(index) {
var txid = tx.getId() return this.getInternalAccount().derive(index).privKey
}
tx.outs.forEach(function(txOut, i) { Wallet.prototype.getPrivateKey = function(index) {
var address return this.getExternalAccount().derive(index).privKey
}
try { Wallet.prototype.getPrivateKeyForAddress = function(address) {
address = Address.fromOutputScript(txOut.script, network).toString() if (includeAddress(this.addresses, address)) {
} catch(e) { var index = this.addresses.indexOf(address)
if (!(e.message.match(/has no matching Address/))) throw e
return this.getPrivateKey(index)
} }
if (isMyAddress(address)) { if (includeAddress(this.changeAddresses, address)) {
var output = txid + ':' + i var index = this.changeAddresses.indexOf(address)
me.outputs[output] = { return this.getInternalPrivateKey(index)
from: output,
value: txOut.value,
address: address,
pending: isPending
}
} }
})
tx.ins.forEach(function(txIn, i) { assert(false, 'Unknown address. Make sure the address is from the keychain and has been generated')
// copy and convert to big-endian hex }
var txinId = new Buffer(txIn.hash)
Array.prototype.reverse.call(txinId)
txinId = txinId.toString('hex')
var output = txinId + ':' + txIn.index Wallet.prototype.getReceiveAddress = function() {
if (this.addresses.length === 0) {
this.generateAddress()
}
return this.addresses[this.addresses.length - 1]
}
if (!(output in me.outputs)) return Wallet.prototype.getUnspentOutputs = function() {
var utxo = []
if (isPending) { for(var key in this.outputs){
me.outputs[output].to = txid + ':' + i var output = this.outputs[key]
me.outputs[output].pending = true if(!output.to) utxo.push(outputToUnspentOutput(output))
} else {
delete me.outputs[output]
}
})
} }
this.createTx = function(to, value, fixedFee, changeAddress) { return utxo
assert(value > network.dustThreshold, value + ' must be above dust threshold (' + network.dustThreshold + ' Satoshis)') }
var utxos = getCandidateOutputs(value) Wallet.prototype.setUnspentOutputs = function(utxo) {
var accum = 0 console.warn('setUnspentOutputs is deprecated, please use the constructor option instead')
var subTotal = value
var addresses = []
var tx = new Transaction() this.outputs = processUnspentOutputs(utxo)
tx.addOutput(to, value) }
for (var i = 0; i < utxos.length; ++i) { Wallet.prototype.signWith = function(tx, addresses) {
var utxo = utxos[i] assert.equal(tx.ins.length, addresses.length, 'Number of addresses must match number of transaction inputs')
addresses.push(utxo.address)
var outpoint = utxo.from.split(':') addresses.forEach(function(address, i) {
tx.addInput(outpoint[0], parseInt(outpoint[1])) var key = this.getPrivateKeyForAddress(address)
var fee = fixedFee == undefined ? estimateFeePadChangeOutput(tx) : fixedFee tx.sign(i, key)
}, this)
accum += utxo.value return tx
subTotal = value + fee }
if (accum >= subTotal) {
var change = accum - subTotal
if (change > network.dustThreshold) { function outputToUnspentOutput(output){
tx.addOutput(changeAddress || getChangeAddress(), change) var hashAndIndex = output.from.split(":")
}
break return {
} hash: hashAndIndex[0],
index: parseInt(hashAndIndex[1]),
address: output.address,
value: output.value,
pending: output.pending
} }
}
assert(accum >= subTotal, 'Not enough funds (incl. fee): ' + accum + ' < ' + subTotal) function estimatePaddedFee(tx, network) {
var tmpTx = tx.clone()
tmpTx.addOutput(Script.EMPTY, network.dustSoftThreshold || 0)
this.signWith(tx, addresses) return network.estimateFee(tmpTx)
return tx }
function processUnspentOutputs(utxos) {
var outputs = {}
utxos.forEach(function(utxo){
var hash = new Buffer(utxo.hash, 'hex')
var index = utxo.index
var address = utxo.address
var value = utxo.value
// FIXME: remove alternative in 2.x.y
if (index === undefined) index = utxo.outputIndex
assert.equal(hash.length, 32, 'Expected hash length of 32, got ' + hash.length)
assert.equal(typeof index, 'number', 'Expected number index, got ' + index)
assert.doesNotThrow(function() { Address.fromBase58Check(address) }, 'Expected Base58 Address, got ' + address)
assert.equal(typeof value, 'number', 'Expected number value, got ' + value)
var key = utxo.hash + ':' + utxo.index
outputs[key] = {
from: key,
address: address,
value: value,
pending: utxo.pending
} }
})
return outputs
}
function getCandidateOutputs() { function getCandidateOutputs(outputs/*, value*/) {
var unspent = [] var unspent = []
for (var key in me.outputs) { for (var key in outputs) {
var output = me.outputs[key] var output = outputs[key]
if (!output.pending) unspent.push(output) if (!output.pending) unspent.push(output)
} }
@ -238,67 +251,54 @@ function Wallet(seed, network) {
}) })
return sortByValueDesc return sortByValueDesc
} }
function estimateFeePadChangeOutput(tx) { function processTx(tx, isPending) {
var tmpTx = tx.clone() var txid = tx.getId()
tmpTx.addOutput(getChangeAddress(), network.dustSoftThreshold || 0)
return network.estimateFee(tmpTx) tx.outs.forEach(function(txOut, i) {
} var address
function getChangeAddress() { try {
if(me.changeAddresses.length === 0) me.generateChangeAddress(); address = Address.fromOutputScript(txOut.script, this.network).toString()
return me.changeAddresses[me.changeAddresses.length - 1] } catch(e) {
if (!(e.message.match(/has no matching Address/))) throw e
} }
this.signWith = function(tx, addresses) { var myAddresses = this.addresses.concat(this.changeAddresses)
assert.equal(tx.ins.length, addresses.length, 'Number of addresses must match number of transaction inputs') if (includeAddress(myAddresses, address)) {
var output = txid + ':' + i
addresses.forEach(function(address, i) {
var key = me.getPrivateKeyForAddress(address)
tx.sign(i, key)
})
return tx this.outputs[output] = {
from: output,
value: txOut.value,
address: address,
pending: isPending
} }
this.getMasterKey = function() { return masterkey }
this.getAccountZero = function() { return accountZero }
this.getInternalAccount = function() { return internalAccount }
this.getExternalAccount = function() { return externalAccount }
this.getPrivateKey = function(index) {
return externalAccount.derive(index).privKey
} }
}, this)
this.getInternalPrivateKey = function(index) { tx.ins.forEach(function(txIn, i) {
return internalAccount.derive(index).privKey // copy and convert to big-endian hex
} var txinId = new Buffer(txIn.hash)
Array.prototype.reverse.call(txinId)
txinId = txinId.toString('hex')
this.getPrivateKeyForAddress = function(address) { var output = txinId + ':' + txIn.index
var index
if((index = this.addresses.indexOf(address)) > -1) {
return this.getPrivateKey(index)
} else if((index = this.changeAddresses.indexOf(address)) > -1) {
return this.getInternalPrivateKey(index)
} else {
throw new Error('Unknown address. Make sure the address is from the keychain and has been generated.')
}
}
function isReceiveAddress(address){ if (!(output in this.outputs)) return
return me.addresses.indexOf(address) > -1
}
function isChangeAddress(address){ if (isPending) {
return me.changeAddresses.indexOf(address) > -1 this.outputs[output].to = txid + ':' + i
this.outputs[output].pending = true
} else {
delete this.outputs[output]
} }
}, this)
}
function isMyAddress(address) { function includeAddress(addresses, address) {
return isReceiveAddress(address) || isChangeAddress(address) return addresses.indexOf(address) > -1
}
} }
module.exports = Wallet module.exports = Wallet

241
test/wallet.js

@ -26,13 +26,17 @@ function fakeTxId(i) {
} }
describe('Wallet', function() { describe('Wallet', function() {
var seed, wallet var seed
beforeEach(function(){ beforeEach(function(){
seed = crypto.sha256("don't use a string seed like this in real life") seed = crypto.sha256("don't use a string seed like this in real life")
wallet = new Wallet(seed)
}) })
describe('constructor', function() { describe('constructor', function() {
var wallet
beforeEach(function(){
wallet = new Wallet(seed)
})
it('defaults to Bitcoin network', function() { it('defaults to Bitcoin network', function() {
assert.equal(wallet.getMasterKey().network, networks.bitcoin) assert.equal(wallet.getMasterKey().network, networks.bitcoin)
}) })
@ -116,6 +120,11 @@ describe('Wallet', function() {
}) })
describe('generateChangeAddress', function(){ describe('generateChangeAddress', function(){
var wallet
beforeEach(function(){
wallet = new Wallet(seed)
})
it('generates change addresses', function(){ it('generates change addresses', function(){
var wallet = new Wallet(seed, networks.testnet) var wallet = new Wallet(seed, networks.testnet)
var expectedAddresses = ["mnXiDR4MKsFxcKJEZjx4353oXvo55iuptn"] var expectedAddresses = ["mnXiDR4MKsFxcKJEZjx4353oXvo55iuptn"]
@ -126,6 +135,11 @@ describe('Wallet', function() {
}) })
describe('getPrivateKey', function(){ describe('getPrivateKey', function(){
var wallet
beforeEach(function(){
wallet = new Wallet(seed)
})
it('returns the private key at the given index of external account', function(){ it('returns the private key at the given index of external account', function(){
var wallet = new Wallet(seed, networks.testnet) var wallet = new Wallet(seed, networks.testnet)
@ -135,6 +149,11 @@ describe('Wallet', function() {
}) })
describe('getInternalPrivateKey', function(){ describe('getInternalPrivateKey', function(){
var wallet
beforeEach(function(){
wallet = new Wallet(seed)
})
it('returns the private key at the given index of internal account', function(){ it('returns the private key at the given index of internal account', function(){
var wallet = new Wallet(seed, networks.testnet) var wallet = new Wallet(seed, networks.testnet)
@ -144,6 +163,11 @@ describe('Wallet', function() {
}) })
describe('getPrivateKeyForAddress', function(){ describe('getPrivateKeyForAddress', function(){
var wallet
beforeEach(function(){
wallet = new Wallet(seed)
})
it('returns the private key for the given address', function(){ it('returns the private key for the given address', function(){
var wallet = new Wallet(seed, networks.testnet) var wallet = new Wallet(seed, networks.testnet)
wallet.generateChangeAddress() wallet.generateChangeAddress()
@ -162,58 +186,63 @@ describe('Wallet', function() {
it('raises an error when address is not found', function(){ it('raises an error when address is not found', function(){
var wallet = new Wallet(seed, networks.testnet) var wallet = new Wallet(seed, networks.testnet)
assert.throws(function() { assert.throws(function() {
wallet.getPrivateKeyForAddress("n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X") wallet.getPrivateKeyForAddress("n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X")
}, /Unknown address. Make sure the address is from the keychain and has been generated./) }, /Unknown address. Make sure the address is from the keychain and has been generated/)
}) })
}) })
describe('Unspent Outputs', function(){ describe('Unspent Outputs', function(){
var expectedUtxo, expectedOutputKey var utxo, expectedOutputKey
var wallet
beforeEach(function(){ beforeEach(function(){
expectedUtxo = { utxo = {
"hash":"6a4062273ac4f9ea4ffca52d9fd102b08f6c32faa0a4d1318e3a7b2e437bb9c7",
"outputIndex": 0,
"address" : "1AZpKpcfCzKDUeTFBQUL4MokQai3m3HMXv", "address" : "1AZpKpcfCzKDUeTFBQUL4MokQai3m3HMXv",
"value": 20000, "hash": fakeTxId(6),
"pending": true "index": 0,
"pending": true,
"value": 20000
} }
expectedOutputKey = expectedUtxo.hash + ":" + expectedUtxo.outputIndex
expectedOutputKey = utxo.hash + ":" + utxo.index
}) })
function addUtxoToOutput(utxo){ describe('on construction', function(){
var key = utxo.hash + ":" + utxo.outputIndex beforeEach(function(){
wallet.outputs[key] = { wallet = new Wallet(seed, networks.bitcoin, [utxo])
from: key, })
address: utxo.address,
value: utxo.value,
pending: utxo.pending
}
}
describe('getBalance', function(){ it('matches the expected behaviour', function(){
var utxo1 var output = wallet.outputs[expectedOutputKey]
assert(output)
assert.equal(output.value, utxo.value)
assert.equal(output.address, utxo.address)
})
})
describe('getBalance', function(){
beforeEach(function(){ beforeEach(function(){
utxo1 = cloneObject(expectedUtxo) var utxo1 = cloneObject(utxo)
utxo1.hash = utxo1.hash.replace('7', 'l') utxo1.hash = fakeTxId(5)
wallet = new Wallet(seed, networks.bitcoin, [utxo, utxo1])
}) })
it('sums over utxo values', function(){ it('sums over utxo values', function(){
addUtxoToOutput(expectedUtxo)
addUtxoToOutput(utxo1)
assert.equal(wallet.getBalance(), 40000) assert.equal(wallet.getBalance(), 40000)
}) })
}) })
describe('getUnspentOutputs', function(){ describe('getUnspentOutputs', function(){
beforeEach(function(){ beforeEach(function(){
addUtxoToOutput(expectedUtxo) wallet = new Wallet(seed, networks.bitcoin, [utxo])
}) })
it('parses wallet outputs to the expect format', function(){ it('parses wallet outputs to the expect format', function(){
assert.deepEqual(wallet.getUnspentOutputs(), [expectedUtxo]) assert.deepEqual(wallet.getUnspentOutputs(), [utxo])
}) })
it("ignores pending spending outputs (outputs with 'to' property)", function(){ it("ignores pending spending outputs (outputs with 'to' property)", function(){
@ -223,40 +252,54 @@ describe('Wallet', function() {
assert.deepEqual(wallet.getUnspentOutputs(), []) assert.deepEqual(wallet.getUnspentOutputs(), [])
}) })
}) })
})
// FIXME: remove in 2.x.y
describe('setUnspentOutputs', function(){ describe('setUnspentOutputs', function(){
var utxo var utxo
var expectedOutputKey
beforeEach(function(){ beforeEach(function(){
utxo = cloneObject([expectedUtxo]) utxo = {
hash: fakeTxId(0),
index: 0,
address: '115qa7iPZqn6as57hxLL8E9VUnhmGQxKWi',
value: 500000
}
expectedOutputKey = utxo.hash + ":" + utxo.index
wallet = new Wallet(seed, networks.bitcoin)
}) })
it('matches the expected behaviour', function(){ it('matches the expected behaviour', function(){
wallet.setUnspentOutputs(utxo) wallet.setUnspentOutputs([utxo])
verifyOutputs()
var output = wallet.outputs[expectedOutputKey]
assert(output)
assert.equal(output.value, utxo.value)
assert.equal(output.address, utxo.address)
}) })
describe('required fields', function(){ describe('required fields', function(){
['outputIndex', 'address', 'hash', 'value'].forEach(function(field){ ['index', 'address', 'hash', 'value'].forEach(function(field){
it("throws an error when " + field + " is missing", function(){ it("throws an error when " + field + " is missing", function(){
delete utxo[0][field] delete utxo[field]
assert.throws(function() { assert.throws(function() {
wallet.setUnspentOutputs(utxo) wallet.setUnspentOutputs([utxo])
}, new RegExp('Invalid unspent output: key ' + field + ' is missing'))
}) })
}) })
}) })
function verifyOutputs() {
var output = wallet.outputs[expectedOutputKey]
assert(output)
assert.equal(output.value, utxo[0].value)
assert.equal(output.address, utxo[0].address)
}
}) })
}) })
describe('Process transaction', function(){ describe('Process transaction', function(){
var wallet
beforeEach(function(){
wallet = new Wallet(seed)
})
var addresses var addresses
var tx var tx
@ -389,39 +432,42 @@ describe('Wallet', function() {
}) })
describe('createTx', function(){ describe('createTx', function(){
var to, value var wallet
var address1, address2 var address1, address2
var to, value
beforeEach(function(){ beforeEach(function(){
to = '15mMHKL96tWAUtqF3tbVf99Z8arcmnJrr3' to = 'mt7MyTVVEWnbwpF5hBn6fgnJcv95Syk2ue'
value = 500000 value = 500000
// generate 2 addresses address1 = "n1GyUANZand9Kw6hGSV9837cCC9FFUQzQa"
address1 = wallet.generateAddress() address2 = "n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X"
address2 = wallet.generateAddress()
// set up 3 utxo // set up 3 utxos
utxo = [ var utxos = [
{ {
"hash": fakeTxId(1), "hash": fakeTxId(1),
"outputIndex": 0, "index": 0,
"address" : address1, "address": address1,
"value": 400000 // not enough for value "value": 400000 // not enough for value
}, },
{ {
"hash": fakeTxId(2), "hash": fakeTxId(2),
"outputIndex": 1, "index": 1,
"address" : address1, "address": address1,
"value": 500000 // enough for only value "value": 500000 // enough for only value
}, },
{ {
"hash": fakeTxId(3), "hash": fakeTxId(3),
"outputIndex": 0, "index": 0,
"address" : address2, "address" : address2,
"value": 510000 // enough for value and fee "value": 510000 // enough for value and fee
} }
] ]
wallet.setUnspentOutputs(utxo)
wallet = new Wallet(seed, networks.testnet, utxos)
wallet.generateAddress()
wallet.generateAddress()
}) })
describe('transaction fee', function(){ describe('transaction fee', function(){
@ -441,17 +487,18 @@ describe('Wallet', function() {
}) })
it('does not overestimate fees when network has dustSoftThreshold', function(){ it('does not overestimate fees when network has dustSoftThreshold', function(){
var wallet = new Wallet(seed, networks.litecoin) var utxo = {
var address = wallet.generateAddress()
wallet.setUnspentOutputs([{
hash: fakeTxId(0), hash: fakeTxId(0),
outputIndex: 0, index: 0,
address: address, address: "LeyySKbQrRRwodKEj1W4a8y3YQupPLw5os",
value: 500000 value: 500000
}]) }
var wallet = new Wallet(seed, networks.litecoin, [utxo])
wallet.generateAddress()
value = 200000 value = 200000
var tx = wallet.createTx(address, value) var tx = wallet.createTx(utxo.address, value)
assert.equal(getFee(wallet, tx), 100000) assert.equal(getFee(wallet, tx), 100000)
}) })
@ -477,66 +524,38 @@ describe('Wallet', function() {
assert.equal(tx.ins[0].index, 0) assert.equal(tx.ins[0].index, 0)
}) })
it('ignores pending outputs', function(){ it('uses confirmed outputs', function(){
utxo.push( var tx2 = new Transaction()
{ tx2.addInput(fakeTxId(4), 0)
"hash": fakeTxId(4), tx2.addOutput(address2, 530000)
"outputIndex": 0,
"address" : address2,
"value": 530000,
"pending": true
}
)
wallet.setUnspentOutputs(utxo)
wallet.processConfirmedTx(tx2)
var tx = wallet.createTx(to, value) var tx = wallet.createTx(to, value)
assert.equal(tx.ins.length, 1) assert.equal(tx.ins.length, 1)
assert.deepEqual(tx.ins[0].hash, fakeTxHash(3)) assert.deepEqual(tx.ins[0].hash, tx2.getHash())
assert.equal(tx.ins[0].index, 0) assert.equal(tx.ins[0].index, 0)
}) })
})
describe('works for testnet', function(){ it('ignores pending outputs', function(){
it('should create transaction', function(){ var tx2 = new Transaction()
var wallet = new Wallet(seed, networks.testnet) tx2.addInput(fakeTxId(4), 0)
var address = wallet.generateAddress() tx2.addOutput(address2, 530000)
wallet.setUnspentOutputs([{
hash: fakeTxId(0),
outputIndex: 0,
address: address,
value: value
}])
var to = 'mt7MyTVVEWnbwpF5hBn6fgnJcv95Syk2ue'
var toValue = value - 10000
var tx = wallet.createTx(to, toValue) wallet.processPendingTx(tx2)
assert.equal(tx.outs.length, 1) var tx = wallet.createTx(to, value)
var outAddress = Address.fromOutputScript(tx.outs[0].script, networks.testnet) assert.equal(tx.ins.length, 1)
assert.equal(outAddress.toString(), to) assert.deepEqual(tx.ins[0].hash, fakeTxHash(3))
assert.equal(tx.outs[0].value, toValue) assert.equal(tx.ins[0].index, 0)
}) })
}) })
describe('changeAddress', function(){ describe('changeAddress', function(){
it('should allow custom changeAddress', function(){ it('should allow custom changeAddress', function(){
var wallet = new Wallet(seed, networks.testnet)
var address = wallet.generateAddress()
wallet.setUnspentOutputs([{
hash: fakeTxId(0),
outputIndex: 0,
address: address,
value: value
}])
assert.equal(wallet.getBalance(), value)
var changeAddress = 'mfrFjnKZUvTcvdAK2fUX5D8v1Epu5H8JCk' var changeAddress = 'mfrFjnKZUvTcvdAK2fUX5D8v1Epu5H8JCk'
var to = 'mt7MyTVVEWnbwpF5hBn6fgnJcv95Syk2ue' var fromValue = 510000
var toValue = value / 2 var toValue = fromValue / 2
var fee = 1e3 var fee = 1e3
var tx = wallet.createTx(to, toValue, fee, changeAddress) var tx = wallet.createTx(to, toValue, fee, changeAddress)
@ -549,7 +568,7 @@ describe('Wallet', function() {
assert.equal(tx.outs[0].value, toValue) assert.equal(tx.outs[0].value, toValue)
assert.equal(outAddress1.toString(), changeAddress) assert.equal(outAddress1.toString(), changeAddress)
assert.equal(tx.outs[1].value, value - (toValue + fee)) assert.equal(tx.outs[1].value, fromValue - (toValue + fee))
}) })
}) })
@ -559,7 +578,7 @@ describe('Wallet', function() {
assert.equal(tx.outs.length, 1) assert.equal(tx.outs.length, 1)
var out = tx.outs[0] var out = tx.outs[0]
var outAddress = Address.fromOutputScript(out.script) var outAddress = Address.fromOutputScript(out.script, networks.testnet)
assert.equal(outAddress.toString(), to) assert.equal(outAddress.toString(), to)
assert.equal(out.value, value) assert.equal(out.value, value)
@ -574,7 +593,7 @@ describe('Wallet', function() {
assert.equal(tx.outs.length, 2) assert.equal(tx.outs.length, 2)
var out = tx.outs[1] var out = tx.outs[1]
var outAddress = Address.fromOutputScript(out.script) var outAddress = Address.fromOutputScript(out.script, networks.testnet)
assert.equal(outAddress.toString(), wallet.changeAddresses[1]) assert.equal(outAddress.toString(), wallet.changeAddresses[1])
assert.equal(out.value, 10000) assert.equal(out.value, 10000)
@ -588,7 +607,7 @@ describe('Wallet', function() {
assert.equal(wallet.changeAddresses.length, 1) assert.equal(wallet.changeAddresses.length, 1)
var out = tx.outs[1] var out = tx.outs[1]
var outAddress = Address.fromOutputScript(out.script) var outAddress = Address.fromOutputScript(out.script, networks.testnet)
assert.equal(outAddress.toString(), wallet.changeAddresses[0]) assert.equal(outAddress.toString(), wallet.changeAddresses[0])
assert.equal(out.value, 10000) assert.equal(out.value, 10000)

Loading…
Cancel
Save