Skip to content

Commit a5ed766

Browse files
cleanup
1 parent 6011100 commit a5ed766

File tree

4 files changed

+33
-27
lines changed

4 files changed

+33
-27
lines changed

src/helpers/common.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,17 @@ export function base64ToBytes(b64: string): Uint8Array {
5454
return bytes;
5555
}
5656

57+
/** Returns keccak256 hash as hex string (0x-prefixed). Use keccak256Bytes when you need bytes to avoid double conversion. */
5758
export function keccak256(a: Uint8Array): string {
5859
const hash = bytesToHex(keccakHash(a));
5960
return `0x${hash}`;
6061
}
6162

63+
/** Returns keccak256 hash as raw bytes. Use instead of hexToBytes(keccak256(...)) to avoid double conversion. */
64+
export function keccak256Bytes(a: Uint8Array): Uint8Array {
65+
return keccakHash(a);
66+
}
67+
6268
export const generatePrivateKey = (keyType: KeyType): Uint8Array => {
6369
if (keyType === KEY_TYPE.SECP256K1) {
6470
return secp256k1.utils.randomSecretKey();

src/helpers/keyUtils.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -60,21 +60,21 @@ function adjustScalarBytes(bytes: Uint8Array): Uint8Array {
6060
}
6161

6262
/** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
63-
export function getEd25519ExtendedPublicKey(keyBuffer: Uint8Array): {
63+
export function getEd25519ExtendedPublicKey(keyBytes: Uint8Array): {
6464
scalar: bigint;
6565
point: Point2D;
6666
} {
6767
const ed25519Curve = getKeyCurve(KEY_TYPE.ED25519);
6868
const len = 32;
6969
const N = ed25519Curve.Point.CURVE().n;
7070

71-
if (keyBuffer.length !== 32) {
72-
log.error("Invalid seed for ed25519 key derivation", keyBuffer.length);
71+
if (keyBytes.length !== 32) {
72+
log.error("Invalid seed for ed25519 key derivation", keyBytes.length);
7373
throw new Error("Invalid seed for ed25519 key derivation");
7474
}
7575
// Hash private key with curve's hash function to produce uniformingly random input
7676
// Check byte lengths: ensure(64, h(ensure(32, key)))
77-
const hashed = sha512(keyBuffer);
77+
const hashed = sha512(keyBytes);
7878
if (hashed.length !== 64) {
7979
throw new Error("Invalid hash length for ed25519 seed");
8080
}
@@ -122,11 +122,11 @@ export const generateEd25519KeyData = async (ed25519Seed: Uint8Array): Promise<P
122122
};
123123
};
124124

125-
export const generateSecp256k1KeyData = async (scalarBuffer: Uint8Array): Promise<PrivateKeyData> => {
125+
export const generateSecp256k1KeyData = async (scalarBytes: Uint8Array): Promise<PrivateKeyData> => {
126126
const secp256k1Curve = getKeyCurve(KEY_TYPE.SECP256K1);
127127
const N = secp256k1Curve.Point.CURVE().n;
128128

129-
const scalar = bytesToNumberBE(scalarBuffer);
129+
const scalar = bytesToNumberBE(scalarBytes);
130130
const randomNonce = bytesToNumberBE(generatePrivateKey(KEY_TYPE.SECP256K1));
131131
const oAuthKey = mod(scalar - randomNonce, N);
132132
const oAuthPub = secp256k1Curve.Point.BASE.multiply(oAuthKey).toAffine();
@@ -148,9 +148,9 @@ export const generateSecp256k1KeyData = async (scalarBuffer: Uint8Array): Promis
148148

149149
function generateAddressFromPoint(keyType: KeyType, point: Point2D): string {
150150
if (keyType === KEY_TYPE.SECP256K1) {
151-
const uncompressed = bytesToHex(getSecp256k1().Point.fromAffine(point).toBytes(false));
152-
const publicKey = uncompressed.slice(2); // remove 04 prefix
153-
const evmAddressLower = `0x${keccak256(hexToBytes(publicKey)).slice(64 - 38)}`;
151+
const uncompressed = getSecp256k1().Point.fromAffine(point).toBytes(false);
152+
const publicKey = uncompressed.slice(1); // remove 04 prefix
153+
const evmAddressLower = `0x${keccak256(publicKey).slice(64 - 38)}`;
154154
return toChecksumAddress(evmAddressLower);
155155
} else if (keyType === KEY_TYPE.ED25519) {
156156
const publicKey = encodeEd25519Point(point);

src/helpers/metadataUtils.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import {
2828
Curve,
2929
encParamsHexToBuf,
3030
hexToBytes,
31-
keccak256,
31+
keccak256Bytes,
3232
numberToBytesBE,
3333
toBigIntBE,
3434
utf8ToBytes,
@@ -62,21 +62,21 @@ export function convertMetadataToNonce(params: { message?: string }): bigint {
6262

6363
export async function decryptNodeData(eciesData: EciesHex, ciphertextHex: string, privKey: Uint8Array): Promise<Uint8Array> {
6464
const metadata = encParamsHexToBuf(eciesData);
65-
const decryptedSigBuffer = await decrypt(privKey, {
65+
const decryptedSigBytes = await decrypt(privKey, {
6666
...metadata,
6767
ciphertext: hexToBytes(ciphertextHex),
6868
});
69-
return decryptedSigBuffer;
69+
return decryptedSigBytes;
7070
}
7171

7272
export async function decryptNodeDataWithPadding(eciesData: EciesHex, ciphertextHex: string, privKey: Uint8Array): Promise<Uint8Array> {
7373
const metadata = encParamsHexToBuf(eciesData);
7474
try {
75-
const decryptedSigBuffer = await decrypt(privKey, {
75+
const decryptedSigBytes = await decrypt(privKey, {
7676
...metadata,
7777
ciphertext: hexToBytes(ciphertextHex),
7878
});
79-
return decryptedSigBuffer;
79+
return decryptedSigBytes;
8080
} catch (error) {
8181
// ciphertext can be any length. not just 64. depends on input. we have this for legacy reason
8282
const ciphertextHexPadding = ciphertextHex.padStart(64, "0");
@@ -92,7 +92,7 @@ export function generateMetadataParams(ecCurve: Curve, serverTimeOffset: number,
9292
data: message,
9393
timestamp: (~~(serverTimeOffset + Date.now() / 1000)).toString(16),
9494
};
95-
const msgHash = hexToBytes(keccak256(utf8ToBytes(stringify(setData))).slice(2));
95+
const msgHash = keccak256Bytes(utf8ToBytes(stringify(setData)));
9696
// metadata only uses secp for sig validation; prehash: false because msgHash is already hashed
9797
const sig = secp256k1.sign(msgHash, hexToBytes(bigintToHex(privateKey)), { prehash: false });
9898
const pubKey = ecCurve.Point.BASE.multiply(privateKey).toAffine();
@@ -145,7 +145,7 @@ export function generateNonceMetadataParams(
145145
setData.seed = ""; // setting it as empty to keep ordering same while serializing the data on backend.
146146
}
147147

148-
const msgHash = hexToBytes(keccak256(utf8ToBytes(stringify(setData))).slice(2));
148+
const msgHash = keccak256Bytes(utf8ToBytes(stringify(setData)));
149149
const sig = secp256k1.sign(msgHash, hexToBytes(bigintToHex(privateKey)), { prehash: false });
150150
const pubKey = secp256k1.Point.BASE.multiply(privateKey).toAffine();
151151
return {
@@ -256,7 +256,7 @@ export async function getOrSetSapphireMetadataNonce(
256256
operation: "getOrSetNonce",
257257
timestamp: (~~(serverTimeOffset + Date.now() / 1000)).toString(16),
258258
};
259-
const msgHash = hexToBytes(keccak256(utf8ToBytes(stringify(setData))).slice(2));
259+
const msgHash = keccak256Bytes(utf8ToBytes(stringify(setData)));
260260
const sig = secp256k1.sign(msgHash, hexToBytes(bigintToHex(privKey)), { prehash: false });
261261
const pubKey = secp256k1.Point.BASE.multiply(privKey).toAffine();
262262
data = {

src/torus.ts

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
getOrSetNonce,
1616
GetOrSetNonceError,
1717
GetPubKeyOrKeyAssign,
18+
hexToBytes,
1819
retrieveOrImportShare,
1920
toBigIntBE,
2021
} from "./helpers";
@@ -203,27 +204,26 @@ class Torus {
203204
extraParams.session_token_exp_second = Torus.sessionTime;
204205
}
205206

206-
let privKeyBuffer;
207+
let privKeyBytes: Uint8Array;
207208

208209
if (this.keyType === KEY_TYPE.SECP256K1) {
209-
privKeyBuffer = Buffer.from(newPrivateKey.padStart(64, "0"), "hex");
210-
if (privKeyBuffer.length !== 32) {
210+
privKeyBytes = hexToBytes(newPrivateKey.padStart(64, "0"));
211+
if (privKeyBytes.length !== 32) {
211212
throw new Error("Invalid private key length for given secp256k1 key");
212213
}
213-
}
214-
if (this.keyType === KEY_TYPE.ED25519) {
215-
privKeyBuffer = Buffer.from(newPrivateKey.padStart(64, "0"), "hex");
216-
if (privKeyBuffer.length !== 32) {
214+
} else {
215+
privKeyBytes = hexToBytes(newPrivateKey.padStart(64, "0"));
216+
if (privKeyBytes.length !== 32) {
217217
throw new Error("Invalid private key length for given ed25519 key");
218218
}
219219
}
220220

221-
const sharesData = await generateShares(this.ec, this.keyType, this.serverTimeOffset, nodeIndexes, nodePubkeys, privKeyBuffer);
221+
const sharesData = await generateShares(this.ec, this.keyType, this.serverTimeOffset, nodeIndexes, nodePubkeys, privKeyBytes);
222222
if (this.keyType === KEY_TYPE.ED25519) {
223-
const ed25519Key = getEd25519ExtendedPublicKey(privKeyBuffer);
223+
const ed25519Key = getEd25519ExtendedPublicKey(privKeyBytes);
224224
const ed25519PubKey = encodeEd25519Point(ed25519Key.point);
225225
const encodedPubKey = encodeEd25519Point(sharesData[0].final_user_point);
226-
const importedPubKey = Buffer.from(ed25519PubKey).toString("hex");
226+
const importedPubKey = bytesToHex(ed25519PubKey);
227227
const derivedPubKey = bytesToHex(encodedPubKey);
228228
if (importedPubKey !== derivedPubKey) {
229229
throw new Error("invalid shares data for ed25519 key, public key is not matching after generating shares");

0 commit comments

Comments
 (0)