Browse Source

Merge pull request #364 from bitcoinjs/standard

use standardjs formatting
hk-custom-address
Daniel Cousens 10 years ago
parent
commit
7513e73f74
  1. 5
      .travis.yml
  2. 19
      jshint.json
  3. 6
      package.json
  4. 4
      src/base58check.js
  5. 1
      src/block.js
  6. 2
      src/bufferutils.js
  7. 3
      src/ecpubkey.js
  8. 3
      src/ecsignature.js
  9. 7
      src/hdnode.js
  10. 2
      src/networks.js
  11. 11
      src/script.js
  12. 6
      src/scripts.js
  13. 20
      src/transaction.js
  14. 24
      src/transaction_builder.js
  15. 26
      src/wallet.js
  16. 2
      test/address.js
  17. 2
      test/base58check.js
  18. 36
      test/bitcoin.core.js
  19. 2
      test/block.js
  20. 2
      test/bufferutils.js
  21. 2
      test/crypto.js
  22. 16
      test/ecdsa.js
  23. 3
      test/eckey.js
  24. 4
      test/ecpubkey.js
  25. 2
      test/ecsignature.js
  26. 4
      test/hdnode.js
  27. 4
      test/integration/advanced.js
  28. 8
      test/integration/basic.js
  29. 15
      test/integration/crypto.js
  30. 10
      test/integration/multisig.js
  31. 6
      test/message.js
  32. 4
      test/network.js
  33. 9
      test/script.js
  34. 2
      test/scripts.js
  35. 7
      test/transaction.js
  36. 24
      test/transaction_builder.js
  37. 127
      test/wallet.js

5
.travis.yml

@ -5,7 +5,8 @@ node_js:
- "0.11"
- "0.10"
env:
- TEST_SUITE=unit
- TEST_SUITE=integration
- TEST_SUITE=coveralls
- TEST_SUITE=integration
- TEST_SUITE=standard
- TEST_SUITE=unit
script: "npm run-script $TEST_SUITE"

19
jshint.json

@ -1,19 +0,0 @@
{
"asi": true,
"camelcase": true,
"freeze": true,
"immed": true,
"indent": 2,
"latedef": true,
"maxcomplexity": 10,
"maxlen": 120,
"noarg": true,
"noempty": true,
"nonbsp": true,
"node": true,
"nonew": true,
"undef": true,
"unused": true,
"strict": false,
"trailing": true
}

6
package.json

@ -36,7 +36,7 @@
"coverage": "istanbul cover _mocha -- test/*.js",
"coveralls": "npm run-script coverage && coveralls < coverage/lcov.info",
"integration": "mocha --reporter list test/integration/*.js",
"jshint": "jshint --config jshint.json src/*.js ; true",
"standard": "standard",
"test": "npm run-script unit",
"unit": "istanbul test mocha -- --reporter list test/*.js"
},
@ -57,9 +57,9 @@
"cb-helloblock": "^0.4.10",
"coveralls": "^2.11.2",
"istanbul": "^0.3.5",
"jshint": "^2.5.11",
"mocha": "^2.1.0",
"mocha-lcov-reporter": "0.0.1",
"sinon": "^1.12.2"
"sinon": "^1.12.2",
"standard": "^2.7.3"
}
}

4
src/base58check.js

@ -1,13 +1,13 @@
var bs58check = require('bs58check')
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)
}
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)
}

1
src/block.js

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

2
src/bufferutils.js

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

3
src/ecpubkey.js

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

3
src/ecsignature.js

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

7
src/hdnode.js

@ -16,9 +16,7 @@ function findBIP32NetworkByVersion(version) {
for (var name in networks) {
var network = networks[name]
if (version === network.bip32.private ||
version === network.bip32.public) {
if (version === network.bip32.private || version === network.bip32.public) {
return network
}
}
@ -95,7 +93,7 @@ HDNode.fromBuffer = function(buffer, network, __ignoreDeprecation) {
var version = buffer.readUInt32BE(0)
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
} else {
@ -221,7 +219,6 @@ HDNode.prototype.toBuffer = function(isPrivate, __ignoreDeprecation) {
buffer.writeUInt8(0, 45)
this.privKey.d.toBuffer(32).copy(buffer, 46)
} else {
// X9.62 encoding for public keys
this.pubKey.toBuffer().copy(buffer, 45)
}

2
src/networks.js

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

11
src/script.js

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

6
src/scripts.js

@ -14,7 +14,8 @@ function isCanonicalPubKey(buffer) {
try {
ecurve.Point.decodeFrom(curve, buffer)
} catch (e) {
if (!(e.message.match(/Invalid sequence (length|tag)/))) throw e
if (!(e.message.match(/Invalid sequence (length|tag)/)))
throw e
return false
}
@ -28,7 +29,8 @@ function isCanonicalSignature(buffer) {
try {
ECSignature.parseScriptSignature(buffer)
} 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
}

20
src/transaction.js

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

24
src/transaction_builder.js

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

26
src/wallet.js

@ -51,10 +51,18 @@ function Wallet(seed, network) {
me.unspentMap = {}
}
this.getMasterKey = function() { return masterKey }
this.getAccountZero = function() { return accountZero }
this.getExternalAccount = function() { return externalAccount }
this.getInternalAccount = function() { return internalAccount }
this.getMasterKey = function () {
return masterKey
}
this.getAccountZero = function () {
return accountZero
}
this.getExternalAccount = function () {
return externalAccount
}
this.getInternalAccount = function () {
return internalAccount
}
}
Wallet.prototype.createTransaction = function (to, value, options) {
@ -144,7 +152,8 @@ Wallet.prototype.__processTx = function(tx, isPending) {
try {
address = Address.fromOutputScript(txOut.script, this.network).toString()
} 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)
@ -168,7 +177,7 @@ Wallet.prototype.__processTx = function(tx, isPending) {
}
}, this)
tx.ins.forEach(function(txIn, i) {
tx.ins.forEach(function (txIn) {
// copy and convert to big-endian hex
var txInId = bufferutils.reverse(txIn.hash).toString('hex')
@ -180,7 +189,6 @@ Wallet.prototype.__processTx = function(tx, isPending) {
if (isPending) {
unspent.pending = true
unspent.spent = true
} else {
delete this.unspentMap[lookup]
@ -308,7 +316,9 @@ Wallet.prototype.setUnspentOutputs = function(unspents) {
typeForce('Number', unspent.value)
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)
// FIXME: remove branch in 2.0.0

2
test/address.js

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

2
test/base58check.js

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

36
test/bitcoin.core.js

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

2
test/block.js

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

2
test/bufferutils.js

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

2
test/crypto.js

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

16
test/ecdsa.js

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert')
var crypto = require('../src/crypto')
var ecdsa = require('../src/ecdsa')
@ -15,10 +17,12 @@ var fixtures = require('./fixtures/ecdsa.json')
describe('ecdsa', function () {
describe('deterministicGenerateK', function () {
function checkSig() { return true }
function checkSig () {
return true
}
fixtures.valid.ecdsa.forEach(function (f) {
it('for \"' + f.message + '\"', function() {
it('for "' + f.message + '"', function () {
var d = BigInteger.fromHex(f.d)
var h1 = crypto.sha256(f.message)
@ -29,7 +33,7 @@ describe('ecdsa', function() {
// FIXME: remove in 2.0.0
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 h1 = crypto.sha256(f.message)
@ -73,7 +77,7 @@ describe('ecdsa', function() {
}))
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 h1 = crypto.sha256(f.message)
@ -145,7 +149,7 @@ describe('ecdsa', function() {
describe('sign', function () {
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 hash = crypto.sha256(f.message)
var signature = ecdsa.sign(curve, hash, d)
@ -167,7 +171,7 @@ describe('ecdsa', function() {
describe('verify/verifyRaw', function () {
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 H = crypto.sha256(f.message)
var e = BigInteger.fromBuffer(H)

3
test/eckey.js

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

4
test/ecpubkey.js

@ -1,3 +1,5 @@
/* global describe, it, beforeEach */
var assert = require('assert')
var crypto = require('../src/crypto')
var networks = require('../src/networks')
@ -109,7 +111,7 @@ describe('ECPubKey', function() {
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')
assert(!pubKey.verify(hash, signature))

2
test/ecsignature.js

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

4
test/hdnode.js

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

4
test/integration/advanced.js

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert')
var bitcoin = require('../../')
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) {
this.timeout(20000)
var key = bitcoin.ECKey.fromWIF("L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy")
var key = bitcoin.ECKey.fromWIF('L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy')
var address = key.pub.getAddress(bitcoin.networks.testnet).toString()
blockchain.addresses.__faucetWithdraw(address, 2e4, function (err) {

8
test/integration/basic.js

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

15
test/integration/crypto.js

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert')
var async = require('async')
var bigi = require('bigi')
@ -41,7 +43,7 @@ describe('bitcoinjs-lib (crypto)', function() {
// TODO
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) {
assert(!master.privKey, 'You already have the parent 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 () {
var inputs = [
{
txId: "f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50",
txId: 'f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50',
vout: 0
},
{
txId: "f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50",
txId: 'f4c16475f2a6e9c602e4a287f9db3040e319eb9ece74761a4b84bc820fbeef50',
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
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
async.parallel(tasks, function (err) {
if (err) throw err
if (err)
throw err
var n = bitcoin.ECKey.curve.n
for (var i = 0; i < inputs.length; ++i) {

10
test/integration/multisig.js

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert')
var bitcoin = require('../../')
var blockchain = new (require('cb-helloblock'))('testnet')
@ -24,7 +26,9 @@ describe('bitcoinjs-lib (multisig)', function() {
'91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgwmaKkrx',
'91avARGdfge8E4tZfYLoxeJ5sGBdNJQH4kvjJoQFacbgww7vXtT'
].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 scriptPubKey = bitcoin.scripts.scriptHashOutput(redeemScript.getHash())
@ -39,7 +43,9 @@ describe('bitcoinjs-lib (multisig)', function() {
if (err) return done(err)
// 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
var unspent = unspents.pop()

6
test/message.js

@ -1,3 +1,5 @@
/* global describe, it */
var assert = require('assert')
var networks = require('../src/networks')
@ -11,7 +13,7 @@ var fixtures = require('./fixtures/message.json')
describe('Message', function () {
describe('magicHash', function () {
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 actual = Message.magicHash(f.message, network)
@ -30,7 +32,7 @@ describe('Message', function() {
})
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]
assert(Message.verify(f.address, f.signature, f.message, network))

4
test/network.js

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

9
test/script.js

@ -1,3 +1,6 @@
/* global describe, it */
/* eslint-disable no-new */
var assert = require('assert')
var opcodes = require('../src/opcodes')
@ -17,7 +20,9 @@ describe('Script', 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 () {
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)
assert.equal(script.getHash().toString('hex'), f.hash)

2
test/scripts.js

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

7
test/transaction.js

@ -1,3 +1,5 @@
/* global describe, it, beforeEach */
var assert = require('assert')
var scripts = require('../src/scripts')
@ -20,7 +22,6 @@ describe('Transaction', function() {
if (txIn.data) {
script = new Script(new Buffer(txIn.data, 'hex'), [])
} else if (txIn.script) {
script = Script.fromASM(txIn.script)
}
@ -225,7 +226,9 @@ describe('Transaction', function() {
].map(function (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 signatures = privKeys.map(function (privKey) {

24
test/transaction_builder.js

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

127
test/wallet.js

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

Loading…
Cancel
Save