From 63bd1f3412b1e19059d98ff517f89253153bae5a Mon Sep 17 00:00:00 2001 From: CryptoSheik <93099369+0xCryptoSheik@users.noreply.github.com> Date: Mon, 13 Dec 2021 09:39:31 +0100 Subject: [PATCH] fix: translateAddress should not rely on PublicKey constructor nam Since anchor is used in web projects which will minify/mangle function names, checking an input object for a custom constructor name is unsafe. Moreover, checking the type of the input Address is unnecessary since `PublicKey`'s constructor handles: - `string` - `array` - object with a `{ _bn }` shape (like `PublicKey` itself) For additional safety, a unit test should be added to prevent `PublicKey` to stop supporting this unexpectedly. See `PublicKey` implementation: ``` /** * JSON object representation of PublicKey class */ export type PublicKeyData = { /** @internal */ _bn: BN; }; function isPublicKeyData(value: PublicKeyInitData): value is PublicKeyData { return (value as PublicKeyData)._bn !== undefined; } export class PublicKey extends Struct { /** @internal */ _bn: BN; /** * Create a new PublicKey object * @param value ed25519 public key as buffer or base-58 encoded string */ constructor(value: PublicKeyInitData) { super({}); if (isPublicKeyData(value)) { this._bn = value._bn; } else { if (typeof value === 'string') { // assume base 58 encoding by default const decoded = bs58.decode(value); if (decoded.length != 32) { throw new Error(`Invalid public key input`); } this._bn = new BN(decoded); } else { this._bn = new BN(value); } if (this._bn.byteLength() > 32) { throw new Error(`Invalid public key input`); } } } ``` --- ts/src/program/common.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/ts/src/program/common.ts b/ts/src/program/common.ts index 5fd24e1968..4990e3dab8 100644 --- a/ts/src/program/common.ts +++ b/ts/src/program/common.ts @@ -55,14 +55,7 @@ export function validateAccounts( // Translates an address to a Pubkey. export function translateAddress(address: Address): PublicKey { - if (typeof address === "string") { - const pk = new PublicKey(address); - return pk; - } else if (address.constructor.prototype.constructor.name === "PublicKey") { - return address; - } else { - throw new Error("Given address is not a PublicKey nor a string."); - } + return new PublicKey(address); } /**