Skip to content

Commit

Permalink
fix: crypto random generator polyfill (#3609)
Browse files Browse the repository at this point in the history
* fix: bip39 generate mnemonic strength to 256

* fix: web crypto polyfill

* fix: native crypto polyfill

* fix: lint

* fix: lint
  • Loading branch information
sidmorizon authored Oct 8, 2023
1 parent c5afc83 commit 01331e5
Show file tree
Hide file tree
Showing 13 changed files with 120 additions and 10 deletions.
4 changes: 3 additions & 1 deletion development/webpackTools.js
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,9 @@ function normalizeConfig({

config.resolve.fallback = {
...config.resolve.fallback,
'crypto': require.resolve('crypto-browserify'),
'crypto': require.resolve(
'@onekeyhq/shared/src/modules3rdParty/cross-crypto/index.js',
),
'stream': require.resolve('stream-browserify'),
'path': false,
'https': false,
Expand Down
4 changes: 3 additions & 1 deletion packages/app/metro.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ config.resolver.extraNodeModules = {
fs: require.resolve('react-native-level-fs'),
path: require.resolve('path-browserify'),
stream: require.resolve('readable-stream'),
crypto: require.resolve('react-native-crypto'),
'crypto': require.resolve(
'@onekeyhq/shared/src/modules3rdParty/cross-crypto/index.native.js',
),
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
net: require.resolve('react-native-tcp-socket'),
Expand Down
2 changes: 1 addition & 1 deletion packages/engine/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"bech32": "^2.0.0",
"bignumber.js": "^9.0.1",
"bip32": "^4.0.0",
"bip39": "^3.0.4",
"bip39": "^3.1.0",
"bitcoinforkjs": "git+https://github.com/OneKeyHQ/bitcoinjs-lib.git#feat/remove-npm-lock",
"bitcoinjs-message": "^2.2.0",
"bs58check": "^2.1.2",
Expand Down
4 changes: 2 additions & 2 deletions packages/engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ class Engine {

@backgroundMethod()
generateMnemonic(): Promise<string> {
return Promise.resolve(bip39.generateMnemonic());
return Promise.resolve(bip39.generateMnemonic(256));
}

@backgroundMethod()
Expand Down Expand Up @@ -372,7 +372,7 @@ class Engine {
await this.validator.validatePasswordStrength(password);

const [usedMnemonic] = await Promise.all([
this.validator.validateMnemonic(mnemonic || bip39.generateMnemonic()),
this.validator.validateMnemonic(mnemonic || bip39.generateMnemonic(256)),
this.validator.validateHDWalletNumber(),
]);

Expand Down
2 changes: 1 addition & 1 deletion packages/engine/src/secret/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ test('Basic mnemonic & seed tests', () => {
});

test('Mnemonic generation', () => {
const mnemonic = bip39.generateMnemonic();
const mnemonic = bip39.generateMnemonic(256);
const rs = revealableSeedFromMnemonic(mnemonic, password);
expect(
mnemonicFromEntropy(rs.entropyWithLangPrefixed, password),
Expand Down
4 changes: 3 additions & 1 deletion packages/ext/development/nextWebpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ function nextWebpack(
config.resolve = config.resolve || {};
config.resolve.fallback = {
...config.resolve.fallback,
'crypto': require.resolve('crypto-browserify'),
'crypto': require.resolve(
'@onekeyhq/shared/src/modules3rdParty/cross-crypto/index.js',
),
'stream': require.resolve('stream-browserify'),
'path': false,
'https': false,
Expand Down
2 changes: 2 additions & 0 deletions packages/kit-bg/src/BackgroundApi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable new-cap */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */

// eslint-disable-next-line import/order
import { Engine } from '@onekeyhq/engine';

import BackgroundApiBase from './BackgroundApiBase';
Expand Down
23 changes: 23 additions & 0 deletions packages/shared/src/modules3rdParty/cross-crypto/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
if (process.env.NODE_ENV !== 'production') {
const getRandomValuesOld = global.crypto.getRandomValues;
global.crypto.getRandomValues = function (...args) {
console.log('------------ call global.crypto.getRandomValues (web)');
return getRandomValuesOld.apply(global.crypto, args);
};
}

const crypto = require('crypto-browserify');

if (global.crypto) {
global.crypto.randomBytes = global.crypto.randomBytes || crypto.randomBytes;
crypto.getRandomValues =
crypto.getRandomValues || global.crypto.getRandomValues;
}
crypto.$$isOneKeyShim = true;
global.crypto.$$isOneKeyShim = true;

if (process.env.NODE_ENV !== 'production') {
console.log('crypto-browserify polyfilled', crypto, global.crypto);
}

module.exports = crypto;
37 changes: 37 additions & 0 deletions packages/shared/src/modules3rdParty/cross-crypto/index.native.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// react-native-crypto
// react-native-quick-crypto
// react-native-get-random-values
// react-native-randombytes (deprecated)

if (global.crypto && global.crypto.getRandomValues) {
delete global.crypto.getRandomValues;
}
// shim global.crypto.getRandomValues
require('react-native-get-random-values');

if (process.env.NODE_ENV !== 'production') {
const getRandomValuesOld = global.crypto.getRandomValues;
global.crypto.getRandomValues = function (...args) {
console.log('------------ call global.crypto.getRandomValues (native)');
return getRandomValuesOld.apply(global.crypto, args);
};
}

const crypto = require('react-native-crypto');

const { randomBytes } = require('@noble/hashes/utils');

// re-assign randomBytes from global.crypto.getRandomValues
crypto.randomBytes = randomBytes;
crypto.getRandomValues =
crypto.getRandomValues || global.crypto.getRandomValues;
global.crypto.randomBytes = global.crypto.randomBytes || crypto.randomBytes;

crypto.$$isOneKeyShim = true;
global.crypto.$$isOneKeyShim = true;

if (process.env.NODE_ENV !== 'production') {
console.log('react-native-crypto polyfilled', crypto, global.crypto);
}

module.exports = crypto;
28 changes: 28 additions & 0 deletions packages/shared/src/modules3rdParty/cross-crypto/verify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import assert from 'assert';
import * as crypto from 'crypto';

const globalCrypto = global.crypto;

// @ts-ignore
assert.ok(globalCrypto?.$$isOneKeyShim, 'global crypto is not polyfilled');
// @ts-ignore
assert.ok(crypto?.$$isOneKeyShim, 'crypto is not polyfilled');

assert.equal(
// eslint-disable-next-line @typescript-eslint/unbound-method
globalCrypto.getRandomValues,
// @ts-ignore
crypto.getRandomValues,
'getRandomValues is not matched',
);

assert.equal(
// @ts-ignore
globalCrypto.randomBytes,
crypto.randomBytes,
'randomBytes is not matched',
);

if (process.env.NODE_ENV !== 'production') {
console.log('cross-crypto verify success!');
}
5 changes: 4 additions & 1 deletion packages/shared/src/polyfills/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// eslint-disable-next-line import/order
/* eslint-disable import/order */
import './polyfillsPlatform';

// eslint-disable-next-line import/order
import '../modules3rdParty/cross-crypto/verify';

import { normalizeRequestLibs } from '../request/normalize';
import timerUtils from '../utils/timerUtils';

Expand Down
4 changes: 3 additions & 1 deletion packages/shared/src/utils/assertUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import assert from 'assert';

type ErrorType = undefined | string | Error;

const check = (statement: any, orError?: ErrorType) => {
Expand Down Expand Up @@ -25,4 +27,4 @@ const checkIsUndefined = (something: any, orError?: ErrorType) => {
);
};

export { check, checkIsDefined, checkIsUndefined };
export { assert, check, checkIsDefined, checkIsUndefined };
11 changes: 10 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6597,7 +6597,7 @@ __metadata:
bech32: ^2.0.0
bignumber.js: ^9.0.1
bip32: ^4.0.0
bip39: ^3.0.4
bip39: ^3.1.0
bitcoinforkjs: "git+https://github.com/OneKeyHQ/bitcoinjs-lib.git#feat/remove-npm-lock"
bitcoinjs-message: ^2.2.0
bs58check: ^2.1.2
Expand Down Expand Up @@ -13288,6 +13288,15 @@ __metadata:
languageName: node
linkType: hard

"bip39@npm:^3.1.0":
version: 3.1.0
resolution: "bip39@npm:3.1.0"
dependencies:
"@noble/hashes": ^1.2.0
checksum: 1224e763ffc6b097052ed8abd57f0e521ad6d31f1645be0d0a15f4417c13f8461f00e47e9cf7c8c784bd533f4fb1ee3ab020f258c7df45ee5dc722b4b0336cfc
languageName: node
linkType: hard

"bip66@npm:^1.1.0, bip66@npm:^1.1.5":
version: 1.1.5
resolution: "bip66@npm:1.1.5"
Expand Down

0 comments on commit 01331e5

Please sign in to comment.