2020-06-04 07:38:21 +02:00
|
|
|
export class PubKey {
|
2020-06-05 08:56:47 +02:00
|
|
|
public static readonly PUBKEY_LEN = 66;
|
2020-06-12 06:03:50 +02:00
|
|
|
private static readonly regex: RegExp = new RegExp(
|
2020-06-30 10:04:17 +02:00
|
|
|
`^(05)?[0-9a-fA-F]{${PubKey.PUBKEY_LEN - 2}}$`
|
2020-06-12 06:03:50 +02:00
|
|
|
);
|
2020-06-04 07:38:21 +02:00
|
|
|
public readonly key: string;
|
|
|
|
|
2020-06-24 05:03:38 +02:00
|
|
|
/**
|
|
|
|
* A PubKey object.
|
|
|
|
* If `pubKeyString` is not valid then this will throw an `Error`.
|
|
|
|
*
|
|
|
|
* @param pubkeyString The public key string.
|
|
|
|
*/
|
2020-06-04 08:11:50 +02:00
|
|
|
constructor(pubkeyString: string) {
|
2020-06-24 05:03:38 +02:00
|
|
|
if (!PubKey.validate(pubkeyString)) {
|
|
|
|
throw new Error(`Invalid pubkey string passed: ${pubkeyString}`);
|
|
|
|
}
|
2020-06-25 04:13:53 +02:00
|
|
|
this.key = pubkeyString.toLowerCase();
|
2020-06-04 07:38:21 +02:00
|
|
|
}
|
|
|
|
|
2020-06-24 05:03:38 +02:00
|
|
|
/**
|
|
|
|
* Cast a `value` to a `PubKey`.
|
|
|
|
* If `value` is not valid then this will throw.
|
|
|
|
*
|
|
|
|
* @param value The value to cast.
|
|
|
|
*/
|
|
|
|
public static cast(value: string | PubKey): PubKey {
|
|
|
|
return typeof value === 'string' ? new PubKey(value) : value;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Try convert `pubKeyString` to `PubKey`.
|
|
|
|
*
|
|
|
|
* @param pubkeyString The public key string.
|
|
|
|
* @returns `PubKey` if valid otherwise returns `undefined`.
|
|
|
|
*/
|
2020-06-04 07:38:21 +02:00
|
|
|
public static from(pubkeyString: string): PubKey | undefined {
|
|
|
|
// Returns a new instance if the pubkey is valid
|
|
|
|
if (PubKey.validate(pubkeyString)) {
|
|
|
|
return new PubKey(pubkeyString);
|
|
|
|
}
|
|
|
|
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static validate(pubkeyString: string): boolean {
|
2020-06-12 03:40:29 +02:00
|
|
|
if (this.regex.test(pubkeyString)) {
|
2020-06-04 07:38:21 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
2020-06-15 01:31:56 +02:00
|
|
|
|
2020-06-18 02:27:08 +02:00
|
|
|
public isEqual(comparator: PubKey | string) {
|
|
|
|
return comparator instanceof PubKey
|
|
|
|
? this.key === comparator.key
|
2020-06-25 04:13:53 +02:00
|
|
|
: this.key === comparator.toLowerCase();
|
2020-06-15 01:31:56 +02:00
|
|
|
}
|
2020-06-04 07:38:21 +02:00
|
|
|
}
|
2020-06-12 05:53:54 +02:00
|
|
|
|
|
|
|
export class PrimaryPubKey extends PubKey {}
|
|
|
|
export class SecondaryPubKey extends PubKey {}
|