Skip to content
This repository has been archived by the owner on Dec 11, 2019. It is now read-only.

Fix up random sampling with brave-crypto random samplers. #14851

Merged
merged 1 commit into from
Jul 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/common/lib/randomUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

module.exports.random = () => Math.random()
const crypto = require('brave-crypto')

module.exports.uniform = (n) => crypto.random.uniform(n)
4 changes: 3 additions & 1 deletion app/extensions/brave/content/scripts/adInsertion.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

const crypto = require('brave-crypto')

if (chrome.contentSettings.adInsertion == 'allow') {
/**
* Determines the ad size which should be shown
Expand Down Expand Up @@ -72,7 +74,7 @@ if (chrome.contentSettings.adInsertion == 'allow') {
// generate a random segment
// @todo - replace with renko targeting
var segments = ['IAB2', 'IAB17', 'IAB14', 'IAB21', 'IAB20']
var segment = segments[Math.floor(Math.random() * 4)]
var segment = segments[crypto.random.uniform(segments.length)]
var time_in_segment = new Date().getSeconds()
var segment_expiration_time = 0 // no expiration

Expand Down
6 changes: 3 additions & 3 deletions app/renderer/rendererTabEvents.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */

const Immutable = require('immutable')
const crypto = require('brave-crypto')
const electron = require('electron')

const windowStore = require('../../js/stores/windowStore')
Expand Down Expand Up @@ -535,9 +536,8 @@ function showWidevineNotification (tabId, frame, noWidevineCallback, widevineCal
return
}

// Generate a random string that is unlikely to collide. Not
// cryptographically random.
const nonce = Math.random().toString()
// Generate a random string that is unlikely to collide.
const nonce = crypto.uint8ToHex(crypto.getSeed(32))
const isWidevineEnabled = state.get('widevine') && state.getIn(['widevine', 'enabled'])
if (isWidevineEnabled) {
const message = locale.translation('allowWidevine').replace(/{{\s*origin\s*}}/, origin)
Expand Down
4 changes: 2 additions & 2 deletions js/about/newtab.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const backgrounds = require('../data/backgrounds')

// Utils
const urlutils = require('../lib/urlutil')
const {random} = require('../../app/common/lib/randomUtil')
const random = require('../../app/common/lib/randomUtil')
const cx = require('../lib/classSet')
const ipc = window.chrome.ipcRenderer

Expand Down Expand Up @@ -83,7 +83,7 @@ class NewTabPage extends React.Component {
}

get randomBackgroundImage () {
const image = Object.assign({}, backgrounds[Math.floor(random() * backgrounds.length)])
const image = Object.assign({}, backgrounds[random.uniform(backgrounds.length)])
return image
}

Expand Down
4 changes: 3 additions & 1 deletion js/about/preferences.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const {StyleSheet, css} = require('aphrodite/no-important')
const globalStyles = require('../../app/renderer/components/styles/global')
const commonStyles = require('../../app/renderer/components/styles/commonStyles')

const crypto = require('brave-crypto')

// Components
const PreferenceNavigation = require('../../app/renderer/components/preferences/preferenceNavigation')
const {SettingsList, SettingItem, SettingCheckbox, SettingItemIcon} = require('../../app/renderer/components/common/settings')
Expand Down Expand Up @@ -614,7 +616,7 @@ class AboutPreferences extends React.Component {
// refresh button is broken.
let newNumber
for (let i = 0; i < 10; ++i) {
newNumber = Math.random() * hintCount | 0
newNumber = crypto.random.uniform(hintCount)
if (!this.state || newNumber !== this.state.hintNumber) {
break
}
Expand Down
3 changes: 2 additions & 1 deletion test/about/bookmarksManagerTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ const {getTargetAboutUrl} = require('../../js/lib/appUrlUtil')
const siteTags = require('../../js/constants/siteTags')
const aboutBookmarksUrl = getTargetAboutUrl('about:bookmarks')
const Immutable = require('immutable')
const crypto = require('brave-crypto')

describe('about:bookmarks', function () {
const folderId = Math.floor(Math.random() * (100 - 1 + 1)) + 1
const folderId = 1 + crypto.random.uniform(100)
const browseableSiteUrl = 'page1.html'
const browseableSiteTitle = 'Page 1'

Expand Down
3 changes: 2 additions & 1 deletion test/lib/brave.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const series = require('async/series')
const path = require('path')
const fs = require('fs-extra')
const os = require('os')
const crypto = require('brave-crypto')
const {getTargetAboutUrl, isSourceAboutUrl, getBraveExtIndexHTML} = require('../../js/lib/appUrlUtil')

var chaiAsPromised = require('chai-as-promised')
Expand All @@ -26,7 +27,7 @@ const logVerbose = (string, ...rest) => {
}

const generateUserDataDir = () => {
return process.env.BRAVE_USER_DATA_DIR || path.join(os.tmpdir(), 'brave-test', (new Date().getTime()) + Math.floor(Math.random() * 1000).toString())
return process.env.BRAVE_USER_DATA_DIR || path.join(os.tmpdir(), 'brave-test', (new Date().getTime()) + crypto.random.uniform(1000).toString())
}

const rmDir = (dirPath) => {
Expand Down
5 changes: 3 additions & 2 deletions test/unit/about/newTabPageTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ const sinon = require('sinon')
const assert = require('assert')
const Immutable = require('immutable')
const fakeElectron = require('../lib/fakeElectron')
const crypto = require('brave-crypto')
const _ = require('underscore')
let NewTabPage, randomSpy, Clock, Stats, FooterInfo, NewPrivateTab
require('../braveUnit')

const randomWrapper = {
random: () => Math.random()
uniform: (n) => crypto.random.uniform(n)
}

describe('NewTab component unit tests', function () {
Expand All @@ -31,7 +32,7 @@ describe('NewTab component unit tests', function () {
mockery.registerMock('../../app/extensions/brave/img/newtab/private_tab_pagearea_icon.svg')
mockery.registerMock('../../app/extensions/brave/img/newtab/private_tab_pagearea_ddgicon.svg')
mockery.registerMock('../../app/extensions/brave/img/newtab/toricon.svg')
randomSpy = sinon.spy(randomWrapper, 'random')
randomSpy = sinon.spy(randomWrapper, 'uniform')
mockery.registerMock('../../app/common/lib/randomUtil', randomWrapper)
window.chrome = fakeElectron
window.CustomEvent = {}
Expand Down
10 changes: 6 additions & 4 deletions tools/lib/randomHostname.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const crypto = require('brave-crypto')

const ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
const _chooseRandomLetter = function () {
return ALPHABET[Math.round(Math.random() * (ALPHABET.length - 1))]
return ALPHABET[crypto.random.uniform(ALPHABET.length)]
}

const _generateRandomString = function (len) {
Expand All @@ -13,12 +15,12 @@ const generateRandomHostname = function (maxLength, minLength) {
maxLength = maxLength || 10
minLength = minLength || 4

let tld = TLDS[Math.round(Math.random() * (TLDS.length - 1))]
let tld = TLDS[crypto.random.uniform(TLDS.length)]

let numParts = Math.round(Math.random()) + 1
let numParts = 1 + crypto.random.uniform(2)

let host = (new Array(numParts)).fill(null).map(function () {
let partLen = Math.max(Math.round(Math.random() * maxLength), minLength)
let partLen = minLength + crypto.random.uniform(maxLength - minLength + 1)
return _generateRandomString(partLen)
}).join('.') + '.' + tld

Expand Down
11 changes: 7 additions & 4 deletions tools/lib/synopsisHelpers.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
const crypto = require('brave-crypto')
const randomHostname = require('./randomHostname')

const Synopsis = require('bat-publisher').Synopsis

const PROTOCOL_PREFIXES = ['http://', 'https://']

const generateSynopsisVisits = function (synopsis, numPublishers) {
let numHosts = numPublishers || Math.round(Math.random() * 100)
let numHosts = numPublishers || crypto.random.uniform(100)

let hosts = (new Array(numHosts)).fill(null).map(function () { return randomHostname() })

hosts.forEach(function (host) {
let numVisits = Math.round(Math.random() * 10)
let numVisits = crypto.random.uniform(10)

for (let i = 0; i < numVisits; i++) {
synopsis.addPublisher(PROTOCOL_PREFIXES[Math.round(Math.random())] + host + '/', {
duration: Math.round(Math.random() * 60 * 1000),
const nprefixes = PROTOCOL_PREFIXES.length
const prefix = PROTOCOL_PREFIXES[crypto.random.uniform(nprefixes)]
synopsis.addPublisher(prefix + host + '/', {
duration: crypto.random.uniform(60 * 1000),
revisitP: false
})
}
Expand Down
11 changes: 8 additions & 3 deletions tools/lib/transactionHelpers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
let Joi = require('joi')
const braveCrypto = require('brave-crypto')
let generateRandomHost = require('./randomHostname')
const BigNumber = require('bignumber.js')

Expand Down Expand Up @@ -44,7 +45,7 @@ const validateTransaction = function (tx) {
}

const generateTransaction = function () {
const count = Math.round(Math.random() * 100)
const count = braveCrypto.random.uniform(100)

const viewingId = generateViewingId()
const surveyorId = generateSurveyorId()
Expand Down Expand Up @@ -104,7 +105,8 @@ const generateSurveyorIds = function (count) {
}

const generateContribution = function () {
let randomContributionAmount = [5.0, 7.5, 10.0, 17.5, 25.0, 50.0, 75.0, 100.0][ Math.round(Math.random() * 3) ]
const amounts = [5.0, 7.5, 10.0, 17.5, 25.0, 50.0, 75.0, 100.0]
let randomContributionAmount = amounts[braveCrypto.random.uniform(amounts.length)]
const currency = 'BAT'

let rates = {
Expand Down Expand Up @@ -145,7 +147,10 @@ const generateBallots = function (votes) {
let votesRemaining = votes

while (votesRemaining) {
let votesToCast = Math.min(Math.round(Math.random() * votesRemaining) + 1, votesRemaining)
let votesToCast = 1
if (votesRemaining > 1) {
votesToCast += braveCrypto.random.uniform(votesRemaining - 1)
}
let host = generateRandomHost()
ballots[host] = votesToCast
votesRemaining -= votesToCast
Expand Down