import { createKeypairFromPeerId , ENR , ENRKey , ENRValue } from "@chainsafe/discv5" ; import { writeFile , readFile } from "../util" ; import PeerId from "peer-id" ; /**
 * `FileENR` is an `ENR` that saves the ENR contents to a file on every modification
 */ export class FileENR extends ENR { private filename : string ; private localPeerId : PeerId ; constructor ( filename , peerId , kvs , seq , signature ) { super ( kvs , seq , signature ) ; Object . setPrototypeOf ( this , FileENR . prototype ) ; this . filename = filename ; this . localPeerId = peerId ; return this ; } static initFromFile ( filename , peerId ) { const enr = FileENR . decodeTxt ( readFile ( filename ) ) as FileENR ; return this . initFromENR ( filename , peerId , enr ) ; } static initFromENR ( filename , peerId , enr ) { const kvs = Array . from ( enr . entries ( ) ) . reduce ( ( obj , kv ) => { obj [ kv [ 0 ] ] = kv [ 1 ] ; return obj ; } , { } ) ; return new FileENR ( filename , peerId , kvs , enr . seq , enr . signature ) ; } saveToFile ( ) { if ( this . localPeerId === null || this . localPeerId === undefined ) return ; const keypair = createKeypairFromPeerId ( this . localPeerId ) ; writeFile ( this . filename , this . encodeTxt ( keypair . privateKey ) ) ; } set ( key , value ) { super . set ( key , value ) ; this . saveToFile ( ) ; return this ; } delete ( key ) { const result = super . delete ( key ) ; this . saveToFile ( ) ; return result ; } }