Skip to content

Commit

Permalink
Add address bytes length check in encodeAddress (#809)
Browse files Browse the repository at this point in the history
* Add address bytes length check in encodeAddress

* Fix example where address is invalid

* Add unit test for incorrect length encoding
  • Loading branch information
algochoi authored Aug 9, 2023
1 parent b09d616 commit 81ab6eb
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
6 changes: 2 additions & 4 deletions examples/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,8 @@ async function main() {

// decode b64 string key with Buffer
const globalKey = algosdk.base64ToString(globalState.key);
// decode b64 address value with encodeAddress and Buffer
const globalValue = algosdk.encodeAddress(
algosdk.base64ToBytes(globalState.value.bytes)
);
// show global value
const globalValue = globalState.value.bytes;

console.log(`Decoded global state - ${globalKey}: ${globalValue}`);

Expand Down
8 changes: 8 additions & 0 deletions src/encoding/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ export function isValidAddress(address: string) {
* @returns the address and checksum encoded as a string.
*/
export function encodeAddress(address: Uint8Array) {
// Check address length
if (
address.length !==
ALGORAND_ADDRESS_BYTE_LENGTH - ALGORAND_CHECKSUM_BYTE_LENGTH
)
throw new Error(
`${MALFORMED_ADDRESS_ERROR_MSG}: ${address}, length ${address.length}`
);
// compute checksum
const checksum = nacl
.genericHash(address)
Expand Down
10 changes: 10 additions & 0 deletions tests/3.Address.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ describe('address', () => {
assert.ok(algosdk.isValidAddress(addr));
});

it('should throw an error for addresses with incorrect length', () => {
const pk = nacl.randomBytes(15);
assert.throws(
() => {
algosdk.encodeAddress(pk);
},
(err) => err.message.includes(address.MALFORMED_ADDRESS_ERROR_MSG)
);
});

it('should be able to encode and decode an address', () => {
const pk = nacl.randomBytes(32);
const addr = algosdk.encodeAddress(pk);
Expand Down

0 comments on commit 81ab6eb

Please sign in to comment.