From fc77e559202d0f10807f78c95efd1a43f2c3e7d9 Mon Sep 17 00:00:00 2001 From: Tyera Eulberg Date: Fri, 20 Dec 2019 16:14:37 -0700 Subject: [PATCH] fix: add PublicKey createWithSeed method --- web3.js/src/publickey.js | 10 +++++++++ web3.js/test/publickey.test.js | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/web3.js/src/publickey.js b/web3.js/src/publickey.js index c2fc63b434..3976661442 100644 --- a/web3.js/src/publickey.js +++ b/web3.js/src/publickey.js @@ -2,6 +2,7 @@ import BN from 'bn.js'; import bs58 from 'bs58'; +import hasha from 'hasha'; /** * A public key @@ -75,4 +76,13 @@ export class PublicKey { toString(): string { return this.toBase58(); } + + /** + * Derive a public key from another key, a seed, and a programId. + */ + static createWithSeed(fromPublicKey: PublicKey, seed: string, programId: PublicKey): PublicKey { + const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]) + const hash = hasha(buffer, {algorithm: 'sha256'}); + return new PublicKey('0x' + hash); + } } diff --git a/web3.js/test/publickey.test.js b/web3.js/test/publickey.test.js index d861573a5e..4cdc38ef30 100644 --- a/web3.js/test/publickey.test.js +++ b/web3.js/test/publickey.test.js @@ -223,3 +223,43 @@ test('equals (II)', () => { expect(key1.equals(key2)).toBe(true); }); + +test('createWithSeed', () => { + const defaultPublicKey = new PublicKey([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ]); + const derivedKey = PublicKey.createWithSeed(defaultPublicKey, 'limber chicken: 4/45', defaultPublicKey); + + expect(derivedKey.equals(new PublicKey('9h1HyLCW5dZnBVap8C5egQ9Z6pHyjsh5MNy83iPqqRuq'))).toBe(true); +});