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

Add scw support #1250

Closed
wants to merge 10 commits into from
Closed
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 packages/restapi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
}
},
"dependencies": {
"@lit-protocol/lit-node-client": "^5.1.0",
"@metamask/eth-sig-util": "^5.0.2",
"buffer": "^6.0.3",
"crypto-js": "^4.1.1",
Expand All @@ -22,6 +23,7 @@
"livepeer": "^2.5.8",
"lru-cache": "^10.1.0",
"openpgp": "^5.5.0",
"shamir-secret-sharing": "^0.0.3",
"simple-peer": "^9.11.1",
"socket.io-client": "^4.7.2",
"video-stream-merger": "^4.0.1",
Expand Down
2 changes: 2 additions & 0 deletions packages/restapi/src/lib/chat/helpers/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export const createUserService = async (options: CreateUserOptionsType) => {
const epoch = Math.floor(Date.now() / 1000);
if (user.split(':').length !== 6) {
user = `${user}:${epoch}`;
} else {
user = user.split(':').slice(0, -1).join(':') + `:${epoch}`;
}
}
const data = {
Expand Down
1 change: 1 addition & 0 deletions packages/restapi/src/lib/chat/helpers/signature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export const verifyProfileSignature = async (
return true;
} else return false;
} catch (err) {
// todo smart contract wallet with EIP191 sig validation
return false;
}
}
Expand Down
2 changes: 2 additions & 0 deletions packages/restapi/src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export enum ENCRYPTION_TYPE {
PGP_V2 = 'aes256GcmHkdfSha256',
PGP_V3 = 'eip191-aes256-gcm-hkdf-sha256',
NFTPGP_V1 = 'pgpv1:nft',
SCWPGP_V1 = 'pgpv1:scw',
}

/**
Expand Down Expand Up @@ -74,6 +75,7 @@ const Constants = {
ENC_TYPE_V2: 'aes256GcmHkdfSha256',
ENC_TYPE_V3: 'eip191-aes256-gcm-hkdf-sha256',
ENC_TYPE_V4: 'pgpv1:nft',
ENC_TYPE_V5: 'pgpv1:scw',
ALPHA_FEATURES,
};

Expand Down
16 changes: 11 additions & 5 deletions packages/restapi/src/lib/helpers/address.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as viem from 'viem';
import Constants, { ENV } from '../constants';
import { get } from '../user';
import { SignerType } from '../types';
import { Signer } from './signer';

export interface AddressValidatorsType {
[key: string]: ({ address }: { address: string }) => boolean;
Expand Down Expand Up @@ -102,8 +104,8 @@ export const isValidPushCAIP = (wallet: string): boolean => {
export const convertToValidDID = async (
wallet: string,
env: ENV = ENV.STAGING,
chainId?: number,
provider?: any
signer?: SignerType | null,
chainId?: number
) => {
/** @dev Why Not throw error? - Used by Group ChatID also */
if (!isValidPushCAIP(wallet)) return wallet;
Expand All @@ -121,10 +123,14 @@ export const convertToValidDID = async (
return `${wallet}:${epoch}`;
}

