Merge pull request #9 from 0xProject/generateSalt

Add generateSalt and tests for it
This commit is contained in:
Leonid 2017-05-25 11:48:21 +02:00 committed by GitHub
commit 334d2f175f
3 changed files with 30 additions and 0 deletions

View File

@ -36,6 +36,7 @@
"@types/mocha": "^2.2.41", "@types/mocha": "^2.2.41",
"@types/node": "^7.0.22", "@types/node": "^7.0.22",
"awesome-typescript-loader": "^3.1.3", "awesome-typescript-loader": "^3.1.3",
"bignumber.js": "^4.0.2",
"chai": "^3.5.0", "chai": "^3.5.0",
"mocha": "^3.4.1", "mocha": "^3.4.1",
"npm-run-all": "^4.0.2", "npm-run-all": "^4.0.2",
@ -53,6 +54,7 @@
"dependencies": { "dependencies": {
"bignumber.js": "^4.0.2", "bignumber.js": "^4.0.2",
"ethereumjs-util": "^5.1.1", "ethereumjs-util": "^5.1.1",
"lodash": "^4.17.4",
"web3": "^0.19.0" "web3": "^0.19.0"
} }
} }

View File

@ -11,6 +11,8 @@ export interface ECSignature {
s: string; s: string;
} }
const MAX_DIGITS_IN_UNSIGNED_256_INT = 78;
export class ZeroEx { export class ZeroEx {
/** /**
* Verifies that the elliptic curve signature `signature` was generated * Verifies that the elliptic curve signature `signature` was generated
@ -34,4 +36,17 @@ export class ZeroEx {
return false; return false;
} }
} }
/**
* Generates pseudo-random 256 bit salt.
* The salt is used to ensure that the 0x order generated has a unique orderHash that does
* not collide with any other outstanding orders.
*/
public static generatePseudoRandomSalt(): BigNumber.BigNumber {
// BigNumber.random returns a pseudo-random number between 0 & 1 with a passed in number of decimal places.
// Source: https://mikemcl.github.io/bignumber.js/#random
const randomNumber = BigNumber.random(MAX_DIGITS_IN_UNSIGNED_256_INT);
const factor = new BigNumber(10).pow(MAX_DIGITS_IN_UNSIGNED_256_INT - 1);
const salt = randomNumber.times(factor).round();
return salt;
}
} }

View File

@ -1,6 +1,7 @@
import {ZeroEx} from '../src/ts/0x.js'; import {ZeroEx} from '../src/ts/0x.js';
import {expect} from 'chai'; import {expect} from 'chai';
import 'mocha'; import 'mocha';
import * as BigNumber from 'bignumber.js';
describe('ZeroEx library', () => { describe('ZeroEx library', () => {
describe('#isValidSignature', () => { describe('#isValidSignature', () => {
@ -73,4 +74,16 @@ describe('ZeroEx library', () => {
expect(isValid).to.be.true; expect(isValid).to.be.true;
}); });
}); });
describe('#generateSalt', () => {
it('generates different salts', () => {
const equal = ZeroEx.generatePseudoRandomSalt().eq(ZeroEx.generatePseudoRandomSalt());
expect(equal).to.be.false;
});
it('generates salt in range [0..2^256)', () => {
const salt = ZeroEx.generatePseudoRandomSalt();
expect(salt.greaterThanOrEqualTo(0)).to.be.true;
const twoPow256 = new BigNumber(2).pow(256);
expect(salt.lessThan(twoPow256)).to.be.true;
});
});
}); });