From 89f0324cd77c1dff92a14fd0a61ef852c9ec6f53 Mon Sep 17 00:00:00 2001 From: Daniel Cousens Date: Mon, 23 Jun 2014 18:22:01 +1000 Subject: [PATCH] ECKey: adds tests for makeRandom --- package.json | 2 +- src/eckey.js | 6 ++++-- test/eckey.js | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 5e38867..09932d6 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,6 @@ "bigi": "1.1.0", "crypto-js": "3.1.2-3", "ecurve": "0.10.0", - "secure-random": "0.2.1" + "secure-random": "1.0.0" } } diff --git a/src/eckey.js b/src/eckey.js index c0a6a77..424e1ff 100644 --- a/src/eckey.js +++ b/src/eckey.js @@ -43,9 +43,11 @@ ECKey.fromWIF = function(string) { } ECKey.makeRandom = function(compressed, rng) { - rng = rng || secureRandom + rng = rng || secureRandom.randomBuffer + + var buffer = rng(32) + assert(Buffer.isBuffer(buffer), 'Expected Buffer, got ' + buffer) - var buffer = new Buffer(rng(32)) var d = BigInteger.fromBuffer(buffer) d = d.mod(curve.n) diff --git a/test/eckey.js b/test/eckey.js index bfd0616..7694a1b 100644 --- a/test/eckey.js +++ b/test/eckey.js @@ -2,6 +2,9 @@ var assert = require('assert') var crypto = require('../src/crypto') var networks = require('../src/networks') +var secureRandom = require('secure-random') +var sinon = require('sinon') + var BigInteger = require('bigi') var ECKey = require('../src/eckey') @@ -76,6 +79,42 @@ describe('ECKey', function() { }) }) + describe('makeRandom', function() { + var exWIF = 'KwMWvwRJeFqxYyhZgNwYuYjbQENDAPAudQx5VEmKJrUZcq6aL2pv' + var exPrivKey = ECKey.fromWIF(exWIF) + var exBuffer = exPrivKey.d.toBuffer(32) + + describe('using default RNG', function() { + beforeEach(function() { + sinon.stub(secureRandom, 'randomBuffer').returns(exBuffer) + }) + + afterEach(function() { + secureRandom.randomBuffer.restore() + }) + + it('generates a ECKey', function() { + var privKey = ECKey.makeRandom() + + assert.equal(privKey.toWIF(), exWIF) + }) + + it('supports compression', function() { + assert.equal(ECKey.makeRandom(true).pub.compressed, true) + assert.equal(ECKey.makeRandom(false).pub.compressed, false) + }) + }) + + it('allows a custom RNG to be used', function() { + function rng(size) { + return exBuffer.slice(0, size) + } + + var privKey = ECKey.makeRandom(undefined, rng) + assert.equal(privKey.toWIF(), exWIF) + }) + }) + describe('signing', function() { var hash = crypto.sha256('Vires in numeris') var priv = ECKey.makeRandom()