feat: generate random keypair with constructor (#17448)

This commit is contained in:
Justin Starry 2021-05-24 21:04:05 -07:00 committed by GitHub
parent fda8cb176a
commit dbd7be5ff1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 7 deletions

View File

@ -1,5 +1,4 @@
import * as nacl from 'tweetnacl';
import type {SignKeyPair} from 'tweetnacl';
import {PublicKey} from './publickey';
@ -11,18 +10,33 @@ export interface Signer {
secretKey: Uint8Array;
}
/**
* Ed25519 Keypair
*/
export interface Ed25519Keypair {
publicKey: Uint8Array;
secretKey: Uint8Array;
}
/**
* An account keypair used for signing transactions.
*/
export class Keypair {
private _keypair: Ed25519Keypair;
/**
* @internal
*
* Create a new keypair instance from a {@link SignKeyPair}.
* Create a new keypair instance.
* Generate random keypair if no {@link Ed25519Keypair} is provided.
*
* @param keypair ed25519 keypair
*/
constructor(private keypair: SignKeyPair) {}
constructor(keypair?: Ed25519Keypair) {
if (keypair) {
this._keypair = keypair;
} else {
this._keypair = nacl.sign.keyPair();
}
}
/**
* Generate a new random keypair
@ -72,13 +86,13 @@ export class Keypair {
* The public key for this keypair
*/
get publicKey(): PublicKey {
return new PublicKey(this.keypair.publicKey);
return new PublicKey(this._keypair.publicKey);
}
/**
* The raw secret key for this keypair
*/
get secretKey(): Uint8Array {
return this.keypair.secretKey;
return this._keypair.secretKey;
}
}

View File

@ -4,6 +4,12 @@ import {Buffer} from 'buffer';
import {Keypair} from '../src';
describe('Keypair', () => {
it('new keypair', () => {
const keypair = new Keypair();
expect(keypair.secretKey).to.have.length(64);
expect(keypair.publicKey.toBytes()).to.have.length(32);
});
it('generate new keypair', () => {
const keypair = Keypair.generate();
expect(keypair.secretKey).to.have.length(64);