import { AirGapWallet } from '@airgap/coinlib-core' ; import { UUID } from 'angular2-uuid' ; import { fromSeed } from 'bip32' ; import { toBoolean } from '../utils/utils' ; import { BIPSigner } from './BIP39Signer' ; import { Identifiable } from './identifiable' ; const signer = new BIPSigner ( ) ; export enum SecretType { MNEMONIC = 'mnemonic' } abstract class Secret implements Identifiable { public id : string = UUID . UUID ( ) ; public label : string ; public secretHex : string ; public isParanoia : boolean ; public type : SecretType ; public getIdentifier ( ) { return this . id ; } public flushSecret ( ) { delete this . secretHex ; } } export class MnemonicSecret extends Secret { public hasSocialRecovery : boolean ; public hasRecoveryKey : boolean ; public fingerprint ? : string ; public wallets : AirGapWallet [ ] ; private readonly twofactor : string ; constructor ( seed , label = '' , isParanoia = false , hasRecoveryKey = false ) { super ( ) ; this . label = label ; this . isParanoia = isParanoia ; this . hasRecoveryKey = hasRecoveryKey ; this . type = SecretType . MNEMONIC ; if ( seed !== null ) { this . secretHex = this . getEntropyFromMnemonic ( seed ) ; this . fingerprint = this . getFingerprintFromMnemonic ( seed ) ; } } public recoverMnemonicFromHex ( hex ) { return signer . entropyToMnemonic ( hex ) ; } public hasTwofactor ( ) { return toBoolean ( this . twofactor ) && this . twofactor . length > 0 ; } public static generateSocialRecover ( secret , numberOfShares , threshold ) { return signer . generateSocialRecover ( secret , numberOfShares , threshold ) ; } public static recoverSecretFromShares ( shares ) { return signer . recoverKey ( shares ) ; } public static init ( obj ) { return Object . assign ( new MnemonicSecret ( null , obj . label ) , obj ) ; } private getEntropyFromMnemonic ( mnemonic ) { return this . isMnemonic ( mnemonic ) ? signer . mnemonicToEntropy ( mnemonic ) : mnemonic ; } private getMnemonicFromEntropy ( entropy ) { return this . isMnemonic ( entropy ) ? entropy : signer . entropyToMnemonic ( entropy ) ; } private getFingerprintFromMnemonic ( entropy ) { const mnemonic = this . getMnemonicFromEntropy ( entropy ) ; const seed = signer . mnemonicToSeedSync ( mnemonic ) ; return fromSeed ( seed ) . fingerprint . toString ( 'hex' ) ; } private isMnemonic ( data ) { return data && data . indexOf ( ' ' ) > - 1 ; } }