Skip to content

Commit

Permalink
fix: add PublicKey createWithSeed method
Browse files Browse the repository at this point in the history
  • Loading branch information
CriesofCarrots committed Jan 2, 2020
1 parent 277fa35 commit fd6a13e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/publickey.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import BN from 'bn.js';
import bs58 from 'bs58';
import hasha from 'hasha';

/**
* A public key
Expand Down Expand Up @@ -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);
}
}
40 changes: 40 additions & 0 deletions test/publickey.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit fd6a13e

Please sign in to comment.