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

298-feature-move-trustconnect-to-background #307

Merged
merged 7 commits into from
Dec 19, 2024
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ dist.7z
/playwright-report/
/blob-report/
/playwright/.cache/
dependency-usage.md
extension-dependencies.md
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@
"typescript.updateImportsOnFileMove.enabled": "always",
"eslint.useFlatConfig": true,
"githubPullRequests.overrideDefaultBranch": "dev",
"githubIssues.issueBranchTitle": "${issueNumber}-${sanitizedIssueTitle}"
"githubIssues.issueBranchTitle": "${issueNumber}-${sanitizedIssueTitle}",
"cSpell.words": ["Cbor", "secp"]
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"@sentry/browser": "^6.19.7",
"@sentry/react": "^6.19.7",
"@sentry/tracing": "^6.19.7",
"@trustwallet/wallet-core": "^4.1.19",
"@trustwallet/wallet-core": "^4.1.21",
"@tsparticles/engine": "^3.6.0",
"@tsparticles/react": "^3.0.0",
"@walletconnect/core": "^2.17.2",
Expand Down
2 changes: 1 addition & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 1 addition & 3 deletions src/background/controller/provider/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import RLP from 'rlp';
import Web3 from 'web3';
import { stringToHex } from 'web3-utils';

import { signWithKey } from '@/background/utils/modules/publicPrivateKey';
import { ensureEvmAddressPrefix, isValidEthereumAddress } from '@/shared/utils/address';
import {
permissionService,
Expand All @@ -22,9 +23,6 @@ import { storage } from '../../webapi';
import BaseController from '../base';
import Wallet from '../wallet';

// eslint-disable-next-line import/order,no-restricted-imports
import { signWithKey } from '@/ui/utils/modules/passkey.js';

interface Web3WalletPermission {
// The name of the method corresponding to the permission
parentCapability: string;
Expand Down
42 changes: 34 additions & 8 deletions src/background/controller/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,22 @@ import { getApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import web3, { TransactionError } from 'web3';

import {
findAddressWithNetwork,
findAddressWithSeed,
findAddressWithPK,
} from '@/background/utils/modules/findAddressWithPK';
import {
pk2PubKey,
seed2PubKey,
formPubKey,
jsonToKey,
} from '@/background/utils/modules/publicPrivateKey';
import eventBus from '@/eventBus';
import { type FeatureFlags } from '@/shared/types/feature-types';
import { type TrackingEvents } from '@/shared/types/tracking-types';
import { isValidEthereumAddress, withPrefix } from '@/shared/utils/address';
import { getHashAlgo, getSignAlgo } from '@/shared/utils/algo';
// eslint-disable-next-line no-restricted-imports
import { findAddressWithNetwork } from '@/ui/utils/modules/findAddressWithPK';
import {
keyringService,
preferenceService,
Expand Down Expand Up @@ -64,9 +73,6 @@ import { getStoragedAccount } from '../utils/getStoragedAccount';
import BaseController from './base';
import provider from './provider';

// eslint-disable-next-line import/order,no-restricted-imports
import { pk2PubKey, seed2PubKey, formPubKey } from '@/ui/utils/modules/passkey.js';

interface Keyring {
type: string;
getAccounts(): Promise<string[]>;
Expand Down Expand Up @@ -380,6 +386,16 @@ export class WalletController extends BaseController {
const { origin } = sessionService.getSession(tabId) || {};
return permissionService.getWithoutUpdate(origin);
};
addConnectedSite = (
origin: string,
name: string,
icon: string,
defaultChain = 747,
isSigned = false
) => {
permissionService.addConnectedSite(origin, name, icon, defaultChain, isSigned);
};

updateConnectSite = (origin: string, data: ConnectedSite) => {
permissionService.updateConnectSite(origin, data);
// sessionService.broadcastEvent(
Expand Down Expand Up @@ -512,6 +528,16 @@ export class WalletController extends BaseController {
return this._setCurrentAccountFromKeyring(keyring);
};

jsonToPrivateKeyHex = async (json: string, password: string): Promise<string | null> => {
const pk = await jsonToKey(json, password);
return pk ? Buffer.from(pk.data()).toString('hex') : null;
};
findAddressWithPrivateKey = async (pk: string, address: string) => {
return await findAddressWithPK(pk, address);
};
findAddressWithSeedPhrase = async (seed: string, address: string, isTemp: boolean = false) => {
return await findAddressWithSeed(seed, address, isTemp);
};
getPreMnemonics = () => keyringService.getPreMnemonics();
generatePreMnemonic = () => keyringService.generatePreMnemonic();
removePreMnemonics = () => keyringService.removePreMnemonics();
Expand Down Expand Up @@ -3840,12 +3866,12 @@ export class WalletController extends BaseController {
await googleDriveService.uploadMnemonicToGoogleDrive(mnemonic, username, user!.uid, password);
mixpanelTrack.track('multi_backup_created', {
address: (await this.getCurrentAddress()) || '',
providers: ['google_drive'],
providers: ['GoogleDrive'],
});
} catch {
mixpanelTrack.track('multi_backup_creation_failed', {
address: (await this.getCurrentAddress()) || '',
providers: ['google_drive'],
providers: ['GoogleDrive'],
});
}
};
Expand Down Expand Up @@ -4103,7 +4129,7 @@ export class WalletController extends BaseController {
trackAccountRecovered = async () => {
mixpanelTrack.track('account_recovered', {
address: (await this.getCurrentAddress()) || '',
mechanism: 'multi-backup',
mechanism: 'Multi-Backup',
methods: [],
});
};
Expand Down
4 changes: 2 additions & 2 deletions src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ async function restoreAppState() {

restoreAppState();

chrome.runtime.onInstalled.addListener(({ reason }) => {
chrome.runtime.onInstalled.addListener(({ reason }: chrome.runtime.InstalledDetails) => {
// chrome.runtime.OnInstalledReason.Install
if (reason === 'install') {
chrome.tabs.create({
Expand Down Expand Up @@ -179,7 +179,7 @@ chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
});

// for page provider
chrome.runtime.onConnect.addListener((port) => {
chrome.runtime.onConnect.addListener((port: chrome.runtime.Port) => {
// openapiService.getConfig();

// @ts-ignore
Expand Down
2 changes: 1 addition & 1 deletion src/background/service/flowns.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as secp from '@noble/secp256k1';
import * as fcl from '@onflow/fcl';

import { signMessageHash } from '@/ui/utils/modules/passkey.js';
import { signMessageHash } from '@/background/utils/modules/publicPrivateKey';
import wallet from 'background/controller/wallet';
import { keyringService, openapiService } from 'background/service';
import { createPersistStore } from 'background/utils';
Expand Down
6 changes: 2 additions & 4 deletions src/background/service/userWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,16 @@ import * as fcl from '@onflow/fcl';
import { getApp } from 'firebase/app';
import { getAuth, signInAnonymously } from 'firebase/auth';

import { signWithKey, seed2PubKey } from '@/background/utils/modules/publicPrivateKey';
import { type ActiveChildType } from '@/shared/types/wallet-types';
import { withPrefix } from '@/shared/utils/address';
import { getHashAlgo, getSignAlgo } from '@/shared/utils/algo';
// eslint-disable-next-line no-restricted-imports
import { findAddressWithSeed, findAddressWithPK } from '@/ui/utils/modules/findAddressWithPK';
// eslint-disable-next-line no-restricted-imports
import { signWithKey, seed2PubKey } from '@/ui/utils/modules/passkey.js';
import wallet from 'background/controller/wallet';
import { keyringService, mixpanelTrack, openapiService } from 'background/service';
import { createPersistStore } from 'background/utils';
import { getStoragedAccount } from 'background/utils/getStoragedAccount';

import { findAddressWithSeed, findAddressWithPK } from '../utils/modules/findAddressWithPK';
import { storage } from '../webapi';

import type {
Expand Down
2 changes: 1 addition & 1 deletion src/background/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import packageJson from '@/../package.json';
import { storage } from '@/background/webapi';

const { version } = packageJson;
import { mixpanelTrack } from '../service';
import { mixpanelTrack } from '../service/mixpanel';
import pageStateCache from '../service/pageStateCache';

export { default as createPersistStore } from './persisitStore';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable no-case-declarations */
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
const PositiveInteger = 0;
const NegativeInteger = 1;
Expand Down Expand Up @@ -64,26 +62,26 @@ class Header {
}

export class CborSimpleDecoder {
static readHeader(reader) {
static readHeader(reader: BinaryReader): Header {
if (!(reader instanceof BinaryReader)) throw new TypeError();
const h = reader.readUInt8();
const header = new Header(h);
if (header.information >= 0 && header.information <= 23) {
header.length = header.information;
} else if (header.information == 24) {
} else if (header.information === 24) {
header.length = reader.readUInt8();
} else if (header.information == 25) {
} else if (header.information === 25) {
header.length = reader.readUInt16();
} else if (header.information == 26) {
} else if (header.information === 26) {
header.length = reader.readUInt32();
} else if (header.information == 27) {
} else if (header.information === 27) {
header.length = reader.readUInt64();
} else {
throw new Error(`not implemented: major=${header.major} information=${header.information}`);
}
return header;
}
static readObject(reader) {
static readObject(reader: BinaryReader) {
if (!(reader instanceof BinaryReader)) throw new TypeError();
const header = CborSimpleDecoder.readHeader(reader);
switch (header.major) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
import { encodeArray } from './base64.js';
import { encodeArray } from './base64';

/**
* Convert Cose key to JWK
Expand Down Expand Up @@ -65,7 +63,7 @@ export function coseToJwk(data) {
* @returns {object} - WebCrypto algorithm
*/
export function getAlgorithm(jwk, alg) {
var algorithm;
let algorithm;
switch (jwk.kty) {
case 'EC':
algorithm = {
Expand All @@ -81,7 +79,7 @@ export function getAlgorithm(jwk, alg) {
default:
throw new Error('invalid argument: kty=' + jwk.kty);
}
var a = alg ?? jwk.alg ?? 'S256';
const a = alg ?? jwk.alg ?? 'S256';
switch (a) {
case 'RS512':
case 'ES512':
Expand Down Expand Up @@ -118,7 +116,7 @@ export function getAlgorithm(jwk, alg) {
* @returns {Promise<CryptoKey} - WebCrypto key
*/
export async function importJWK(jwk, alg) {
var key;
let key;
switch (jwk.kty) {
case 'EC':
key = {
Expand All @@ -138,7 +136,7 @@ export async function importJWK(jwk, alg) {
default:
throw new Error('invalid argument: kty=' + jwk.kty);
}
var algorithm = getAlgorithm(jwk, alg);
const algorithm = getAlgorithm(jwk, alg);
//console.log("importKey key: "+ encodeJson(key));
//console.log("importKey algorithm: "+ encodeJson(algorithm));
return await crypto.subtle.importKey('jwk', key, algorithm, false, ['verify']);
Expand All @@ -161,7 +159,7 @@ export async function sha256(data) {
* @returns {Uint8Array}
*/
export function getRandomBytes(length) {
var array = new Uint8Array(length ?? 32);
const array = new Uint8Array(length ?? 32);
crypto.getRandomValues(array);
return array;
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck
import { toArrayBuffer, BinaryReader } from './WebAuthnDecoder.js';
import { importJWK, sha256, getAlgorithm } from './Crypto.js';
import { importJWK, sha256, getAlgorithm } from './Crypto';
import { toArrayBuffer, BinaryReader } from './WebAuthnDecoder';

/**
* Decode assertion signature to WebCrypto format
Expand All @@ -18,18 +16,18 @@ export function decodeSignature(publicKey, signature) {
0x30|b1|0x02|b2|r|0x02|b3|s
b1 = Length of remaining data
b2 = Length of r
b3 = Length of s
b3 = Length of s
*/
if (reader.readUInt8() != 0x30) throw new Error('invalid argument');
if (reader.readUInt8() !== 0x30) throw new Error('invalid argument');
const b1 = reader.readUInt8();
if (reader.readUInt8() != 0x02) throw new Error('invalid argument');
if (reader.readUInt8() !== 0x02) throw new Error('invalid argument');
let b2 = reader.readUInt8();
if (b2 > 32) {
b2--;
reader.readUInt8();
}
const r = reader.readBytes(b2);
if (reader.readUInt8() != 0x02) throw new Error('invalid argument');
if (reader.readUInt8() !== 0x02) throw new Error('invalid argument');
let b3 = reader.readUInt8();
if (b3 > 32) {
b3--;
Expand Down
Loading
Loading