2018-09-30 18:42:45 -07:00
|
|
|
// @flow
|
|
|
|
|
|
|
|
import BN from 'bn.js';
|
|
|
|
import bs58 from 'bs58';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A public key
|
|
|
|
*/
|
|
|
|
export class PublicKey {
|
|
|
|
_bn: BN;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new PublicKey object
|
|
|
|
*/
|
|
|
|
constructor(number: string | Buffer | Array<number>) {
|
|
|
|
|
2018-09-30 21:27:55 -07:00
|
|
|
for (;;) {
|
|
|
|
if (typeof number === 'string') {
|
|
|
|
// base 58 encoded?
|
|
|
|
if (/^[1-9A-HJ-NP-Za-km-z]{43,44}$/.test(number)) {
|
|
|
|
this._bn = new BN(bs58.decode(number));
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
// hexadecimal number
|
|
|
|
if (number.startsWith('0x')) {
|
|
|
|
this._bn = new BN(number.substring(2), 16);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
this._bn = new BN(number);
|
|
|
|
break;
|
2018-09-30 18:42:45 -07:00
|
|
|
}
|
2018-09-30 21:27:55 -07:00
|
|
|
|
2018-09-30 18:42:45 -07:00
|
|
|
if (this._bn.byteLength() > 32) {
|
|
|
|
throw new Error(`Invalid public key input`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if the provided object is a PublicKey
|
|
|
|
*/
|
|
|
|
static isPublicKey(o: Object): boolean {
|
|
|
|
return o instanceof PublicKey;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if two publicKeys are equal
|
|
|
|
*/
|
|
|
|
equals(publicKey: PublicKey): boolean {
|
|
|
|
return this._bn.eq(publicKey._bn);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the base-58 representation of the public key
|
|
|
|
*/
|
|
|
|
toBase58(): string {
|
|
|
|
return bs58.encode(this.toBuffer());
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-09-30 22:02:31 -07:00
|
|
|
* Return the Buffer representation of the public key
|
2018-09-30 18:42:45 -07:00
|
|
|
*/
|
|
|
|
toBuffer(): Buffer {
|
2018-09-30 20:40:59 -07:00
|
|
|
const b = this._bn.toArrayLike(Buffer);
|
2018-09-30 18:42:45 -07:00
|
|
|
if (b.length === 32) {
|
|
|
|
return b;
|
|
|
|
}
|
|
|
|
|
|
|
|
const zeroPad = new Buffer(32);
|
2018-09-30 20:07:28 -07:00
|
|
|
b.copy(zeroPad);
|
2018-09-30 18:42:45 -07:00
|
|
|
return zeroPad;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns a string representation of the public key
|
|
|
|
*/
|
|
|
|
toString(): string {
|
|
|
|
return this.toBase58();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|