// TODO: Implement SCW DID CHECK
if (provider) {
if (signer) {
try {
const pushSigner = new Signer(signer);
const isSmartContract = await pushSigner.isSmartContract();
// check if onChain code exists
if (isSmartContract) {
return `scw:eip155:${await pushSigner.getChainId()}:${await pushSigner.getAddress()}`;
}
} catch (err) {
// Ignore if it fails
}
Expand Down Expand Up @@ -252,7 +258,7 @@ export const walletToPCAIP10 = (account: string): string => {
};

export const pCAIP10ToWallet = (wallet: string): string => {
if (isValidNFTCAIP(wallet)) return wallet;
if (isValidNFTCAIP(wallet) || isValidSCWCAIP(wallet)) return wallet;
wallet = wallet.replace('eip155:', '');
return wallet;
};
145 changes: 136 additions & 9 deletions packages/restapi/src/lib/helpers/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ import {
} from '@metamask/eth-sig-util';
import * as CryptoJS from 'crypto-js';
import {
aesDecrypt,
getAccountAddress,
getWallet,
pgpDecrypt,
verifySignature,
getEip712Signature,
getEip191Signature,
} from '../chat/helpers';
Expand All @@ -19,7 +16,6 @@ import {
walletType,
encryptedPrivateKeyType,
encryptedPrivateKeyTypeV2,
IMessageIPFS,
ProgressHookType,
ProgressHookTypeFunction,
} from '../types';
Expand All @@ -30,6 +26,8 @@ import PROGRESSHOOK from '../progressHook';
import { Signer } from './signer';
import * as viem from 'viem';
import { mainnet } from 'viem/chains';
import { combine, split } from 'shamir-secret-sharing';
import { Lit } from './lit';

const KDFSaltSize = 32; // bytes
const AESGCMNonceSize = 12; // property iv
Expand Down Expand Up @@ -83,7 +81,7 @@ export const encryptV1 = (
return encryptedSecret;
};

/** DEPRECATED */
/** @deprecated */
export const decryptWithWalletRPCMethod = async (
encryptedPGPPrivateKey: string,
account: string
Expand Down Expand Up @@ -238,12 +236,58 @@ export const decryptPGPKey = async (options: decryptPgpKeyProps) => {
privateKey = dec.decode(encodedPrivateKey);
break;
}
case Constants.ENC_TYPE_V5: {
const { shardInfo } = JSON.parse(
encryptedPGPPrivateKey
) as encryptedPrivateKeyType;

if (!shardInfo) {
throw new Error('Invalid Shard Info');
}

const pushShard = shardInfo.shards[0].shard;
const litEncryptedShard = shardInfo.shards[1].shard;

const LitInstance = await Lit.createInstance(
wallet.signer as SignerType,
wallet.account as string,
'sepolia',
env
);

const pushSigner = new Signer(wallet.signer as SignerType);
const chainId = await pushSigner.getChainId();

const litShard = await LitInstance.decrypt(
litEncryptedShard.ciphertext,
litEncryptedShard.dataToEncryptHash,
chainId
);

const secret = await combine([
hexToBytes(pushShard),
hexToBytes(litShard),
]);

const encodedPrivateKey = await decryptV2(
JSON.parse(encryptedPGPPrivateKey),
secret
);
const dec = new TextDecoder();
privateKey = dec.decode(encodedPrivateKey);
break;
}
default:
throw new Error('Invalid Encryption Type');
}

// try key upgradation
if (signer && toUpgrade && encryptionType !== Constants.ENC_TYPE_V4) {
if (
signer &&
toUpgrade &&
encryptionType !== Constants.ENC_TYPE_V4 &&
encryptionType !== Constants.ENC_TYPE_V5
) {
try {
await upgrade({ env, account: address, signer, progressHook });
} catch (err) {
Expand All @@ -259,13 +303,17 @@ export const decryptPGPKey = async (options: decryptPgpKeyProps) => {
progressHook?.(PROGRESSHOOK['PUSH-DECRYPT-02'] as ProgressHookType);
return privateKey;
} catch (err) {
// TODO: Remove Later
console.log(err);
// Report Progress
const errorProgressHook = PROGRESSHOOK[
'PUSH-ERROR-00'
] as ProgressHookTypeFunction;
progressHook?.(errorProgressHook(decryptPGPKey.name, err));
throw Error(
`[Push SDK] - API - Error - API ${decryptPGPKey.name} -: ${err}`
`[Push SDK] - API - Error - API ${decryptPGPKey.name} -: ${JSON.stringify(
err
)}`
);
}
};
Expand Down Expand Up @@ -380,7 +428,11 @@ export const encryptPGPKey = async (
NFTPGP_V1?: {
password: string;
};
}
SCWPGP_V1?: {
password: string;
};
},
env: ENV = ENV.STAGING
): Promise<encryptedPrivateKeyType> => {
let encryptedPrivateKey: encryptedPrivateKeyType;
switch (encryptionType) {
Expand Down Expand Up @@ -449,6 +501,80 @@ export const encryptPGPKey = async (
);
encryptedPrivateKey.version = Constants.ENC_TYPE_V4;
encryptedPrivateKey.preKey = '';
encryptedPrivateKey.encryptedPassword = await encryptPGPKey(
Constants.ENC_TYPE_V3,
additionalMeta.NFTPGP_V1.password,
wallet
);
break;
}
case Constants.ENC_TYPE_V5: {
if (!additionalMeta?.SCWPGP_V1?.password) {
throw new Error('Password is required!');
}
// 1. Generate secret to encrypt private key
const encryptionSecret = await getRandomValues(new Uint8Array(32));
// 2. Split secret into 3 shards ( Combining any 2 shards can decrypt the secret )
const PARTS = 3;
const QUORUM = 2;
const [shard1, shard2, shard3] = await split(
encryptionSecret,
PARTS,
QUORUM
);
// 3. Encrypt private key with secret
const enc = new TextEncoder();
const encodedPrivateKey = enc.encode(privateKey);
encryptedPrivateKey = await encryptV2(
encodedPrivateKey,
encryptionSecret
);

encryptedPrivateKey.version = encryptionType;

// 4. Store shard1 on Push nodes
const pushShard = bytesToHex(shard1);

// 5. Encrypt and store shard2 on lit nodes
const LitInstance = await Lit.createInstance(
wallet.signer as SignerType,
wallet.account as string,
'sepolia',
env
);

const pushSigner = new Signer(wallet.signer as SignerType);
const chainId = await pushSigner.getChainId();

const litEncryptedShard = await LitInstance.encrypt(
bytesToHex(shard2),
chainId
);

// 6. Encrypt and store shard3 on push nodes
const encodedShard3 = enc.encode(bytesToHex(shard3));
const pushEncryptedShard = await encryptV2(
encodedShard3,
hexToBytes(stringToHex(additionalMeta?.SCWPGP_V1?.password as string))
);

encryptedPrivateKey.shardInfo = {
shards: [
{
shard: pushShard,
encryptionType: 'NONE',
},
{
shard: litEncryptedShard,
encryptionType: 'LIT_SHARD_ENC_V1',
},
{
shard: pushEncryptedShard,
encryptionType: 'PUSH_SHARD_ENC_V1',
},
],
pattern: `${QUORUM}-${PARTS}`,
};
break;
}
default:
Expand All @@ -464,7 +590,8 @@ export const preparePGPPublicKey = async (
): Promise<string> => {
let chatPublicKey: string;
switch (encryptionType) {
case Constants.ENC_TYPE_V1: {
case Constants.ENC_TYPE_V1:
case Constants.ENC_TYPE_V5: {
chatPublicKey = publicKey;
break;
}
Expand Down
Loading
Loading