diff --git a/src/address.js b/src/address.js index 354dda8..9a010dd 100644 --- a/src/address.js +++ b/src/address.js @@ -1,7 +1,6 @@ var base58 = require('./base58') var base58check = require('./base58check') var convert = require('./convert') -var error = require('./util').error var mainnet = require('./network').mainnet.addressVersion function Address(bytes, version) { @@ -25,7 +24,7 @@ function Address(bytes, version) { this.version = version || mainnet } else { - error('invalid or unrecognized input') + throw new Error('Invalid or unrecognized input') } } else { diff --git a/src/base58check.js b/src/base58check.js index ca95048..51c970e 100644 --- a/src/base58check.js +++ b/src/base58check.js @@ -1,14 +1,7 @@ // https://en.bitcoin.it/wiki/Base58Check_encoding var assert = require('assert') var base58 = require('./base58') -var crypto = require('crypto') - -function sha256(buf) { - var hash = crypto.createHash('sha256') - hash.update(buf) - - return hash.digest() -} +var crypto = require('./crypto') // Encode a buffer as a base58-check-encoded string function encode(buffer, version) { @@ -19,7 +12,7 @@ function encode(buffer, version) { var payload = new Buffer(buffer) var message = Buffer.concat([version, payload]) - var checksum = sha256(sha256(message)).slice(0, 4) + var checksum = crypto.hash256(message).slice(0, 4) return base58.encode(Buffer.concat([ message, @@ -33,7 +26,7 @@ function decode(string) { var message = buffer.slice(0, -4) var checksum = buffer.slice(-4) - var newChecksum = sha256(sha256(message)).slice(0, 4) + var newChecksum = crypto.hash256(message).slice(0, 4) assert.deepEqual(newChecksum, checksum) diff --git a/src/crypto.js b/src/crypto.js new file mode 100644 index 0000000..64d69e6 --- /dev/null +++ b/src/crypto.js @@ -0,0 +1,40 @@ +// Crypto, crypto, where art thou crypto +var CryptoJS = require('crypto-js') +var crypto = require('crypto') +var convert = require('./convert') + +function hash160(buffer) { + if (!Buffer.isBuffer(buffer)) buffer = new Buffer(buffer) // FIXME: transitionary + + var step1 = sha256(buffer) + + var step2a = convert.bytesToWordArray(step1) + var step2b = CryptoJS.RIPEMD160(step2a) + + return new Buffer(convert.wordArrayToBytes(step2b)) +} + +function hash256(buffer) { + if (!Buffer.isBuffer(buffer)) buffer = new Buffer(buffer) // FIXME: transitionary + + return sha256(sha256(buffer)) +} + +function sha1(buffer) { + if (!Buffer.isBuffer(buffer)) buffer = new Buffer(buffer) // FIXME: transitionary + + return crypto.createHash('sha1').update(buffer).digest() +} + +function sha256(buffer) { + if (!Buffer.isBuffer(buffer)) buffer = new Buffer(buffer) // FIXME: transitionary + + return crypto.createHash('sha256').update(buffer).digest() +} + +module.exports = { + sha1: sha1, + sha256: sha256, + hash160: hash160, + hash256: hash256 +} diff --git a/src/eckey.js b/src/eckey.js index 190e6de..c5a35bd 100644 --- a/src/eckey.js +++ b/src/eckey.js @@ -1,13 +1,13 @@ var Address = require('./address') var assert = require('assert') -var convert = require('./convert') var base58check = require('./base58check') var BigInteger = require('./jsbn/jsbn') +var convert = require('./convert') +var crypto = require('./crypto') var ecdsa = require('./ecdsa') var ECPointFp = require('./jsbn/ec').ECPointFp var sec = require('./jsbn/sec') var Network = require('./network') -var util = require('./util') var ecparams = sec("secp256k1") // input can be nothing, array of bytes, hex string, or base58 string @@ -175,7 +175,7 @@ ECPubKey.prototype.toString = ECPubKey.prototype.toHex ECPubKey.prototype.getAddress = function(version) { version = version || Network.mainnet.addressVersion - return new Address(util.sha256ripe160(this.toBytes()), version) + return new Address(crypto.hash160(this.toBytes()), version) } ECPubKey.prototype.verify = function(hash, sig) { diff --git a/src/hdwallet.js b/src/hdwallet.js index a6998b5..6276111 100644 --- a/src/hdwallet.js +++ b/src/hdwallet.js @@ -1,30 +1,25 @@ -var convert = require('./convert.js') -var base58 = require('./base58.js') +var Address = require('./address') var assert = require('assert') +var base58 = require('./base58') +var convert = require('./convert') +var CJS = require('crypto-js') +var crypto = require('./crypto') +var ECKey = require('./eckey').ECKey +var ECPubKey = require('./eckey').ECPubKey var format = require('util').format -var util = require('./util.js') -var Crypto = require('crypto-js') -var HmacSHA512 = Crypto.HmacSHA512 -var HMAC= Crypto.algo.HMAC -var ECKey = require('./eckey.js').ECKey -var ECPubKey = require('./eckey.js').ECPubKey -var Address = require('./address.js') var Network = require('./network') -var crypto = require('crypto') +function HmacSHA512(buffer, secret) { + var words = convert.bytesToWordArray(buffer) + var hash = CJS.HmacSHA512(words, secret) -function sha256(buf) { - var hash = crypto.createHash('sha256') - hash.update(buf) - - return hash.digest() + return convert.wordArrayToBytes(hash) } function HDWallet(seed, network) { if (seed === undefined) return; - var seedWords = convert.bytesToWordArray(seed) - var I = convert.wordArrayToBytes(HmacSHA512(seedWords, 'Bitcoin seed')) + var I = HmacSHA512(seed, 'Bitcoin seed') this.chaincode = I.slice(32) this.network = network || 'mainnet' if(!Network.hasOwnProperty(this.network)) { @@ -57,7 +52,7 @@ HDWallet.fromBase58 = function(string) { var payload = buffer.slice(0, -4) var checksum = buffer.slice(-4) - var newChecksum = sha256(sha256(payload)).slice(0, 4) + var newChecksum = crypto.hash256(payload).slice(0, 4) assert.deepEqual(newChecksum, checksum) assert.equal(payload.length, HDWallet.LENGTH) @@ -131,15 +126,15 @@ HDWallet.fromBytes = function(input) { } HDWallet.prototype.getIdentifier = function() { - return util.sha256ripe160(this.pub.toBytes()) + return crypto.hash160(this.pub.toBytes()) } HDWallet.prototype.getFingerprint = function() { - return this.getIdentifier().slice(0, 4) + return Array.prototype.slice.call(this.getIdentifier(), 0, 4) } HDWallet.prototype.getAddress = function() { - return new Address(util.sha256ripe160(this.pub.toBytes()), this.getKeyVersion()) + return new Address(crypto.hash160(this.pub.toBytes()), this.getKeyVersion()) } HDWallet.prototype.toBytes = function(priv) { @@ -192,7 +187,7 @@ HDWallet.prototype.toHex = function(priv) { HDWallet.prototype.toBase58 = function(priv) { var buffer = new Buffer(this.toBytes(priv)) - var checksum = sha256(sha256(buffer)).slice(0, 4) + var checksum = crypto.hash256(buffer).slice(0, 4) return base58.encode(Buffer.concat([ buffer, @@ -205,7 +200,7 @@ HDWallet.prototype.derive = function(i) { , iBytes = convert.numToBytes(i, 4).reverse() , cPar = this.chaincode , usePriv = i >= HDWallet.HIGHEST_BIT - , SHA512 = Crypto.algo.SHA512 + , SHA512 = CJS.algo.SHA512 if (usePriv) { assert(this.priv, 'Private derive on public key') @@ -259,7 +254,7 @@ HDWallet.prototype.getKeyVersion = function() { HDWallet.prototype.toString = HDWallet.prototype.toBase58 function HmacFromBytesToBytes(hasher, message, key) { - var hmac = HMAC.create(hasher, convert.bytesToWordArray(key)) + var hmac = CJS.algo.HMAC.create(hasher, convert.bytesToWordArray(key)) hmac.update(convert.bytesToWordArray(message)) return convert.wordArrayToBytes(hmac.finalize()) } diff --git a/src/index.js b/src/index.js index 52fd4f4..b98749e 100644 --- a/src/index.js +++ b/src/index.js @@ -3,6 +3,7 @@ var T = require('./transaction') module.exports = { Address: require('./address'), + crypto: require('./crypto'), Key: Key.ECKey, ECKey: Key.ECKey, ECPubKey: Key.ECPubKey, @@ -12,7 +13,6 @@ module.exports = { Script: require('./script'), Opcode: require('./opcode'), Transaction: T.Transaction, - Util: require('./util'), TransactionIn: T.TransactionIn, TransactionOut: T.TransactionOut, ECPointFp: require('./jsbn/ec').ECPointFp, diff --git a/src/message.js b/src/message.js index a9ed312..56eee48 100644 --- a/src/message.js +++ b/src/message.js @@ -2,9 +2,9 @@ var Address = require('./address') var convert = require('./convert') +var crypto = require('./crypto') var ecdsa = require('./ecdsa') var ECPubKey = require('./eckey').ECPubKey -var SHA256 = require('crypto-js/sha256') // FIXME: magicHash is incompatible with other magic messages var magicBytes = convert.stringToBytes('Bitcoin Signed Message:\n') @@ -19,7 +19,7 @@ function magicHash(message) { messageBytes ) - return convert.wordArrayToBytes(SHA256(SHA256(convert.bytesToWordArray(buffer)))) + return crypto.hash256(buffer) } // TODO: parameterize compression instead of using ECKey.compressed diff --git a/src/script.js b/src/script.js index 49d78fa..b8fba80 100644 --- a/src/script.js +++ b/src/script.js @@ -1,5 +1,5 @@ var Opcode = require('./opcode') -var util = require('./util') +var crypto = require('./crypto') var convert = require('./convert') var Address = require('./address') var network = require('./network') @@ -144,10 +144,10 @@ Script.prototype.toScriptHash = function() { } if (outType == 'P2SH') { - return util.sha256ripe160(this.buffer) + return crypto.hash160(this.buffer) } - return util.sha256ripe160(this.buffer) + return crypto.hash160(this.buffer) } //TODO: support testnet @@ -257,7 +257,7 @@ Script.prototype.simpleInPubKey = function() { * This method is useful for indexing transactions. */ Script.prototype.simpleInHash = function() { - return util.sha256ripe160(this.simpleInPubKey()) + return crypto.hash160(this.simpleInPubKey()) } /** diff --git a/src/transaction.js b/src/transaction.js index 55e9954..0f0bc3f 100644 --- a/src/transaction.js +++ b/src/transaction.js @@ -1,11 +1,12 @@ +// FIXME: To all ye that enter here, be weary of Buffers, Arrays and Hex interchanging between the outpoints + +var Address = require('./address') var BigInteger = require('./jsbn/jsbn') var Script = require('./script') -var util = require('./util') var convert = require('./convert') +var crypto = require('./crypto') var ECKey = require('./eckey').ECKey var ECDSA = require('./ecdsa') -var Address = require('./address') -var SHA256 = require('crypto-js/sha256') var Transaction = function (doc) { if (!(this instanceof Transaction)) { return new Transaction(doc) } @@ -201,11 +202,9 @@ Transaction.prototype.hashTransactionForSignature = } var buffer = txTmp.serialize() - buffer = buffer.concat(convert.numToBytes(parseInt(hashType), 4)) - buffer = convert.bytesToWordArray(buffer) - return convert.wordArrayToBytes(SHA256(SHA256(buffer))) + return crypto.hash256(buffer) } /** @@ -215,8 +214,10 @@ Transaction.prototype.hashTransactionForSignature = */ Transaction.prototype.getHash = function () { - var buffer = convert.bytesToWordArray(this.serialize()) - return convert.wordArrayToBytes(SHA256(SHA256(buffer))).reverse() + var buffer = this.serialize() + var hash = crypto.hash256(buffer) + + return Array.prototype.slice.call(hash, 0).reverse() } Transaction.prototype.clone = function () @@ -300,13 +301,12 @@ Transaction.prototype.sign = function(index, key, type) { type = type || SIGHASH_ALL key = new ECKey(key) - // TODO: getPub is slow, sha256ripe160 probably is too. - // This could be sped up a lot by providing these as inputs. - var pub = key.getPub().toBytes(), - hash160 = util.sha256ripe160(pub), - script = Script.createOutputScript(new Address(hash160)), - hash = this.hashTransactionForSignature(script, index, type), - sig = key.sign(hash).concat([type]) + var pub = key.getPub().toBytes() + var hash160 = crypto.hash160(pub) + var script = Script.createOutputScript(new Address(hash160)) + var hash = this.hashTransactionForSignature(script, index, type) + var sig = key.sign(hash).concat([type]) + this.ins[index].script = Script.createInputScript(sig, pub) } diff --git a/src/util.js b/src/util.js deleted file mode 100644 index 9cbc541..0000000 --- a/src/util.js +++ /dev/null @@ -1,13 +0,0 @@ -var convert = require('./convert.js') -var Crypto = require('crypto-js') -var RIPEMD160 = Crypto.RIPEMD160 -var SHA256 = Crypto.SHA256 - -exports.sha256ripe160 = function (data) { - var wordArray = RIPEMD160(SHA256(convert.bytesToWordArray(data))) - return convert.wordArrayToBytes(wordArray) -} - -exports.error = function (msg) { - throw new Error(msg) -} diff --git a/test/crypto.js b/test/crypto.js new file mode 100644 index 0000000..9b2068b --- /dev/null +++ b/test/crypto.js @@ -0,0 +1,49 @@ +var assert = require('assert') +var crypto = require('../').crypto +var fixture = require('./fixtures/crypto') + +describe('Crypto', function() { + describe('HASH160', function() { + it('matches the test vector', function() { + fixture.before.hex.forEach(function(hex, i) { + var actual = crypto.hash160(new Buffer(hex, 'hex')).toString('hex') + var expected = fixture.after.hash160[i] + + assert.equal(actual, expected) + }) + }) + }) + + describe('HASH256', function() { + it('matches the test vector', function() { + fixture.before.hex.forEach(function(hex, i) { + var actual = crypto.hash256(new Buffer(hex, 'hex')).toString('hex') + var expected = fixture.after.hash256[i] + + assert.equal(actual, expected) + }) + }) + }) + + describe('SHA1', function() { + it('matches the test vector', function() { + fixture.before.hex.forEach(function(hex, i) { + var actual = crypto.sha1(new Buffer(hex, 'hex')).toString('hex') + var expected = fixture.after.sha1[i] + + assert.equal(actual, expected) + }) + }) + }) + + describe('SHA256', function() { + it('matches the test vector', function() { + fixture.before.hex.forEach(function(hex, i) { + var actual = crypto.sha256(new Buffer(hex, 'hex')).toString('hex') + var expected = fixture.after.sha256[i] + + assert.equal(actual, expected) + }) + }) + }) +}) diff --git a/test/fixtures/crypto.js b/test/fixtures/crypto.js new file mode 100644 index 0000000..790fa9e --- /dev/null +++ b/test/fixtures/crypto.js @@ -0,0 +1,37 @@ +module.exports = { + before: { + hex: [ + '0000000000000001', + '0101010101010101', + 'FFFFFFFFFFFFFFFF', + '4c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e73656374657475722061646970697363696e6720656c69742e20446f6e65632061742066617563696275732073617069656e2c2076656c20666163696c6973697320617263752e20536564207574206d61737361206e6962682e205574206d6f6c6c69732070756c76696e6172206d617373612e20557420756c6c616d636f7270657220646f6c6f7220656e696d2c20696e206d6f6c657374696520656e696d20636f6e64696d656e74756d2061632e20416c697175616d206572617420766f6c75747061742e204e756c6c6120736f64616c657320617420647569206e656320' + ], + }, + + after: { + hash160: [ + 'cdb00698f02afd929ffabea308340fa99ac2afa8', + 'abaf1119f83e384210fe8e222eac76e2f0da39dc', + 'f86221f5a1fca059a865c0b7d374dfa9d5f3aeb4', + '9763e6b367c363bd6b88a7b361c98e6beee243a5' + ], + hash256: [ + '3ae5c198d17634e79059c2cd735491553d22c4e09d1d9fea3ecf214565df2284', + '728338d99f356175c4945ef5cccfa61b7b56143cbbf426ddd0e0fc7cfe8c3c23', + '752adad0a7b9ceca853768aebb6965eca126a62965f698a0c1bc43d83db632ad', + '033588797115feb3545052670cac2a46584ab3cb460de63756ee0275e66b5799' + ], + sha1: [ + 'cb473678976f425d6ec1339838f11011007ad27d', + 'c0357a32ed1f6a03be92dd094476f7f1a2e214ec', + 'be673e8a56eaa9d8c1d35064866701c11ef8e089', + '10d96fb43aca84e342206887bbeed3065d4e4344' + ], + sha256: [ + 'cd2662154e6d76b2b2b92e70c0cac3ccf534f9b74eb5b89819ec509083d00a50', + '04abc8821a06e5a30937967d11ad10221cb5ac3b5273e434f1284ee87129a061', + '12a3ae445661ce5dee78d0650d33362dec29c4f82af05e7e57fb595bbbacf0ca', + 'a7fb8276035057ed6479c5f2305a96da100ac43f0ac10f277e5ab8c5457429da' + ] + } +} diff --git a/test/misc.js b/test/misc.js index e02c924..121f479 100644 --- a/test/misc.js +++ b/test/misc.js @@ -1,17 +1,13 @@ var assert = require('assert') var bitcoinjs = require('../') +var crypto = require('../').crypto var sec = require('../src/jsbn/sec') var BigInteger = require('../src/jsbn/jsbn.js') -var SHA256 = require('crypto-js/sha256') var rng = require('secure-random') var ecparams = sec('secp256k1') var ECPointFp = bitcoinjs.ECPointFp var convert = require('../src/convert') -function sha256FromBytesToBytes(message){ - return convert.wordArrayToBytes(SHA256(convert.bytesToWordArray(message))) -} - it('Keys & Key Management', function () { var p1 = bitcoinjs.Key().getPub().toBytes() assert.equal(p1.length, 65) @@ -37,7 +33,7 @@ it('Signing and Verifying', function () { assert.ok(s1.verify(BigInteger.ZERO, sig_a)) var message = new BigInteger(1024, rng).toByteArrayUnsigned() - var hash = sha256FromBytesToBytes(message) + var hash = crypto.sha256(message) var sig_b = s1.sign(hash) assert.ok(sig_b, 'Sign random string') assert.ok(s1.verify(hash, sig_b)) @@ -49,7 +45,7 @@ it('Signing and Verifying', function () { '8a33f50d7cefb96a5dab897b5efcb99cbafb0d777cb83fc9b2115b69c0fa' + '3d82507b932b84e4') - var hash2 = sha256FromBytesToBytes(message2) + var hash2 = crypto.sha256(message2) var sig_c = bitcoinjs.convert.hexToBytes( '3044022038d9b8dd5c9fbf330565c1f51d72a59ba869aeb2c2001be959d3' + diff --git a/test/script.js b/test/script.js index b6ce5e9..6a611ac 100644 --- a/test/script.js +++ b/test/script.js @@ -2,8 +2,7 @@ var Script = require('../src/script.js') var assert = require('assert') var Address = require('../src/address.js') var Network = require('../src/network.js') -var Util = require('../src/util.js') -var sha256ripe160 = Util.sha256ripe160 +var crypto = require('../').crypto var Convert = require('../src/convert.js') var bytesToHex = Convert.bytesToHex var hexToBytes = Convert.hexToBytes @@ -83,7 +82,7 @@ describe('Script', function() { it('should create valid multi-sig address', function() { script = Script.createMultiSigOutputScript(numSigs, compressedPubKeys.map(hexToBytes)) - multisig = sha256ripe160(script.buffer) + multisig = crypto.hash160(script.buffer) var multiSigAddress = Address(multisig, network).toString() assert.ok(Address.validate(multiSigAddress)) @@ -107,7 +106,7 @@ describe('Script', function() { assert.equal(sigs[0], '02ea1297665dd733d444f31ec2581020004892cdaaf3dd6c0107c615afb839785f') assert.equal(sigs[1], '02fab2dea1458990793f56f42e4a47dbf35a12a351f26fa5d7e0cc7447eaafa21f') assert.equal(sigs[2], '036c6802ce7e8113723dd92cdb852e492ebb157a871ca532c3cb9ed08248ff0e19') - assert.equal(Address(sha256ripe160(redeemScript), network).toString(), '32vYjxBb7pHJJyXgNk8UoK3BdRDxBzny2v') + assert.equal(Address(crypto.hash160(redeemScript), network).toString(), '32vYjxBb7pHJJyXgNk8UoK3BdRDxBzny2v') }) }) }) diff --git a/test/wallet.js b/test/wallet.js index d69674e..a998286 100644 --- a/test/wallet.js +++ b/test/wallet.js @@ -7,8 +7,7 @@ var Script = require('../src/script.js') var convert = require('../src/convert.js') var assert = require('assert') var sinon = require('sinon') -var SHA256 = require('crypto-js/sha256') -var Crypto = require('crypto-js') +var crypto = require('../').crypto var fixtureTxes = require('./fixtures/mainnet_tx') var fixtureTx1Hex = fixtureTxes.prevTx @@ -17,7 +16,7 @@ var fixtureTx2Hex = fixtureTxes.tx describe('Wallet', function() { var seed, wallet beforeEach(function(){ - seed = convert.wordArrayToBytes(SHA256("don't use a string seed like this in real life")) + seed = crypto.sha256("don't use a string seed like this in real life") wallet = new Wallet(seed) })