ECKey: adds tests for makeRandom

This commit is contained in:
Daniel Cousens 2014-06-23 18:22:01 +10:00
parent 0198477c6d
commit 89f0324cd7
3 changed files with 44 additions and 3 deletions

View file

@ -72,6 +72,6 @@
"bigi": "1.1.0", "bigi": "1.1.0",
"crypto-js": "3.1.2-3", "crypto-js": "3.1.2-3",
"ecurve": "0.10.0", "ecurve": "0.10.0",
"secure-random": "0.2.1" "secure-random": "1.0.0"
} }
} }

View file

@ -43,9 +43,11 @@ ECKey.fromWIF = function(string) {
} }
ECKey.makeRandom = function(compressed, rng) { 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) var d = BigInteger.fromBuffer(buffer)
d = d.mod(curve.n) d = d.mod(curve.n)

View file

@ -2,6 +2,9 @@ var assert = require('assert')
var crypto = require('../src/crypto') var crypto = require('../src/crypto')
var networks = require('../src/networks') var networks = require('../src/networks')
var secureRandom = require('secure-random')
var sinon = require('sinon')
var BigInteger = require('bigi') var BigInteger = require('bigi')
var ECKey = require('../src/eckey') 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() { describe('signing', function() {
var hash = crypto.sha256('Vires in numeris') var hash = crypto.sha256('Vires in numeris')
var priv = ECKey.makeRandom() var priv = ECKey.makeRandom()