Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: replace asmcrypto.js with native crypto module #6550

Draft
wants to merge 17 commits into
base: x
Choose a base branch
from
17 changes: 17 additions & 0 deletions @types/react-native-aes-crypto.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,21 @@ declare module '@metamask/react-native-aes-crypto' {
base64Key: string,
base64IV: string,
): Promise<string>;

// 添加 PBKDF2 密钥派生函数
export function pbkdf2(password: string, salt: string): Promise<string>;

// 添加 HMAC-SHA256 函数
export function hmac256(data: string, key: string): Promise<string>;

// 添加各种哈希函数
export function sha256(data: string): Promise<string>;
export function sha1(data: string): Promise<string>;
export function sha512(data: string): Promise<string>;

// 添加随机 UUID 生成函数
export function randomUuid(): Promise<string>;

// 添加随机密钥生成函数
export function randomKey(length: number): Promise<string>;
}
1 change: 1 addition & 0 deletions __mocks__/emptyMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {};
6 changes: 6 additions & 0 deletions apps/mobile/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,8 @@ PODS:
- React-Mapbuffer (0.73.7):
- glog
- React-debug
- react-native-aes (3.2.1):
- React-Core
- react-native-ble-manager (10.1.5):
- React-Core
- react-native-ble-plx (3.0.0):
Expand Down Expand Up @@ -1361,6 +1363,7 @@ DEPENDENCIES:
- React-jsinspector (from `../../../node_modules/react-native/ReactCommon/jsinspector-modern`)
- React-logger (from `../../../node_modules/react-native/ReactCommon/logger`)
- React-Mapbuffer (from `../../../node_modules/react-native/ReactCommon`)
- react-native-aes (from `../../../node_modules/react-native-aes-crypto`)
- react-native-ble-manager (from `../../../node_modules/react-native-ble-manager`)
- "react-native-ble-plx (from `../../../node_modules/@onekeyfe/react-native-ble-plx`)"
- react-native-cloud-fs (from `../../../node_modules/react-native-cloud-fs`)
Expand Down Expand Up @@ -1560,6 +1563,8 @@ EXTERNAL SOURCES:
:path: "../../../node_modules/react-native/ReactCommon/logger"
React-Mapbuffer:
:path: "../../../node_modules/react-native/ReactCommon"
react-native-aes:
:path: "../../../node_modules/react-native-aes-crypto"
react-native-ble-manager:
:path: "../../../node_modules/react-native-ble-manager"
react-native-ble-plx:
Expand Down Expand Up @@ -1749,6 +1754,7 @@ SPEC CHECKSUMS:
React-jsinspector: f356e49aa086380d3a4892708ca173ad31ac69c1
React-logger: 7b19bdfb254772a0332d6cd4d66eceb0678b6730
React-Mapbuffer: 401b164386595138c3ee5c2106ff117d54c3ba22
react-native-aes: 2f9ce51c4bd1e9fb5c50f5c867df05bcac10884b
react-native-ble-manager: 09724bad4d06b86a85e0cd7bd97196fecca15e9a
react-native-ble-plx: 4b0b605e4c52453ecbeb82807878bc4a2652d1c9
react-native-cloud-fs: 70c7cafe80186a6022da6741a76741e215633b6c
Expand Down
3 changes: 3 additions & 0 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"@formatjs/intl-getcanonicallocales": "^1.9.2",
"@formatjs/intl-locale": "^2.4.47",
"@formatjs/intl-pluralrules": "^4.3.3",
"@metamask/react-native-aes-crypto": "1.2.2",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove

"@notifee/react-native": "9.0.0",
"@onekeyfe/react-native-animated-charts": "1.0.0",
"@onekeyfe/react-native-ble-plx": "3.0.0",
Expand All @@ -54,6 +55,7 @@
"expo-barcode-scanner": "12.9.3",
"expo-blur": "12.9.1",
"expo-clipboard": "5.0.1",
"expo-crypto": "14.0.2",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove

"expo-device": "5.9.3",
"expo-haptics": "12.8.1",
"expo-image-manipulator": "11.5.0",
Expand All @@ -78,6 +80,7 @@
"path-browserify": "^1.0.1",
"react": "18.2.0",
"react-native": "0.73.7",
"react-native-aes-crypto": "3.2.1",
"react-native-ble-manager": "^10.0.2",
"react-native-camera-kit": "14.0.0-beta15",
"react-native-canvas": "^0.1.39",
Expand Down
3 changes: 3 additions & 0 deletions development/spellCheckerSkipWords.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ module.exports = [
'Eip1559',
'Boardloader',
'fs',
'ethersproject',
'hdk',
'cbc',
'dkey',
'impls',
'transpile',
'ttl',
'Cbc',
'Sollet',
Expand All @@ -29,6 +31,7 @@ module.exports = [
'txids',
'_j_msgid',
'ord',
'asmcrypto',
'exe',
'Merkle',
'cond',
Expand Down
1 change: 1 addition & 0 deletions development/webpack/webpack.base.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const baseResolve = ({ platform, configName }) => ({
symlinks: true,
alias: {
'react-native$': 'react-native-web',
'react-native-aes-crypto': false,
'react-native/Libraries/Components/View/ViewStylePropTypes$':
'react-native-web/dist/exports/View/ViewStylePropTypes',
'react-native/Libraries/EventEmitter/RCTDeviceEventEmitter$':
Expand Down
8 changes: 6 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,15 @@ module.exports = async () => {
'\\./adaWebSdk$':
'<rootDir>/packages/core/src/chains/ada/sdkAda/sdk/adaWebSdk.jest.ts',
'^lodash-es$': 'lodash',
// 'react-native-aes-crypto': '<rootDir>/__mocks__/emptyMock.js',
// 'react-native-reanimated': '<rootDir>/__mocks__/emptyMock.js',
},
// TODO unify with transpile modules
transformIgnorePatterns: ['nodo_modules/react-native-reanimated'],
transformIgnorePatterns: [
'node_modules/(?!(react-native-reanimated|react-native-aes-crypto)/)',
],
transform: {
'^.+\\.(ts|tsx)$': [
'^.+\\.(ts|tsx|js|jsx)$': [
'ts-jest',
{
'diagnostics': {
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"app:split-bundle": "yarn workspace @onekeyhq/mobile split-bundle",
"app:ios": "yarn workspace @onekeyhq/mobile ios",
"app:ios:device": "yarn workspace @onekeyhq/mobile ios:device",
"app:ios:pod-install": "cd apps/mobile/ios && pod install",
"app:android": "yarn workspace @onekeyhq/mobile android",
"app:android:device": "yarn workspace @onekeyhq/mobile android:device",
"icon:build": "yarn workspace @onekeyhq/components icon:build",
Expand Down Expand Up @@ -235,6 +236,7 @@
"resolutions": {
"expo-modules-core": "1.11.13",
"tronweb@^6.0.0": "6.0.0",
"protobufjs": "6.11.2",
"@babel/core": "7.23.5",
"@babel/code-frame": "7.23.5",
"@babel/generator": "7.23.5",
Expand Down
1 change: 0 additions & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
"@starcoin/starcoin": "^2.3.7",
"@zondax/izari-filecoin": "^1.2.0",
"algosdk": "^2.6.0",
"asmcrypto.js": "2.3.2",
"base32-decode": "^1.0.0",
"bchaddrjs": "^0.5.2",
"bip32": "^4.0.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/chains/btc/CoreChainSoftware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ export default class CoreChainSoftwareBtc extends CoreChainApiBase {
const index = pathComponent.endsWith("'")
? parseInt(pathComponent.slice(0, -1), 10) + 2 ** 31
: parseInt(pathComponent, 10);
const thisPrivKey = deriver.CKDPriv(parent, index);
const thisPrivKey = await deriver.CKDPriv(parent, index);
cache[currentPath] = thisPrivKey;
}
parent = cache[currentPath];
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/chains/btc/sdkBtc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ export async function getAddressFromXpub({
const index = part.endsWith("'")
? parseInt(part.slice(0, -1), 10) + 2 ** 31
: parseInt(part, 10);
extendedKey = CKDPub(curve, extendedKey, index);
extendedKey = await CKDPub(curve, extendedKey, index);
cache.set(relPath, extendedKey);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/chains/nexa/CoreChainSoftware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export default class CoreChainSoftware extends CoreChainApiBase {

const path = fullPath ? prefixPath : '';

const displayAddress = getDisplayAddress({
const displayAddress: string = await getDisplayAddress({
address,
chainId: networkInfo.chainId,
});
Expand Down
38 changes: 22 additions & 16 deletions packages/core/src/chains/nexa/sdkNexa/sdk/sign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ function getBN(buffer: Buffer, isLittleEndian = false) {
return new BN(hex, 16);
}

function nonceFunctionRFC6979(privkey: Buffer, msgbuf: Buffer): BN {
async function nonceFunctionRFC6979(
privkey: Buffer,
msgbuf: Buffer,
): Promise<BN> {
let V = Buffer.from(
'0101010101010101010101010101010101010101010101010101010101010101',
'hex',
Expand All @@ -43,27 +46,27 @@ function nonceFunctionRFC6979(privkey: Buffer, msgbuf: Buffer): BN {
Buffer.from('Schnorr+SHA256 ', 'ascii'),
]);

K = hmacSHA256(K, Buffer.concat([V, Buffer.from('00', 'hex'), blob]));
V = hmacSHA256(K, V);
K = await hmacSHA256(K, Buffer.concat([V, Buffer.from('00', 'hex'), blob]));
V = await hmacSHA256(K, V);

K = hmacSHA256(K, Buffer.concat([V, Buffer.from('01', 'hex'), blob]));
V = hmacSHA256(K, V);
K = await hmacSHA256(K, Buffer.concat([V, Buffer.from('01', 'hex'), blob]));
V = await hmacSHA256(K, V);

let k = new BN(0);
let T;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
const N = new BN(ec.curve.n.toArray());
// eslint-disable-next-line no-constant-condition
while (true) {
V = hmacSHA256(K, V);
V = await hmacSHA256(K, V);
T = getBN(V);

k = T;
if (k.gt(new BN(0)) && k.lt(N)) {
break;
}
K = hmacSHA256(K, Buffer.concat([V, Buffer.from('00', 'hex')]));
V = hmacSHA256(K, V);
K = await hmacSHA256(K, Buffer.concat([V, Buffer.from('00', 'hex')]));
V = await hmacSHA256(K, V);
}
return k;
}
Expand Down Expand Up @@ -105,12 +108,12 @@ function pointToCompressed(point: curve.base.BasePoint): Buffer {
return Buffer.concat([prefix, xbuf]);
}

function findSignature(d: BN, e: BN) {
async function findSignature(d: BN, e: BN) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion, @typescript-eslint/no-unsafe-member-access
const G: curve.base.BasePoint = ec.curve.g as curve.base.BasePoint;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call
const n: BN = new BN(ec.curve.n.toArray());
let k = nonceFunctionRFC6979(
let k = await nonceFunctionRFC6979(
getBufferFromBN(d, 'be', 32),
getBufferFromBN(e, 'be', 32),
);
Expand All @@ -123,7 +126,7 @@ function findSignature(d: BN, e: BN) {

const r = R.getX();
const e0 = getBN(
sha256(
await sha256(
Buffer.concat([
getrBuffer(r),
pointToCompressed(P),
Expand All @@ -139,21 +142,24 @@ function findSignature(d: BN, e: BN) {
};
}

export function sign(privateKey: Buffer, digest: Buffer): Buffer {
export async function sign(
privateKey: Buffer,
digest: Buffer,
): Promise<Buffer> {
const privateKeyBN = getBN(privateKey);
const digestBN = getBN(digest);
const { r, s } = findSignature(privateKeyBN, digestBN);
const { r, s } = await findSignature(privateKeyBN, digestBN);
return Buffer.concat([
getBufferFromBN(r, 'be', 32),
getBufferFromBN(s, 'be', 32),
]);
}

export function verify(
export async function verify(
publicKey: Buffer,
digest: Buffer,
signature: Buffer,
): boolean {
): Promise<boolean> {
if (signature.length !== 64) {
return false;
}
Expand Down Expand Up @@ -190,7 +196,7 @@ export function verify(
}
const Br = getrBuffer(r);
const Bp = pointToCompressed(P);
const hash = sha256(Buffer.concat([Br, Bp, hashbuf]));
const hash = await sha256(Buffer.concat([Br, Bp, hashbuf]));

// const e = BN.fromBuffer(hash, 'big').umod(n);
const e = new BN(hash, 'be').umod(n);
Expand Down
16 changes: 9 additions & 7 deletions packages/core/src/chains/nexa/sdkNexa/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,30 +258,32 @@ describe('Nexa Utils Tests', () => {
).toBe('nexatest:nqtsq5g5x3fqjd6kx8tf8l9rseg5rnrdupfwz9uhauzga026');
});

it('Nexa Utils Sgin Transaction', () => {
it('Nexa Utils Sgin Transaction', async () => {
const privateKey =
'91632aaa4de97d24c58ff234aa371c7a7c8363808a73fa9189cb5ee3d55a0cd3';
const digest =
'ae11c0c8f2576bd05fcde9d0d1f78f0fdaf679476d499c8cd366b81b476350fc';
expect(
sign(Buffer.from(privateKey, 'hex'), Buffer.from(digest, 'hex')).toString(
'hex',
),
(
await sign(Buffer.from(privateKey, 'hex'), Buffer.from(digest, 'hex'))
).toString('hex'),
).toBe(
'dbe0b176c8f425321302aa42d144544f3a7701d07d1666c0a90a642e0351b22a6e687b2c08030415c714843111bac0cfe6ba5e5aac4acb166caee9ae35e12dba',
);
});

it('Nexa Utils Sgin Transaction With signatureBuffer', () => {
it('Nexa Utils Sgin Transaction With signatureBuffer', async () => {
const privateKey =
'91632aaa4de97d24c58ff234aa371c7a7c8363808a73fa9189cb5ee3d55a0cd3';
const signatureBuffer =
'0094d3de9aa564a4fa760a6b16c76a0a15b724c38b39a7249215e397ed1bbf07d40084af2da0940d66153580ce18b185ac78ca4237d3ccaec3dfb32f4fd4134fb63bb13029ce7b1f559ef5e747fcac439f1455a2ec7c5f09b72290795e70665044026cad7049e07c205ae2c4f11bae23b1ead0de47bd52031fdc875e74b590e784c9228a0000000000';
const digest = sha256sha256(Buffer.from(signatureBuffer, 'hex'));
const digest = await sha256sha256(Buffer.from(signatureBuffer, 'hex'));
expect(digest.toString('hex')).toBe(
'fe1717e9f1d1315ab2a6048fcb51231f56a88512d1ed1ce552045bf7a9225b4d',
);
expect(sign(Buffer.from(privateKey, 'hex'), digest).toString('hex')).toBe(
expect(
(await sign(Buffer.from(privateKey, 'hex'), digest)).toString('hex'),
).toBe(
'7e5edff03500cec509bf55c4983560de8f794a88ae3539f7804cf2c34cad39d73ef115cf8d8cfa25ec841b38c123c19740a971a7de188319eaac5c4db897ce51',
);
});
Expand Down
Loading
Loading