feat: generate random keypair with constructor (#17448)
This commit is contained in:
parent
fda8cb176a
commit
dbd7be5ff1
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
Loading…
Reference in New Issue