Skip to content

Commit

Permalink
feat: Replace zk crypto with ed25519
Browse files Browse the repository at this point in the history
  • Loading branch information
rrr523 committed Mar 11, 2024
1 parent 8aea036 commit d47b646
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 294 deletions.
4 changes: 2 additions & 2 deletions examples/nextjs/src/components/bucket/create/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { client, selectSp } from '@/client';
import { getOffchainAuthKeys } from '@/utils/offchainAuth';
import { GRNToString, newBucketGRN, newGroupGRN } from '@bnb-chain/greenfield-js-sdk';
import { add } from 'lodash';
import { GRNToString, newBucketGRN } from '@bnb-chain/greenfield-js-sdk';
import { useState } from 'react';
import { useAccount } from 'wagmi';

Expand Down Expand Up @@ -34,6 +33,7 @@ export const CreateBucket = () => {

const provider = await connector?.getProvider();
const offChainData = await getOffchainAuthKeys(address, provider);
// console.log('offChainData', offChainData);
if (!offChainData) {
alert('No offchain, please create offchain pairs first');
return;
Expand Down
4 changes: 4 additions & 0 deletions examples/nextjs/src/components/deposit/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ export const Deposit = () => {
});

console.log(txHash);

if (txHash) {
alert('deposit success');
}
}}
>
deposit
Expand Down
1 change: 0 additions & 1 deletion packages/js-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@
},
"dependencies": {
"@bnb-chain/greenfield-cosmos-types": "0.4.0-alpha.30",
"@bnb-chain/greenfield-zk-crypto": "workspace:*",
"@cosmjs/proto-signing": "^0.32.0",
"@cosmjs/stargate": "^0.32.0",
"@cosmjs/tendermint-rpc": "^0.32.0",
Expand Down
18 changes: 4 additions & 14 deletions packages/js-sdk/src/api/objects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ import {
MsgUpdateObjectInfo,
} from '@bnb-chain/greenfield-cosmos-types/greenfield/storage/tx';
import { bytesFromBase64 } from '@bnb-chain/greenfield-cosmos-types/helpers';
import { hexlify } from '@ethersproject/bytes';
import { Headers } from 'cross-fetch';
import { bytesToUtf8, hexToBytes, utf8ToBytes } from 'ethereum-cryptography/utils';
import { bytesToUtf8, hexToBytes } from 'ethereum-cryptography/utils';
import { container, delay, inject, injectable } from 'tsyringe';
import {
GRNToString,
Expand All @@ -38,7 +37,7 @@ import {
newObjectGRN,
} from '..';
import { RpcQueryClient } from '../clients/queryclient';
import { encodePath, getMsgToSign, getSortQuery, secpSign } from '../clients/spclient/auth';
import { encodePath, getAuthorization, getSortQuery } from '../clients/spclient/auth';
import { getApprovalMetaInfo } from '../clients/spclient/spApis/approval';
import { getGetObjectMetaInfo } from '../clients/spclient/spApis/getObject';
import {
Expand All @@ -63,7 +62,6 @@ import { MsgCancelCreateObjectSDKTypeEIP712 } from '../messages/greenfield/stora
import { MsgCreateObjectSDKTypeEIP712 } from '../messages/greenfield/storage/MsgCreateObject';
import { MsgDeleteObjectSDKTypeEIP712 } from '../messages/greenfield/storage/MsgDeleteObject';
import { MsgUpdateObjectInfoSDKTypeEIP712 } from '../messages/greenfield/storage/MsgUpdateObjectInfo';
import { signSignatureByEddsa } from '../offchainauth';
import {
AuthType,
CreateObjectApprovalRequest,
Expand Down Expand Up @@ -484,17 +482,9 @@ export class Objects implements IObject {
'\n',
].join('\n');

const unsignedMsg = getMsgToSign(utf8ToBytes(canonicalRequest));
let authorization = '';
if (authType.type === 'ECDSA') {
const sig = secpSign(unsignedMsg, authType.privateKey);
authorization = `GNFD1-ECDSA, Signature=${sig.slice(2)}`;
} else {
const sig = await signSignatureByEddsa(authType.seed, hexlify(unsignedMsg).slice(2));
authorization = `GNFD1-EDDSA,Signature=${sig}`;
}
const auth = getAuthorization(canonicalRequest, authType);

return `${url}?Authorization=${encodeURIComponent(authorization)}&${queryRaw}`;
return `${url}?Authorization=${encodeURIComponent(auth)}&${queryRaw}`;
}

public async downloadFile(configParam: GetObjectRequest, authType: AuthType): Promise<void> {
Expand Down
46 changes: 8 additions & 38 deletions packages/js-sdk/src/api/offchainauth.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,14 @@
import { NORMAL_ERROR_CODE } from '../constants/http';
import {
fetchNonces,
genLocalSignMsg,
genSecondSignMsg,
getCurrentAccountPublicKey,
getCurrentSeedString,
personalSign,
updateSpsPubKey,
} from '../offchainauth';
import { hexlify } from '@ethersproject/bytes';
import { ed25519 } from '@noble/curves/ed25519';
import { injectable } from 'tsyringe';
import { convertTimeStampToDate, getUtcZeroTimestamp, SpResponse } from '..';
import { NORMAL_ERROR_CODE } from '../constants/http';
import { genSecondSignMsg, personalSign, updateSpsPubKey } from '../offchainauth';
import {
IGenOffChainAuthKeyPairAndUpload,
IReturnOffChainAuthKeyPairAndUpload,
ISp,
} from '../types/storage';

import { ed25519 } from '@noble/curves/ed25519';
import { toUtf8Bytes } from '@ethersproject/strings';

export interface IOffChainAuth {
/**
* generate off-chain auth key pair and upload the public key to meta service, return the seedString for signing message when user need to get approval from sp.
Expand All @@ -28,11 +17,6 @@ export interface IOffChainAuth {
params: IGenOffChainAuthKeyPairAndUpload,
provider: any,
): Promise<SpResponse<IReturnOffChainAuthKeyPairAndUpload>>;

signAndVerify(messageHash: Uint8Array): {
signature: Uint8Array;
verified: boolean;
};
}

@injectable()
Expand Down Expand Up @@ -85,9 +69,11 @@ export class OffChainAuth implements IOffChainAuth {
return {
code: 0,
body: {
seedString: hexlify(privateKey).slice(2),
privateKey: hexlify(privateKey).slice(2),
pubKey: hexlify(publicKey),
seedString: hexlify(privateKey),
keypars: {
privateKey: hexlify(privateKey),
publicKey: hexlify(publicKey),
},
expirationTime,
spAddresses: successSps,
failedSpAddresses: uploadSpsPubkeyFailed,
Expand All @@ -108,20 +94,4 @@ export class OffChainAuth implements IOffChainAuth {
publicKey,
};
}

public signAndVerify(messageHash: Uint8Array) {
const { privateKey, publicKey } = this.generateKeys();

const signature = ed25519.sign(messageHash, privateKey);
const verified = ed25519.verify(messageHash, signature, publicKey);

return {
verified,
signature,
};
}

testS() {
return toUtf8Bytes('Hello, world!');
}
}
18 changes: 10 additions & 8 deletions packages/js-sdk/src/clients/spclient/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { signSignatureByEddsa } from '@/offchainauth';
import { AuthType, ReqMeta } from '@/types/auth';
import { hexlify, joinSignature } from '@ethersproject/bytes';
import { SigningKey } from '@ethersproject/signing-key';
import { ed25519 } from '@noble/curves/ed25519';
import { Headers } from 'cross-fetch';
import { keccak256 } from 'ethereum-cryptography/keccak.js';
import { utf8ToBytes } from 'ethereum-cryptography/utils.js';
Expand Down Expand Up @@ -41,11 +41,7 @@ const getSignedHeaders = (reqHeaders: Headers) => {
return sortedHeaders.join(';');
};

export const getAuthorization = async (
reqMeta: Partial<ReqMeta>,
reqHeaders: Headers,
authType: AuthType,
) => {
export const getCanonicalRequest = (reqMeta: Partial<ReqMeta>, reqHeaders: Headers) => {
const canonicalHeaders = getCanonicalHeaders(reqMeta, reqHeaders);
const signedHeaders = getSignedHeaders(reqHeaders);
const canonicalRequestArr = [
Expand All @@ -57,6 +53,11 @@ export const getAuthorization = async (
];

const canonicalRequest = canonicalRequestArr.join('\n');

return canonicalRequest;
};

export const getAuthorization = (canonicalRequest: string, authType: AuthType) => {
// console.log('canonicalRequest', canonicalRequest);

const unsignedMsg = getMsgToSign(utf8ToBytes(canonicalRequest));
Expand All @@ -65,8 +66,8 @@ export const getAuthorization = async (
const sig = secpSign(unsignedMsg, authType.privateKey);
authorization = `GNFD1-ECDSA, Signature=${sig.slice(2)}`;
} else {
const sig = await signSignatureByEddsa(authType.seed, hexlify(unsignedMsg).slice(2));
authorization = `GNFD1-EDDSA,Signature=${sig}`;
const sig = hexlify(ed25519.sign(hexlify(unsignedMsg).slice(2), authType.seed.slice(2)));
authorization = `GNFD2-EDDSA,Signature=${sig.slice(2)}`;
}

return authorization;
Expand Down Expand Up @@ -131,6 +132,7 @@ export const HTTPHeaderContentMD5 = 'Content-MD5';
export const HTTPHeaderUnsignedMsg = 'X-Gnfd-Unsigned-Msg';
export const HTTPHeaderUserAddress = 'X-Gnfd-User-Address';
export const HTTPHeaderAppDomain = 'X-Gnfd-App-Domain';
export const HTTPHeaderRegPubKey = 'X-Gnfd-App-Reg-Public-Key';

const SUPPORTED_HEADERS = [
HTTPHeaderContentSHA256.toLocaleLowerCase(),
Expand Down
19 changes: 2 additions & 17 deletions packages/js-sdk/src/clients/spclient/sign.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,6 @@
import { hexlify, arrayify } from '@ethersproject/bytes';
import { arrayify, hexlify } from '@ethersproject/bytes';
import { toUtf8Bytes } from '@ethersproject/strings';
import { TGetCurrentSeedStringParams } from '../../types/storage';
import { getEddsaCompressedPublicKey, eddsaSign } from '@bnb-chain/greenfield-zk-crypto';

const getCurrentAccountPublicKey = async (seedString: string) => {
if ((window as any).getEddsaCompressedPublicKey) {
return (window as any).getEddsaCompressedPublicKey(seedString);
}
return await getEddsaCompressedPublicKey(seedString);
};

const signSignatureByEddsa = async (seedString: string, message: string) => {
if ((window as any).eddsaSign) {
return (window as any).eddsaSign(seedString, message);
}
return await eddsaSign(seedString, message);
};

const signMessagePersonalAPI = async (
provider: any,
Expand Down Expand Up @@ -59,4 +44,4 @@ const getCurrentSeedString = async ({
return seeds[seedKey].seed;
};

export { getCurrentAccountPublicKey, signSignatureByEddsa, getCurrentSeedString };
export { getCurrentSeedString };
12 changes: 10 additions & 2 deletions packages/js-sdk/src/clients/spclient/spClient.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {
getAuthorization,
getCanonicalRequest,
HTTPHeaderAppDomain,
HTTPHeaderAuthorization,
HTTPHeaderRegPubKey,
HTTPHeaderUserAddress,
newRequestHeadersByMeta,
} from '@/clients/spclient/auth';
Expand All @@ -12,6 +14,8 @@ import { fetchWithTimeout } from '@/utils/http';
import { injectable } from 'tsyringe';
import { getGetObjectMetaInfo } from './spApis/getObject';
import { getPutObjectMetaInfo } from './spApis/putObject';
import { ed25519 } from '@noble/curves/ed25519';
import { hexlify } from '@ethersproject/bytes';

export interface ISpClient {
callApi(
Expand Down Expand Up @@ -92,12 +96,16 @@ export class SpClient implements ISpClient {
const metaHeaders: Headers = newRequestHeadersByMeta(reqMeta);

if (authType.type === 'EDDSA') {
const { domain, address } = authType;
const { domain, address, seed } = authType;
const pubKey = hexlify(ed25519.getPublicKey(seed.slice(2)));

metaHeaders.set(HTTPHeaderUserAddress, address);
metaHeaders.set(HTTPHeaderAppDomain, domain);
metaHeaders.set(HTTPHeaderRegPubKey, pubKey.slice(2));
}

const auth = await getAuthorization(reqMeta, metaHeaders, authType);
const canonicalRequest = getCanonicalRequest(reqMeta, metaHeaders);
const auth = getAuthorization(canonicalRequest, authType);
metaHeaders.set(HTTPHeaderAuthorization, auth);

return metaHeaders;
Expand Down
9 changes: 7 additions & 2 deletions packages/js-sdk/src/types/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,14 @@ export interface IGenOffChainAuthKeyPairAndUpload extends IBaseUser {
}

export interface IReturnOffChainAuthKeyPairAndUpload {
/**
* compatibility: private key
*/
seedString: string;
privateKey: string;
pubKey: string;
keypars: {
privateKey: string;
publicKey: string;
};
expirationTime: number;
spAddresses: string[];
failedSpAddresses: string[];
Expand Down
Loading

0 comments on commit d47b646

Please sign in to comment.