Skip to content

Instantly share code, notes, and snippets.

@okovalov
Last active January 14, 2020 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okovalov/21ebc7f0fdf97e2e88cefa9a4b16f09c to your computer and use it in GitHub Desktop.
Save okovalov/21ebc7f0fdf97e2e88cefa9a4b16f09c to your computer and use it in GitHub Desktop.
an example of derriving keypairs with factories
interface CurrencyKey {
keyIndex: number;
privateKey: string;
publicKey: string;
address?: string;
getKeyIndex(): number;
getPrivateKey(): string;
getPublicKey(): string;
getAddress(): string;
}
abstract class CoinKey implements CurrencyKey {
keyIndex: number;
address: string;
privateKey: string;
publicKey: string;
constructor(keyIndex: number) {
this.keyIndex = keyIndex;
}
getKeyIndex(): number {
return this.keyIndex
}
getPrivateKey(): string {
return this.privateKey
}
getPublicKey(): string {
return this.publicKey
}
getAddress(): string {
return this.address
}
}
class BitCoinKey extends CoinKey {
constructor(masterSeed: string, keyIndex: number) {
super(keyIndex)
this.privateKey = `btc pri key ${masterSeed}`;
this.publicKey = `btc pub key ${masterSeed}`;
this.address = `btc address ${masterSeed}`;
}
}
class EthCoinKey extends CoinKey {
constructor(masterSeed: string, keyIndex: number) {
super(keyIndex)
this.privateKey = `btc pri key ${masterSeed}`;
this.publicKey = `btc pub key ${masterSeed}`;
this.address = `btc address ${masterSeed}`;
}
}
interface DerivedKeyPair {
keyIndex: number;
publicKey: string;
address: string;
}
interface IConstructor<T> {
new (...args: any[]): T;
// Or enforce default constructor
// new (): T;
}
// instead of using an IConstructor interface, we could use less readable inline initialization for t
// function keyPairFactory<T extends CurrencyKey>(masterSeed: string, keyIndex: number, type?: { new(): T ;}) {
function keyPairFactory<T extends CurrencyKey>(masterSeed: string, keyIndex: number, type?: IConstructor<T>) {
return new type(masterSeed, keyIndex);
}
function deriveNewKeyPair<T extends CurrencyKey>(masterSeed: string, keyIndex: number): DerivedKeyPair {
const key = keyPairFactory<T>(masterSeed, keyIndex)
return {
keyIndex: key.getKeyIndex(),
publicKey: key.getPublicKey(),
address: key.getAddress()
}
}
// derive keyPairs
const btcKeyPair = deriveNewKeyPair<BitCoinKey>('btcaddrts', 1)
const ethKeyPair = deriveNewKeyPair<EthCoinKey>('ethaddr', 1)
// use a factory to create a coin key
const key = keyPairFactory<BitCoinKey>('dssd', 1, BitCoinKey)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment