import { IPrivateKey , IPrivateKeyExporter } from '../types' ; import { IKeyEntryStorage } from './KeyEntryStorage/IKeyEntryStorage' ; import { KeyEntryStorage } from './KeyEntryStorage/KeyEntryStorage' ; import { PrivateKeyExistsError } from './errors' ; /**
 * Interface of a single entry in  PrivateKeyStorage .
  export interface IPrivateKeyEntry { privateKey : IPrivateKey ; meta ? : { [ key ] : string ; } ; } /**
 * Class responsible for storage of private keys.
 */ export class PrivateKeyStorage { param { IPrivateKeyExporter } privateKeyExporter param { IKeyEntryStorage } keyEntryStorage constructor ( private privateKeyExporter , private keyEntryStorage = new KeyEntryStorage ( ) ) { } /**
     * Persists the given `privateKey` and `meta` under the given `name`.
     * If an entry with the same name already exists rejects the returned
     * Promise with  PrivateKeyExistsError error.
     *
     *  param { string } name param { IPrivateKey } privateKey param { Object < string , string > } meta returns { Promise < void > } async store ( name , privateKey , meta ? ) { const privateKeyData = this . privateKeyExporter . exportPrivateKey ( privateKey ) ; try { await this . keyEntryStorage . save ( { name , value : privateKeyData . toString ( 'base64' ) , meta } ) ; } catch ( error ) { if ( error && error . name === 'KeyEntryAlreadyExistsError' ) { throw new PrivateKeyExistsError ( `Private key with the name ${ name } already exists.` ) ; } throw error ; } } param { string } name returns { Promise < IPrivateKeyEntry | null > } async load ( name ) { const keyEntry = await this . keyEntryStorage . load ( name ) ; if ( keyEntry === null ) { return null ; } const privateKey = this . privateKeyExporter . importPrivateKey ( keyEntry . value ) ; return { privateKey , meta : keyEntry . meta } ; } param { string } name returns { Promise < void > } async delete ( name ) { await this . keyEntryStorage . remove ( name ) ; } }