use standardjs formatting

This commit is contained in:
Daniel Cousens 2015-02-23 10:36:57 +11:00
parent 09d8e440de
commit 399803affa
41 changed files with 1252 additions and 1177 deletions

View file

@ -60,6 +60,7 @@
"jshint": "^2.5.11", "jshint": "^2.5.11",
"mocha": "^2.1.0", "mocha": "^2.1.0",
"mocha-lcov-reporter": "0.0.1", "mocha-lcov-reporter": "0.0.1",
"sinon": "^1.12.2" "sinon": "^1.12.2",
"standard": "^2.7.3"
} }
} }

View file

@ -1,13 +1,13 @@
var bs58check = require('bs58check') var bs58check = require('bs58check')
function decode () { function decode () {
console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.'); console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.')
return bs58check.decode.apply(undefined, arguments) return bs58check.decode.apply(undefined, arguments)
} }
function encode () { function encode () {
console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.'); console.warn('bs58check will be removed in 2.0.0. require("bs58check") instead.')
return bs58check.encode.apply(undefined, arguments) return bs58check.encode.apply(undefined, arguments)
} }

View file

@ -3,7 +3,6 @@ var bufferutils = require('./bufferutils')
var crypto = require('./crypto') var crypto = require('./crypto')
var Transaction = require('./transaction') var Transaction = require('./transaction')
var Script = require('./script')
function Block () { function Block () {
this.version = 1 this.version = 1

View file

@ -41,7 +41,6 @@ function readPushDataInt(buffer, offset) {
number = buffer.readUInt32LE(offset + 1) number = buffer.readUInt32LE(offset + 1)
size = 5 size = 5
} }
return { return {
@ -113,7 +112,6 @@ function writePushDataInt(buffer, number, offset) {
} else { } else {
buffer.writeUInt8(opcodes.OP_PUSHDATA4, offset) buffer.writeUInt8(opcodes.OP_PUSHDATA4, offset)
buffer.writeUInt32LE(number, offset + 1) buffer.writeUInt32LE(number, offset + 1)
} }
return size return size

View file

@ -9,7 +9,8 @@ var ecurve = require('ecurve')
var secp256k1 = ecurve.getCurveByName('secp256k1') var secp256k1 = ecurve.getCurveByName('secp256k1')
function ECPubKey (Q, compressed) { function ECPubKey (Q, compressed) {
if (compressed === undefined) compressed = true if (compressed === undefined)
compressed = true
typeForce('Point', Q) typeForce('Point', Q)
typeForce('Boolean', compressed) typeForce('Boolean', compressed)

View file

@ -82,7 +82,8 @@ ECSignature.parseScriptSignature = function(buffer) {
} }
ECSignature.prototype.toCompact = function (i, compressed) { ECSignature.prototype.toCompact = function (i, compressed) {
if (compressed) i += 4 if (compressed)
i += 4
i += 27 i += 27
var buffer = new Buffer(65) var buffer = new Buffer(65)

View file

@ -16,9 +16,7 @@ function findBIP32NetworkByVersion(version) {
for (var name in networks) { for (var name in networks) {
var network = networks[name] var network = networks[name]
if (version === network.bip32.private || if (version === network.bip32.private || version === network.bip32.public) {
version === network.bip32.public) {
return network return network
} }
} }
@ -95,7 +93,7 @@ HDNode.fromBuffer = function(buffer, network, __ignoreDeprecation) {
var version = buffer.readUInt32BE(0) var version = buffer.readUInt32BE(0)
if (network) { if (network) {
assert(version === network.bip32.private || version === network.bip32.public, 'Network doesn\'t match') assert(version === network.bip32.private || version === network.bip32.public, "Network doesn't match")
// auto-detect // auto-detect
} else { } else {
@ -221,7 +219,6 @@ HDNode.prototype.toBuffer = function(isPrivate, __ignoreDeprecation) {
buffer.writeUInt8(0, 45) buffer.writeUInt8(0, 45)
this.privKey.d.toBuffer(32).copy(buffer, 46) this.privKey.d.toBuffer(32).copy(buffer, 46)
} else { } else {
// X9.62 encoding for public keys // X9.62 encoding for public keys
this.pubKey.toBuffer().copy(buffer, 45) this.pubKey.toBuffer().copy(buffer, 45)
} }

View file

@ -134,7 +134,7 @@ function estimateFee(type) {
var byteSize = tx.toBuffer().length var byteSize = tx.toBuffer().length
var fee = baseFee * Math.ceil(byteSize / 1000) var fee = baseFee * Math.ceil(byteSize / 1000)
if (network.dustSoftThreshold == undefined) return fee if (network.dustSoftThreshold === undefined) return fee
tx.outs.forEach(function (e) { tx.outs.forEach(function (e) {
if (e.value < network.dustSoftThreshold) { if (e.value < network.dustSoftThreshold) {

View file

@ -14,11 +14,12 @@ function Script(buffer, chunks) {
Script.fromASM = function (asm) { Script.fromASM = function (asm) {
var strChunks = asm.split(' ') var strChunks = asm.split(' ')
var chunks = strChunks.map(function (strChunk) { var chunks = strChunks.map(function (strChunk) {
// opcode
if (strChunk in opcodes) { if (strChunk in opcodes) {
return opcodes[strChunk] return opcodes[strChunk]
// data chunk
} else { } else {
return new Buffer(strChunk, 'hex') return new Buffer(strChunk, 'hex')
} }
@ -34,6 +35,7 @@ Script.fromBuffer = function(buffer) {
while (i < buffer.length) { while (i < buffer.length) {
var opcode = buffer.readUInt8(i) var opcode = buffer.readUInt8(i)
// data chunk
if ((opcode > opcodes.OP_0) && (opcode <= opcodes.OP_PUSHDATA4)) { if ((opcode > opcodes.OP_0) && (opcode <= opcodes.OP_PUSHDATA4)) {
var d = bufferutils.readPushDataInt(buffer, i) var d = bufferutils.readPushDataInt(buffer, i)
i += d.size i += d.size
@ -43,6 +45,7 @@ Script.fromBuffer = function(buffer) {
chunks.push(data) chunks.push(data)
// opcode
} else { } else {
chunks.push(opcode) chunks.push(opcode)
@ -57,10 +60,12 @@ Script.fromChunks = function(chunks) {
typeForce('Array', chunks) typeForce('Array', chunks)
var bufferSize = chunks.reduce(function (accum, chunk) { var bufferSize = chunks.reduce(function (accum, chunk) {
// data chunk
if (Buffer.isBuffer(chunk)) { if (Buffer.isBuffer(chunk)) {
return accum + bufferutils.pushDataSize(chunk.length) + chunk.length return accum + bufferutils.pushDataSize(chunk.length) + chunk.length
} }
// opcode
return accum + 1 return accum + 1
}, 0.0) }, 0.0)
@ -68,12 +73,14 @@ Script.fromChunks = function(chunks) {
var offset = 0 var offset = 0
chunks.forEach(function (chunk) { chunks.forEach(function (chunk) {
// data chunk
if (Buffer.isBuffer(chunk)) { if (Buffer.isBuffer(chunk)) {
offset += bufferutils.writePushDataInt(buffer, chunk.length, offset) offset += bufferutils.writePushDataInt(buffer, chunk.length, offset)
chunk.copy(buffer, offset) chunk.copy(buffer, offset)
offset += chunk.length offset += chunk.length
// opcode
} else { } else {
buffer.writeUInt8(chunk, offset) buffer.writeUInt8(chunk, offset)
offset += 1 offset += 1
@ -109,9 +116,11 @@ for (var op in opcodes) {
Script.prototype.toASM = function () { Script.prototype.toASM = function () {
return this.chunks.map(function (chunk) { return this.chunks.map(function (chunk) {
// data chunk
if (Buffer.isBuffer(chunk)) { if (Buffer.isBuffer(chunk)) {
return chunk.toString('hex') return chunk.toString('hex')
// opcode
} else { } else {
return reverseOps[chunk] return reverseOps[chunk]
} }

View file

@ -14,7 +14,8 @@ function isCanonicalPubKey(buffer) {
try { try {
ecurve.Point.decodeFrom(curve, buffer) ecurve.Point.decodeFrom(curve, buffer)
} catch (e) { } catch (e) {
if (!(e.message.match(/Invalid sequence (length|tag)/))) throw e if (!(e.message.match(/Invalid sequence (length|tag)/)))
throw e
return false return false
} }
@ -28,7 +29,8 @@ function isCanonicalSignature(buffer) {
try { try {
ECSignature.parseScriptSignature(buffer) ECSignature.parseScriptSignature(buffer)
} catch (e) { } catch (e) {
if (!(e.message.match(/Not a DER sequence|Invalid sequence length|Expected a DER integer|R length is zero|S length is zero|R value excessively padded|S value excessively padded|R value is negative|S value is negative|Invalid hashType/))) throw e if (!(e.message.match(/Not a DER sequence|Invalid sequence length|Expected a DER integer|R length is zero|S length is zero|R value excessively padded|S value excessively padded|R value is negative|S value is negative|Invalid hashType/)))
throw e
return false return false
} }

View file

@ -69,7 +69,6 @@ Transaction.fromBuffer = function(buffer, __disableAssert) {
script: readGenerationScript(), script: readGenerationScript(),
sequence: readUInt32() sequence: readUInt32()
}) })
} else { } else {
tx.ins.push({ tx.ins.push({
hash: hash, hash: hash,
@ -127,10 +126,8 @@ Transaction.prototype.addInput = function(hash, index, sequence, script) {
if (typeof hash === 'string') { if (typeof hash === 'string') {
// TxId hex is big-endian, we need little-endian // TxId hex is big-endian, we need little-endian
hash = bufferutils.reverse(new Buffer(hash, 'hex')) hash = bufferutils.reverse(new Buffer(hash, 'hex'))
} else if (hash instanceof Transaction) { } else if (hash instanceof Transaction) {
hash = hash.getHash() hash = hash.getHash()
} }
typeForce('Buffer', hash) typeForce('Buffer', hash)
@ -239,12 +236,11 @@ Transaction.prototype.hashForSignature = function(inIndex, prevOutScript, hashTy
txTmp.ins[inIndex].script = hashScript txTmp.ins[inIndex].script = hashScript
var hashTypeModifier = hashType & 0x1f var hashTypeModifier = hashType & 0x1f
if (hashTypeModifier === Transaction.SIGHASH_NONE) { if (hashTypeModifier === Transaction.SIGHASH_NONE) {
assert(false, 'SIGHASH_NONE not yet supported') assert(false, 'SIGHASH_NONE not yet supported')
} else if (hashTypeModifier === Transaction.SIGHASH_SINGLE) { } else if (hashTypeModifier === Transaction.SIGHASH_SINGLE) {
assert(false, 'SIGHASH_SINGLE not yet supported') assert(false, 'SIGHASH_SINGLE not yet supported')
} }
if (hashType & Transaction.SIGHASH_ANYONECANPAY) { if (hashType & Transaction.SIGHASH_ANYONECANPAY) {
@ -278,8 +274,12 @@ Transaction.prototype.toBuffer = function () {
8 + 8 +
bufferutils.varIntSize(this.ins.length) + bufferutils.varIntSize(this.ins.length) +
bufferutils.varIntSize(this.outs.length) + bufferutils.varIntSize(this.outs.length) +
this.ins.reduce(function(sum, input) { return sum + 40 + scriptSize(input.script) }, 0) + this.ins.reduce(function (sum, input) {
this.outs.reduce(function(sum, output) { return sum + 8 + scriptSize(output.script) }, 0) return sum + 40 + scriptSize(input.script)
}, 0) +
this.outs.reduce(function (sum, output) {
return sum + 8 + scriptSize(output.script)
}, 0)
) )
var offset = 0 var offset = 0
@ -339,7 +339,7 @@ Transaction.prototype.setInputScript = function(index, script) {
// FIXME: remove in 2.x.y // FIXME: remove in 2.x.y
Transaction.prototype.sign = function (index, privKey, hashType) { Transaction.prototype.sign = function (index, privKey, hashType) {
console.warn("Transaction.prototype.sign is deprecated. Use TransactionBuilder instead.") console.warn('Transaction.prototype.sign is deprecated. Use TransactionBuilder instead.')
var prevOutScript = privKey.pub.getAddress().toOutputScript() var prevOutScript = privKey.pub.getAddress().toOutputScript()
var signature = this.signInput(index, prevOutScript, privKey, hashType) var signature = this.signInput(index, prevOutScript, privKey, hashType)
@ -350,7 +350,7 @@ Transaction.prototype.sign = function(index, privKey, hashType) {
// FIXME: remove in 2.x.y // FIXME: remove in 2.x.y
Transaction.prototype.signInput = function (index, prevOutScript, privKey, hashType) { Transaction.prototype.signInput = function (index, prevOutScript, privKey, hashType) {
console.warn("Transaction.prototype.signInput is deprecated. Use TransactionBuilder instead.") console.warn('Transaction.prototype.signInput is deprecated. Use TransactionBuilder instead.')
hashType = hashType || Transaction.SIGHASH_ALL hashType = hashType || Transaction.SIGHASH_ALL
@ -362,7 +362,7 @@ Transaction.prototype.signInput = function(index, prevOutScript, privKey, hashTy
// FIXME: remove in 2.x.y // FIXME: remove in 2.x.y
Transaction.prototype.validateInput = function (index, prevOutScript, pubKey, buffer) { Transaction.prototype.validateInput = function (index, prevOutScript, pubKey, buffer) {
console.warn("Transaction.prototype.validateInput is deprecated. Use TransactionBuilder instead.") console.warn('Transaction.prototype.validateInput is deprecated. Use TransactionBuilder instead.')
var parsed = ECSignature.parseScriptSignature(buffer) var parsed = ECSignature.parseScriptSignature(buffer)
var hash = this.hashForSignature(index, prevOutScript, parsed.hashType) var hash = this.hashForSignature(index, prevOutScript, parsed.hashType)

View file

@ -21,7 +21,6 @@ function extractInput(txIn) {
scriptSig = Script.fromChunks(scriptSig.chunks.slice(0, -1)) scriptSig = Script.fromChunks(scriptSig.chunks.slice(0, -1))
scriptType = scripts.classifyInput(scriptSig, true) scriptType = scripts.classifyInput(scriptSig, true)
} else { } else {
scriptType = prevOutType scriptType = prevOutType
} }
@ -124,19 +123,21 @@ TransactionBuilder.fromTransaction = function(transaction) {
TransactionBuilder.prototype.addInput = function (prevTx, index, sequence, prevOutScript) { TransactionBuilder.prototype.addInput = function (prevTx, index, sequence, prevOutScript) {
var prevOutHash var prevOutHash
// txId
if (typeof prevTx === 'string') { if (typeof prevTx === 'string') {
prevOutHash = new Buffer(prevTx, 'hex') prevOutHash = new Buffer(prevTx, 'hex')
// TxId hex is big-endian, we want little-endian hash // TxId hex is big-endian, we want little-endian hash
Array.prototype.reverse.call(prevOutHash) Array.prototype.reverse.call(prevOutHash)
// Transaction
} else if (prevTx instanceof Transaction) { } else if (prevTx instanceof Transaction) {
prevOutHash = prevTx.getHash() prevOutHash = prevTx.getHash()
prevOutScript = prevTx.outs[index].script prevOutScript = prevTx.outs[index].script
// txHash
} else { } else {
prevOutHash = prevTx prevOutHash = prevTx
} }
var input = {} var input = {}
@ -188,10 +189,18 @@ TransactionBuilder.prototype.addOutput = function(scriptPubKey, value) {
return this.tx.addOutput(scriptPubKey, value) return this.tx.addOutput(scriptPubKey, value)
} }
TransactionBuilder.prototype.build = function() { return this.__build(false) } TransactionBuilder.prototype.build = function () {
TransactionBuilder.prototype.buildIncomplete = function() { return this.__build(true) } return this.__build(false)
}
TransactionBuilder.prototype.buildIncomplete = function () {
return this.__build(true)
}
var canSignTypes = { 'pubkeyhash': true, 'multisig': true, 'pubkey': true } var canSignTypes = {
'pubkeyhash': true,
'multisig': true,
'pubkey': true
}
TransactionBuilder.prototype.__build = function (allowIncomplete) { TransactionBuilder.prototype.__build = function (allowIncomplete) {
if (!allowIncomplete) { if (!allowIncomplete) {
@ -280,6 +289,7 @@ TransactionBuilder.prototype.sign = function(index, privKey, redeemScript, hashT
// no? prepare // no? prepare
} else { } else {
// must be pay-to-scriptHash?
if (redeemScript) { if (redeemScript) {
// if we have a prevOutScript, enforce scriptHash equality to the redeemScript // if we have a prevOutScript, enforce scriptHash equality to the redeemScript
if (input.prevOutScript) { if (input.prevOutScript) {
@ -320,10 +330,11 @@ TransactionBuilder.prototype.sign = function(index, privKey, redeemScript, hashT
input.redeemScript = redeemScript input.redeemScript = redeemScript
input.scriptType = scriptType input.scriptType = scriptType
// cannot be pay-to-scriptHash
} else { } else {
assert.notEqual(input.prevOutType, 'scripthash', 'PrevOutScript is P2SH, missing redeemScript') assert.notEqual(input.prevOutType, 'scripthash', 'PrevOutScript is P2SH, missing redeemScript')
// can we sign this? // can we otherwise sign this?
if (input.scriptType) { if (input.scriptType) {
assert(input.pubKeys, input.scriptType + ' not supported') assert(input.pubKeys, input.scriptType + ' not supported')
@ -333,7 +344,6 @@ TransactionBuilder.prototype.sign = function(index, privKey, redeemScript, hashT
input.prevOutType = 'pubkeyhash' input.prevOutType = 'pubkeyhash'
input.pubKeys = [privKey.pub] input.pubKeys = [privKey.pub]
input.scriptType = input.prevOutType input.scriptType = input.prevOutType
} }
} }

View file

@ -51,10 +51,18 @@ function Wallet(seed, network) {
me.unspentMap = {} me.unspentMap = {}
} }
this.getMasterKey = function() { return masterKey } this.getMasterKey = function () {
this.getAccountZero = function() { return accountZero } return masterKey
this.getExternalAccount = function() { return externalAccount } }
this.getInternalAccount = function() { return internalAccount } this.getAccountZero = function () {
return accountZero
}
this.getExternalAccount = function () {
return externalAccount
}
this.getInternalAccount = function () {
return internalAccount
}
} }
Wallet.prototype.createTransaction = function (to, value, options) { Wallet.prototype.createTransaction = function (to, value, options) {
@ -144,7 +152,8 @@ Wallet.prototype.__processTx = function(tx, isPending) {
try { try {
address = Address.fromOutputScript(txOut.script, this.network).toString() address = Address.fromOutputScript(txOut.script, this.network).toString()
} catch (e) { } catch (e) {
if (!(e.message.match(/has no matching Address/))) throw e if (!(e.message.match(/has no matching Address/)))
throw e
} }
var myAddresses = this.addresses.concat(this.changeAddresses) var myAddresses = this.addresses.concat(this.changeAddresses)
@ -168,7 +177,7 @@ Wallet.prototype.__processTx = function(tx, isPending) {
} }
}, this) }, this)
tx.ins.forEach(function(txIn, i) { tx.ins.forEach(function (txIn) {
// copy and convert to big-endian hex // copy and convert to big-endian hex
var txInId = bufferutils.reverse(txIn.hash).toString('hex') var txInId = bufferutils.reverse(txIn.hash).toString('hex')
@ -180,7 +189,6 @@ Wallet.prototype.__processTx = function(tx, isPending) {
if (isPending) { if (isPending) {
unspent.pending = true unspent.pending = true
unspent.spent = true unspent.spent = true
} else { } else {
delete this.unspentMap[lookup] delete this.unspentMap[lookup]
@ -308,7 +316,9 @@ Wallet.prototype.setUnspentOutputs = function(unspents) {
typeForce('Number', unspent.value) typeForce('Number', unspent.value)
assert.equal(txId.length, 64, 'Expected valid txId, got ' + txId) assert.equal(txId.length, 64, 'Expected valid txId, got ' + txId)
assert.doesNotThrow(function() { Address.fromBase58Check(unspent.address) }, 'Expected Base58 Address, got ' + unspent.address) assert.doesNotThrow(function () {
Address.fromBase58Check(unspent.address)
}, 'Expected Base58 Address, got ' + unspent.address)
assert(isFinite(index), 'Expected finite index, got ' + index) assert(isFinite(index), 'Expected finite index, got ' + index)
// FIXME: remove branch in 2.0.0 // FIXME: remove branch in 2.0.0

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var networks = require('../src/networks') var networks = require('../src/networks')

View file

@ -1,3 +1,5 @@
/* global describe, it, beforeEach */
var assert = require('assert') var assert = require('assert')
var base58check = require('../src/base58check') var base58check = require('../src/base58check')
var bs58check = require('bs58check') var bs58check = require('bs58check')

View file

@ -1,7 +1,7 @@
var assert = require('assert') /* global describe, it */
var assert = require('assert')
var base58 = require('bs58') var base58 = require('bs58')
//var base58check = require('bs58check')
var Bitcoin = require('../') var Bitcoin = require('../')
var Address = Bitcoin.Address var Address = Bitcoin.Address
@ -12,13 +12,13 @@ var ECSignature = Bitcoin.ECSignature
var Transaction = Bitcoin.Transaction var Transaction = Bitcoin.Transaction
var Script = Bitcoin.Script var Script = Bitcoin.Script
var base58_encode_decode = require("./fixtures/core/base58_encode_decode.json") var base58_encode_decode = require('./fixtures/core/base58_encode_decode.json')
var base58_keys_invalid = require("./fixtures/core/base58_keys_invalid.json") var base58_keys_invalid = require('./fixtures/core/base58_keys_invalid.json')
var base58_keys_valid = require("./fixtures/core/base58_keys_valid.json") var base58_keys_valid = require('./fixtures/core/base58_keys_valid.json')
var sig_canonical = require("./fixtures/core/sig_canonical.json") var sig_canonical = require('./fixtures/core/sig_canonical.json')
var sig_noncanonical = require("./fixtures/core/sig_noncanonical.json") var sig_noncanonical = require('./fixtures/core/sig_noncanonical.json')
var sighash = require("./fixtures/core/sighash.json") var sighash = require('./fixtures/core/sighash.json')
var tx_valid = require("./fixtures/core/tx_valid.json") var tx_valid = require('./fixtures/core/tx_valid.json')
describe('Bitcoin-core', function () { describe('Bitcoin-core', function () {
// base58_encode_decode // base58_encode_decode
@ -45,6 +45,11 @@ describe('Bitcoin-core', function() {
// base58_keys_valid // base58_keys_valid
describe('Address', function () { describe('Address', function () {
var typeMap = {
'pubkey': 'pubKeyHash',
'script': 'scriptHash'
}
base58_keys_valid.forEach(function (f) { base58_keys_valid.forEach(function (f) {
var string = f[0] var string = f[0]
var hex = f[1] var hex = f[1]
@ -52,18 +57,14 @@ describe('Bitcoin-core', function() {
var network = networks.bitcoin var network = networks.bitcoin
if (params.isPrivkey) return if (params.isPrivkey) return
if (params.isTestnet) network = networks.testnet if (params.isTestnet)
network = networks.testnet
it('can import ' + string, function () { it('can import ' + string, function () {
var address = Address.fromBase58Check(string) var address = Address.fromBase58Check(string)
assert.equal(address.hash.toString('hex'), hex) assert.equal(address.hash.toString('hex'), hex)
if (params.addrType === 'pubkey') { assert.equal(address.version, network[typeMap[params.addrType]])
assert.equal(address.version, network.pubKeyHash)
} else if (params.addrType === 'script') {
assert.equal(address.version, network.scriptHash)
}
}) })
}) })
}) })
@ -190,7 +191,8 @@ describe('Bitcoin-core', function() {
actualHash = transaction.hashForSignature(inIndex, script, hashType) actualHash = transaction.hashForSignature(inIndex, script, hashType)
} catch (e) { } catch (e) {
// don't fail if we don't support it yet, TODO // don't fail if we don't support it yet, TODO
if (!e.message.match(/not yet supported/)) throw e if (!e.message.match(/not yet supported/))
throw e
} }
if (actualHash !== undefined) { if (actualHash !== undefined) {

View file

@ -1,3 +1,5 @@
/* global describe, it, beforeEach */
var assert = require('assert') var assert = require('assert')
var Block = require('../src/block') var Block = require('../src/block')

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var bufferutils = require('../src/bufferutils') var bufferutils = require('../src/bufferutils')

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var crypto = require('../src/crypto') var crypto = require('../src/crypto')

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var crypto = require('../src/crypto') var crypto = require('../src/crypto')
var ecdsa = require('../src/ecdsa') var ecdsa = require('../src/ecdsa')
@ -15,10 +17,12 @@ var fixtures = require('./fixtures/ecdsa.json')
describe('ecdsa', function () { describe('ecdsa', function () {
describe('deterministicGenerateK', function () { describe('deterministicGenerateK', function () {
function checkSig() { return true } function checkSig () {
return true
}
fixtures.valid.ecdsa.forEach(function (f) { fixtures.valid.ecdsa.forEach(function (f) {
it('for \"' + f.message + '\"', function() { it('for "' + f.message + '"', function () {
var d = BigInteger.fromHex(f.d) var d = BigInteger.fromHex(f.d)
var h1 = crypto.sha256(f.message) var h1 = crypto.sha256(f.message)
@ -29,7 +33,7 @@ describe('ecdsa', function() {
// FIXME: remove in 2.0.0 // FIXME: remove in 2.0.0
fixtures.valid.ecdsa.forEach(function (f) { fixtures.valid.ecdsa.forEach(function (f) {
it('(deprecated) for \"' + f.message + '\"', function() { it('(deprecated) for "' + f.message + '"', function () {
var d = BigInteger.fromHex(f.d) var d = BigInteger.fromHex(f.d)
var h1 = crypto.sha256(f.message) var h1 = crypto.sha256(f.message)
@ -73,7 +77,7 @@ describe('ecdsa', function() {
})) }))
fixtures.valid.rfc6979.forEach(function (f) { fixtures.valid.rfc6979.forEach(function (f) {
it('produces the expected k values for ' + f.message + ' if k wasn\'t suitable', function() { it('produces the expected k values for ' + f.message + " if k wasn't suitable", function () {
var d = BigInteger.fromHex(f.d) var d = BigInteger.fromHex(f.d)
var h1 = crypto.sha256(f.message) var h1 = crypto.sha256(f.message)
@ -145,7 +149,7 @@ describe('ecdsa', function() {
describe('sign', function () { describe('sign', function () {
fixtures.valid.ecdsa.forEach(function (f) { fixtures.valid.ecdsa.forEach(function (f) {
it('produces a deterministic signature for \"' + f.message + '\"', function() { it('produces a deterministic signature for "' + f.message + '"', function () {
var d = BigInteger.fromHex(f.d) var d = BigInteger.fromHex(f.d)
var hash = crypto.sha256(f.message) var hash = crypto.sha256(f.message)
var signature = ecdsa.sign(curve, hash, d) var signature = ecdsa.sign(curve, hash, d)
@ -167,7 +171,7 @@ describe('ecdsa', function() {
describe('verify/verifyRaw', function () { describe('verify/verifyRaw', function () {
fixtures.valid.ecdsa.forEach(function (f) { fixtures.valid.ecdsa.forEach(function (f) {
it('verifies a valid signature for \"' + f.message + '\"', function() { it('verifies a valid signature for "' + f.message + '"', function () {
var d = BigInteger.fromHex(f.d) var d = BigInteger.fromHex(f.d)
var H = crypto.sha256(f.message) var H = crypto.sha256(f.message)
var e = BigInteger.fromBuffer(H) var e = BigInteger.fromBuffer(H)

View file

@ -1,3 +1,6 @@
/* global describe, it, beforeEach, afterEach */
/* eslint-disable no-new */
var assert = require('assert') var assert = require('assert')
var crypto = require('crypto') var crypto = require('crypto')
var ecurve = require('ecurve') var ecurve = require('ecurve')

View file

@ -1,3 +1,5 @@
/* global describe, it, beforeEach */
var assert = require('assert') var assert = require('assert')
var crypto = require('../src/crypto') var crypto = require('../src/crypto')
var networks = require('../src/networks') var networks = require('../src/networks')
@ -109,7 +111,7 @@ describe('ECPubKey', function() {
assert(pubKey.verify(hash, signature)) assert(pubKey.verify(hash, signature))
}) })
it('doesn\'t verify the wrong signature', function() { it("doesn't verify the wrong signature", function () {
var hash = crypto.sha256('mushrooms') var hash = crypto.sha256('mushrooms')
assert(!pubKey.verify(hash, signature)) assert(!pubKey.verify(hash, signature))

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var BigInteger = require('bigi') var BigInteger = require('bigi')

View file

@ -1,3 +1,6 @@
/* global describe, it */
/* eslint-disable no-new */
var assert = require('assert') var assert = require('assert')
var networks = require('../src/networks') var networks = require('../src/networks')
@ -297,7 +300,6 @@ describe('HDNode', function() {
it(c.description + ' from ' + f.master.fingerprint, function () { it(c.description + ' from ' + f.master.fingerprint, function () {
if (c.hardened) { if (c.hardened) {
hd = hd.deriveHardened(c.m) hd = hd.deriveHardened(c.m)
} else { } else {
hd = hd.derive(c.m) hd = hd.derive(c.m)
} }

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var bitcoin = require('../../') var bitcoin = require('../../')
var blockchain = new (require('cb-helloblock'))('testnet') var blockchain = new (require('cb-helloblock'))('testnet')
@ -22,7 +24,7 @@ describe('bitcoinjs-lib (advanced)', function() {
it('can create an OP_RETURN transaction', function (done) { it('can create an OP_RETURN transaction', function (done) {
this.timeout(20000) this.timeout(20000)
var key = bitcoin.ECKey.fromWIF("L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy") var key = bitcoin.ECKey.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy')
var address = key.pub.getAddress(bitcoin.networks.testnet).toString() var address = key.pub.getAddress(bitcoin.networks.testnet).toString()
blockchain.addresses.__faucetWithdraw(address, 2e4, function (err) { blockchain.addresses.__faucetWithdraw(address, 2e4, function (err) {

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var bigi = require('bigi') var bigi = require('bigi')
var bitcoin = require('../../') var bitcoin = require('../../')
@ -34,11 +36,11 @@ describe('bitcoinjs-lib (basic)', function() {
}) })
it('can create a Transaction', function () { it('can create a Transaction', function () {
var key = bitcoin.ECKey.fromWIF("L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy") var key = bitcoin.ECKey.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy')
var tx = new bitcoin.TransactionBuilder() var tx = new bitcoin.TransactionBuilder()
tx.addInput("aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31", 0) tx.addInput('aa94ab02c182214f090e99a0d57021caffd0f195a81c24602b1028b130b63e31', 0)
tx.addOutput("1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK", 15000) tx.addOutput('1Gokm82v6DmtwKEB8AiVhm82hyFSsEvBDK', 15000)
tx.sign(0, key) tx.sign(0, key)
assert.equal(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000') assert.equal(tx.build().toHex(), '0100000001313eb630b128102b60241ca895f1d0ffca2170d5a0990e094f2182c102ab94aa000000006b483045022100aefbcf847900b01dd3e3debe054d3b6d03d715d50aea8525f5ea3396f168a1fb022013d181d05b15b90111808b22ef4f9ebe701caf2ab48db269691fdf4e9048f4f60121029f50f51d63b345039a290c94bffd3180c99ed659ff6ea6b1242bca47eb93b59fffffffff01983a0000000000001976a914ad618cf4333b3b248f9744e8e81db2964d0ae39788ac00000000')

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var async = require('async') var async = require('async')
var bigi = require('bigi') var bigi = require('bigi')
@ -41,7 +43,7 @@ describe('bitcoinjs-lib (crypto)', function() {
// TODO // TODO
it.skip('can generate a dual-key stealth address', function () {}) it.skip('can generate a dual-key stealth address', function () {})
it('can recover a parent private key from the parent\'s public key and a derived non-hardened child private key', function() { it("can recover a parent private key from the parent's public key and a derived non-hardened child private key", function () {
function recoverParent (master, child) { function recoverParent (master, child) {
assert(!master.privKey, 'You already have the parent private key') assert(!master.privKey, 'You already have the parent private key')
assert(child.privKey, 'Missing child private key') assert(child.privKey, 'Missing child private key')
@ -90,16 +92,18 @@ describe('bitcoinjs-lib (crypto)', function() {
it('can recover a private key from duplicate R values', function () { it('can recover a private key from duplicate R values', function () {
var inputs = [ var inputs = [
{ {
txId: "f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50", txId: 'f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50',
vout: 0 vout: 0
}, },
{ {
txId: "f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50", txId: 'f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50',
vout: 1 vout: 1
} }
] ]
var txIds = inputs.map(function(x) { return x.txId }) var txIds = inputs.map(function (x) {
return x.txId
})
// first retrieve the relevant transactions // first retrieve the relevant transactions
blockchain.transactions.get(txIds, function (err, results) { blockchain.transactions.get(txIds, function (err, results) {
@ -145,7 +149,8 @@ describe('bitcoinjs-lib (crypto)', function() {
// finally, run the tasks, then on to the math // finally, run the tasks, then on to the math
async.parallel(tasks, function (err) { async.parallel(tasks, function (err) {
if (err) throw err if (err)
throw err
var n = bitcoin.ECKey.curve.n var n = bitcoin.ECKey.curve.n
for (var i = 0; i < inputs.length; ++i) { for (var i = 0; i < inputs.length; ++i) {

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var bitcoin = require('../../') var bitcoin = require('../../')
var blockchain = new (require('cb-helloblock'))('testnet') var blockchain = new (require('cb-helloblock'))('testnet')
@ -24,7 +26,9 @@ describe('bitcoinjs-lib (multisig)', function() {
'91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx', '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx',
'91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT' '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT'
].map(bitcoin.ECKey.fromWIF) ].map(bitcoin.ECKey.fromWIF)
var pubKeys = privKeys.map(function(x) { return x.pub }) var pubKeys = privKeys.map(function (x) {
return x.pub
})
var redeemScript = bitcoin.scripts.multisigOutput(2, pubKeys) // 2 of 2 var redeemScript = bitcoin.scripts.multisigOutput(2, pubKeys) // 2 of 2
var scriptPubKey = bitcoin.scripts.scriptHashOutput(redeemScript.getHash()) var scriptPubKey = bitcoin.scripts.scriptHashOutput(redeemScript.getHash())
@ -39,7 +43,9 @@ describe('bitcoinjs-lib (multisig)', function() {
if (err) return done(err) if (err) return done(err)
// filter small unspents // filter small unspents
unspents = unspents.filter(function(unspent) { return unspent.value > 1e4 }) unspents = unspents.filter(function (unspent) {
return unspent.value > 1e4
})
// use the oldest unspent // use the oldest unspent
var unspent = unspents.pop() var unspent = unspents.pop()

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var networks = require('../src/networks') var networks = require('../src/networks')
@ -11,7 +13,7 @@ var fixtures = require('./fixtures/message.json')
describe('Message', function () { describe('Message', function () {
describe('magicHash', function () { describe('magicHash', function () {
fixtures.valid.magicHash.forEach(function (f) { fixtures.valid.magicHash.forEach(function (f) {
it('produces the correct magicHash for \"' + f.message + '\" (' + f.network + ')', function() { it('produces the correct magicHash for "' + f.message + '" (' + f.network + ')', function () {
var network = networks[f.network] var network = networks[f.network]
var actual = Message.magicHash(f.message, network) var actual = Message.magicHash(f.message, network)
@ -30,7 +32,7 @@ describe('Message', function() {
}) })
fixtures.valid.verify.forEach(function (f) { fixtures.valid.verify.forEach(function (f) {
it('verifies a valid signature for \"' + f.message + '\" (' + f.network + ')', function() { it('verifies a valid signature for "' + f.message + '" (' + f.network + ')', function () {
var network = networks[f.network] var network = networks[f.network]
assert(Message.verify(f.address, f.signature, f.message, network)) assert(Message.verify(f.address, f.signature, f.message, network))

View file

@ -1,3 +1,5 @@
/* global describe, it, before, after */
var assert = require('assert') var assert = require('assert')
var networks = require('../src/networks') var networks = require('../src/networks')
var sinon = require('sinon') var sinon = require('sinon')
@ -10,7 +12,7 @@ var fixtures = require('./fixtures/network')
describe('networks', function () { describe('networks', function () {
var txToBuffer var txToBuffer
before(function () { before(function () {
txToBuffer = sinon.stub(Transaction.prototype, "toBuffer") txToBuffer = sinon.stub(Transaction.prototype, 'toBuffer')
}) })
after(function () { after(function () {

View file

@ -1,3 +1,6 @@
/* global describe, it */
/* eslint-disable no-new */
var assert = require('assert') var assert = require('assert')
var opcodes = require('../src/opcodes') var opcodes = require('../src/opcodes')
@ -17,7 +20,9 @@ describe('Script', function() {
}) })
it('throws an error when input is not an array', function () { it('throws an error when input is not an array', function () {
assert.throws(function(){ new Script({}) }, /Expected Buffer, got/) assert.throws(function () {
new Script({})
}, /Expected Buffer, got/)
}) })
}) })
@ -39,7 +44,7 @@ describe('Script', function() {
describe('getHash', function () { describe('getHash', function () {
fixtures.valid.forEach(function (f) { fixtures.valid.forEach(function (f) {
it('produces a HASH160 of \"' + f.asm + '\"', function() { it('produces a HASH160 of "' + f.asm + '"', function () {
var script = Script.fromHex(f.hex) var script = Script.fromHex(f.hex)
assert.equal(script.getHash().toString('hex'), f.hash) assert.equal(script.getHash().toString('hex'), f.hash)

View file

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert') var assert = require('assert')
var ops = require('../src/opcodes') var ops = require('../src/opcodes')
var scripts = require('../src/scripts') var scripts = require('../src/scripts')

View file

@ -1,3 +1,5 @@
/* global describe, it, beforeEach */
var assert = require('assert') var assert = require('assert')
var scripts = require('../src/scripts') var scripts = require('../src/scripts')
@ -20,7 +22,6 @@ describe('Transaction', function() {
if (txIn.data) { if (txIn.data) {
script = new Script(new Buffer(txIn.data, 'hex'), []) script = new Script(new Buffer(txIn.data, 'hex'), [])
} else if (txIn.script) { } else if (txIn.script) {
script = Script.fromASM(txIn.script) script = Script.fromASM(txIn.script)
} }
@ -225,7 +226,9 @@ describe('Transaction', function() {
].map(function (wif) { ].map(function (wif) {
return ECKey.fromWIF(wif) return ECKey.fromWIF(wif)
}) })
var pubKeys = privKeys.map(function(eck) { return eck.pub }) var pubKeys = privKeys.map(function (eck) {
return eck.pub
})
var redeemScript = scripts.multisigOutput(2, pubKeys) var redeemScript = scripts.multisigOutput(2, pubKeys)
var signatures = privKeys.map(function (privKey) { var signatures = privKeys.map(function (privKey) {

View file

@ -1,3 +1,5 @@
/* global describe, it, beforeEach */
var assert = require('assert') var assert = require('assert')
var BigInteger = require('bigi') var BigInteger = require('bigi')
@ -41,8 +43,10 @@ function construct(txb, f, sign) {
} }
// FIXME: add support for locktime/version in TransactionBuilder API // FIXME: add support for locktime/version in TransactionBuilder API
if (f.version !== undefined) txb.tx.version = f.version if (f.version !== undefined)
if (f.locktime !== undefined) txb.tx.locktime = f.locktime txb.tx.version = f.version
if (f.locktime !== undefined)
txb.tx.locktime = f.locktime
} }
describe('TransactionBuilder', function () { describe('TransactionBuilder', function () {
@ -141,7 +145,6 @@ describe('TransactionBuilder', function() {
if (!sign.throws) { if (!sign.throws) {
txb.sign(index, privKey, redeemScript, sign.hashType) txb.sign(index, privKey, redeemScript, sign.hashType)
} else { } else {
assert.throws(function () { assert.throws(function () {
txb.sign(index, privKey, redeemScript, sign.hashType) txb.sign(index, privKey, redeemScript, sign.hashType)
@ -155,7 +158,7 @@ describe('TransactionBuilder', function() {
describe('build', function () { describe('build', function () {
fixtures.valid.build.forEach(function (f) { fixtures.valid.build.forEach(function (f) {
it('builds \"' + f.description + '\"', function() { it('builds "' + f.description + '"', function () {
construct(txb, f) construct(txb, f)
var tx = txb.build() var tx = txb.build()
@ -169,7 +172,6 @@ describe('TransactionBuilder', function() {
if (f.txHex) { if (f.txHex) {
var tx = Transaction.fromHex(f.txHex) var tx = Transaction.fromHex(f.txHex)
txb = TransactionBuilder.fromTransaction(tx) txb = TransactionBuilder.fromTransaction(tx)
} else { } else {
construct(txb, f) construct(txb, f)
} }
@ -182,7 +184,7 @@ describe('TransactionBuilder', function() {
}) })
if (f.alwaysThrows) return if (f.alwaysThrows) return
it('doesn\'t throw if building incomplete', function() { it("doesn't throw if building incomplete", function () {
txb.buildIncomplete() txb.buildIncomplete()
}) })
}) })
@ -211,13 +213,13 @@ describe('TransactionBuilder', function() {
it('works for the out-of-order P2SH multisig case', function () { it('works for the out-of-order P2SH multisig case', function () {
var privKeys = [ var privKeys = [
"91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT", '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT',
"91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx" '91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx'
].map(ECKey.fromWIF) ].map(ECKey.fromWIF)
var redeemScript = Script.fromASM("OP_2 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 04c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee51ae168fea63dc339a3c58419466ceaeef7f632653266d0e1236431a950cfe52a OP_2 OP_CHECKMULTISIG") var redeemScript = Script.fromASM('OP_2 0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8 04c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee51ae168fea63dc339a3c58419466ceaeef7f632653266d0e1236431a950cfe52a OP_2 OP_CHECKMULTISIG')
txb.addInput("4971f016798a167331bcbc67248313fbc444c6e92e4416efd06964425588f5cf", 0) txb.addInput('4971f016798a167331bcbc67248313fbc444c6e92e4416efd06964425588f5cf', 0)
txb.addOutput("1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH", 10000) txb.addOutput('1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH', 10000)
txb.sign(0, privKeys[0], redeemScript) txb.sign(0, privKeys[0], redeemScript)
var tx = txb.buildIncomplete() var tx = txb.buildIncomplete()

View file

@ -1,3 +1,5 @@
/* global describe, it, beforeEach, afterEach */
var assert = require('assert') var assert = require('assert')
var bufferutils = require('../src/bufferutils') var bufferutils = require('../src/bufferutils')
var crypto = require('../src/crypto') var crypto = require('../src/crypto')
@ -111,8 +113,8 @@ describe('Wallet', function() {
it('generate receiving addresses', function () { it('generate receiving addresses', function () {
var wallet = new Wallet(seed, networks.testnet) var wallet = new Wallet(seed, networks.testnet)
var expectedAddresses = [ var expectedAddresses = [
"n1GyUANZand9Kw6hGSV9837cCC9FFUQzQa", 'n1GyUANZand9Kw6hGSV9837cCC9FFUQzQa',
"n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X" 'n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X'
] ]
assert.equal(wallet.generateAddress(), expectedAddresses[0]) assert.equal(wallet.generateAddress(), expectedAddresses[0])
@ -122,14 +124,9 @@ 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']
assert.equal(wallet.generateChangeAddress(), expectedAddresses[0]) assert.equal(wallet.generateChangeAddress(), expectedAddresses[0])
assert.deepEqual(wallet.changeAddresses, expectedAddresses) assert.deepEqual(wallet.changeAddresses, expectedAddresses)
@ -137,11 +134,6 @@ 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)
@ -151,11 +143,6 @@ 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)
@ -165,11 +152,6 @@ 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()
@ -177,11 +159,11 @@ describe('Wallet', function() {
wallet.generateAddress() wallet.generateAddress()
assertEqual( assertEqual(
wallet.getPrivateKeyForAddress("n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X"), wallet.getPrivateKeyForAddress('n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X'),
wallet.getExternalAccount().derive(1).privKey wallet.getExternalAccount().derive(1).privKey
) )
assertEqual( assertEqual(
wallet.getPrivateKeyForAddress("mnXiDR4MKsFxcKJEZjx4353oXvo55iuptn"), wallet.getPrivateKeyForAddress('mnXiDR4MKsFxcKJEZjx4353oXvo55iuptn'),
wallet.getInternalAccount().derive(0).privKey wallet.getInternalAccount().derive(0).privKey
) )
}) })
@ -190,23 +172,23 @@ describe('Wallet', 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 utxo, expectedOutputKey var utxo
var wallet var wallet
beforeEach(function () { beforeEach(function () {
utxo = { utxo = {
"address" : "1AZpKpcfCzKDUeTFBQUL4MokQai3m3HMXv", 'address': '1AZpKpcfCzKDUeTFBQUL4MokQai3m3HMXv',
"confirmations": 1, 'confirmations': 1,
"index": 0, 'index': 0,
"txId": fakeTxId(6), 'txId': fakeTxId(6),
"value": 20000, 'value': 20000,
"pending": false 'pending': false
} }
}) })
@ -272,7 +254,6 @@ describe('Wallet', function() {
describe('setUnspentOutputs', function () { describe('setUnspentOutputs', function () {
var utxo var utxo
var expectedOutputKey
var wallet var wallet
beforeEach(function () { beforeEach(function () {
@ -296,7 +277,7 @@ describe('Wallet', function() {
describe('required fields', function () { describe('required fields', function () {
['index', '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[field] delete utxo[field]
assert.throws(function () { assert.throws(function () {
@ -326,15 +307,15 @@ describe('Wallet', function() {
tx = Transaction.fromHex(fixtureTx1Hex) tx = Transaction.fromHex(fixtureTx1Hex)
}) })
describe("processPendingTx", function() { describe('processPendingTx', function () {
it("incoming: sets the pending flag on output", function() { it('incoming: sets the pending flag on output', function () {
wallet.addresses = [addresses[0]] wallet.addresses = [addresses[0]]
wallet.processPendingTx(tx) wallet.processPendingTx(tx)
verifyOutputAdded(0, true) verifyOutputAdded(0, true)
}) })
describe("when tx ins outpoint contains a known txhash:i", function() { describe('when tx ins outpoint contains a known txhash:i', function () {
var spendTx var spendTx
beforeEach(function () { beforeEach(function () {
wallet.addresses = [addresses[0]] wallet.addresses = [addresses[0]]
@ -372,7 +353,7 @@ describe('Wallet', function() {
}) })
describe("when tx outs contains an address owned by the wallet, an 'output' gets added to wallet.unspentMap", function () { describe("when tx outs contains an address owned by the wallet, an 'output' gets added to wallet.unspentMap", function () {
it("works for receive address", function() { it('works for receive address', function () {
var totalOuts = outputCount() var totalOuts = outputCount()
wallet.addresses = [addresses[0]] wallet.addresses = [addresses[0]]
@ -382,7 +363,7 @@ describe('Wallet', function() {
verifyOutputAdded(0, false) verifyOutputAdded(0, false)
}) })
it("works for change address", function() { it('works for change address', function () {
var totalOuts = outputCount() var totalOuts = outputCount()
wallet.changeAddresses = [addresses[1]] wallet.changeAddresses = [addresses[1]]
@ -397,7 +378,7 @@ describe('Wallet', function() {
} }
}) })
describe("when tx ins contains a known txhash:i", function() { describe('when tx ins contains a known txhash:i', function () {
var spendTx var spendTx
beforeEach(function () { beforeEach(function () {
wallet.addresses = [addresses[0]] // the address fixtureTx2 used as input wallet.addresses = [addresses[0]] // the address fixtureTx2 used as input
@ -406,7 +387,7 @@ describe('Wallet', function() {
spendTx = Transaction.fromHex(fixtureTx2Hex) spendTx = Transaction.fromHex(fixtureTx2Hex)
}) })
it("does not add to wallet.unspentMap", function() { it('does not add to wallet.unspentMap', function () {
wallet.processConfirmedTx(spendTx) wallet.processConfirmedTx(spendTx)
assert.deepEqual(wallet.unspentMap, {}) assert.deepEqual(wallet.unspentMap, {})
}) })
@ -424,16 +405,15 @@ describe('Wallet', function() {
}) })
}) })
it("does nothing when none of the involved addresses belong to the wallet", function() { it('does nothing when none of the involved addresses belong to the wallet', function () {
wallet.processConfirmedTx(tx) wallet.processConfirmedTx(tx)
assert.deepEqual(wallet.unspentMap, {}) assert.deepEqual(wallet.unspentMap, {})
}) })
function verifyOutputAdded (index, pending) { function verifyOutputAdded (index, pending) {
var txOut = tx.outs[index] var txOut = tx.outs[index]
var key = tx.getId() + ":" + index var key = tx.getId() + ':' + index
var output = wallet.unspentMap[key] var output = wallet.unspentMap[key]
assert.deepEqual(output.txHash, tx.getHash()) assert.deepEqual(output.txHash, tx.getHash())
assert.equal(output.value, txOut.value) assert.equal(output.value, txOut.value)
@ -453,28 +433,28 @@ describe('Wallet', function() {
to = 'mt7MyTVVEWnbwpF5hBn6fgnJcv95Syk2ue' to = 'mt7MyTVVEWnbwpF5hBn6fgnJcv95Syk2ue'
value = 500000 value = 500000
address1 = "n1GyUANZand9Kw6hGSV9837cCC9FFUQzQa" address1 = 'n1GyUANZand9Kw6hGSV9837cCC9FFUQzQa'
address2 = "n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X" address2 = 'n2fiWrHqD6GM5GiEqkbWAc6aaZQp3ba93X'
// set up 3 utxos // set up 3 utxos
var utxos = [ var utxos = [
{ {
"txId": fakeTxId(1), 'txId': fakeTxId(1),
"index": 0, 'index': 0,
"address": address1, 'address': address1,
"value": 400000 // not enough for value 'value': 400000 // not enough for value
}, },
{ {
"txId": fakeTxId(2), 'txId': fakeTxId(2),
"index": 1, 'index': 1,
"address": address1, 'address': address1,
"value": 500000 // enough for only value 'value': 500000 // enough for only value
}, },
{ {
"txId": fakeTxId(3), 'txId': fakeTxId(3),
"index": 0, 'index': 0,
"address" : address2, 'address': address2,
"value": 510000 // enough for value and fee 'value': 510000 // enough for value and fee
} }
] ]
@ -487,7 +467,9 @@ describe('Wallet', function() {
describe('transaction fee', function () { describe('transaction fee', function () {
it('allows fee to be specified', function () { it('allows fee to be specified', function () {
var fee = 30000 var fee = 30000
var tx = wallet.createTx(to, value, { fixedFee: fee }) var tx = wallet.createTx(to, value, {
fixedFee: fee
})
assert.equal(getFee(wallet, tx), fee) assert.equal(getFee(wallet, tx), fee)
}) })
@ -495,7 +477,9 @@ describe('Wallet', function() {
it('allows fee to be set to zero', function () { it('allows fee to be set to zero', function () {
value = 510000 value = 510000
var fee = 0 var fee = 0
var tx = wallet.createTx(to, value, { fixedFee: fee }) var tx = wallet.createTx(to, value, {
fixedFee: fee
})
assert.equal(getFee(wallet, tx), fee) assert.equal(getFee(wallet, tx), fee)
}) })
@ -504,7 +488,7 @@ describe('Wallet', function() {
var utxo = { var utxo = {
txId: fakeTxId(0), txId: fakeTxId(0),
index: 0, index: 0,
address: "LeyySKbQrRRwodKEj1W4a8y3YQupPLw5os", address: 'LeyySKbQrRRwodKEj1W4a8y3YQupPLw5os',
value: 500000 value: 500000
} }
@ -608,7 +592,9 @@ describe('Wallet', function() {
var fee = 0 var fee = 0
wallet.generateChangeAddress() wallet.generateChangeAddress()
wallet.generateChangeAddress() wallet.generateChangeAddress()
var tx = wallet.createTx(to, value, { fixedFee: fee }) var tx = wallet.createTx(to, value, {
fixedFee: fee
})
assert.equal(tx.outs.length, 2) assert.equal(tx.outs.length, 2)
var out = tx.outs[1] var out = tx.outs[1]
@ -622,7 +608,9 @@ describe('Wallet', function() {
var fee = 0 var fee = 0
assert.equal(wallet.changeAddresses.length, 0) assert.equal(wallet.changeAddresses.length, 0)
var tx = wallet.createTx(to, value, { fixedFee: fee }) var tx = wallet.createTx(to, value, {
fixedFee: fee
})
assert.equal(wallet.changeAddresses.length, 1) assert.equal(wallet.changeAddresses.length, 1)
var out = tx.outs[1] var out = tx.outs[1]
@ -649,15 +637,18 @@ describe('Wallet', function() {
it('signs the inputs with respective keys', function () { it('signs the inputs with respective keys', function () {
var fee = 30000 var fee = 30000
sinon.spy(TransactionBuilder.prototype, "sign") sinon.spy(TransactionBuilder.prototype, 'sign')
wallet.createTx(to, value, { fixedFee: fee }) wallet.createTx(to, value, {
fixedFee: fee
})
var priv1 = wallet.getPrivateKeyForAddress(address1) var priv1 = wallet.getPrivateKeyForAddress(address1)
var priv2 = wallet.getPrivateKeyForAddress(address2) var priv2 = wallet.getPrivateKeyForAddress(address2)
// FIXME: boo (required) side effects // FIXME: boo, toString invokes reqiuired affine coordinate side effects
priv1.pub.Q.affineX, priv2.pub.Q.affineX priv1.pub.Q.toString()
priv2.pub.Q.toString()
assert(TransactionBuilder.prototype.sign.calledWith(0, priv2)) assert(TransactionBuilder.prototype.sign.calledWith(0, priv2))
assert(TransactionBuilder.prototype.sign.calledWith(1, priv1)) assert(TransactionBuilder.prototype.sign.calledWith(1, priv1))