Skip to content

Commit

Permalink
chore(decryptAddress): add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
leventdem committed Mar 18, 2024
1 parent 26248fb commit def870b
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
28 changes: 28 additions & 0 deletions src/sdk/decrypt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,32 @@ describe('decrypt', () => {
const cleartext = decryptAddress(keypair, ciphertext);
expect(cleartext).toBe(getAddress(value.toString(16)));
});

it('decrypts an address Uint8Array value bigger than 160 bits', async () => {
const keypair = sodium.crypto_box_keypair();
const address = '0x9b8a8ba1f109551bd432803012645ac136ddd64dba72'
// Must truncate to 40-digit
const expected = '0x8ba1f109551bd432803012645ac136ddd64dba72'
const value = BigInt(address);
const ciphertext = sodium.crypto_box_seal(
bigIntToBytes(value),
keypair.publicKey,
);
const cleartext = decryptAddress(keypair, ciphertext);
expect(cleartext).toBe(getAddress(expected));
});

it.only('decrypts an address Uint8Array value lower than 160 bits', async () => {
const keypair = sodium.crypto_box_keypair();
const address = '0x8ba1f109551bd432803012645ac136ddd64d'
// Must add padding until to 40-digit
const expected = '0x00008ba1f109551bd432803012645ac136ddd64d'
const value = BigInt(address);
const ciphertext = sodium.crypto_box_seal(
bigIntToBytes(value),
keypair.publicKey,
);
const cleartext = decryptAddress(keypair, ciphertext);
expect(cleartext).toBe(getAddress(expected));
});
});
2 changes: 1 addition & 1 deletion src/sdk/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ let hexString = bytesToHex(decrypted);
if (hexString.length > 40) {
hexString = hexString.substring(hexString.length - 40);
} else {
hexString = hexString.padStart(40, '0');
hexString = hexString.slice(2).padStart(40, '0');
}
return getAddress(hexString);
};
4 changes: 1 addition & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ export const bytesToHex = function (byteArray: Uint8Array): string {
return '0x0';
}
const buffer = Buffer.from(byteArray);
const result = '0x' + buffer.toString('hex');
return result;
return `0x${buffer.toString('hex')}`;
};

export const bytesToBigInt = function (byteArray: Uint8Array): bigint {
Expand All @@ -30,7 +29,6 @@ export const bytesToBigInt = function (byteArray: Uint8Array): bigint {

const buffer = Buffer.from(byteArray);
const result = toBigIntBE(buffer);

return result;
};

Expand Down

0 comments on commit def870b

Please sign in to comment.