import { Logger , getLogger , Md5Hash , SignatureVerifier , DefaultSignatureVerifier , serializeObject , deserializeObject , } from '@pigi/core-utils' ; import { DB } from '@pigi/core-db' ; import { SignedByDBInterface } from '../../types/db/signed-by-db.interface' ; import { SignedMessage } from '../../types/serialization' ; const log = getLogger ( 'signed-by-db' ) ; /**
 * DB to store and access message signatures.
 */ export class SignedByDB implements SignedByDBInterface { public constructor ( private readonly db , private readonly singatureVerifier = DefaultSignatureVerifier . instance ( ) ) { } public async handleMessage ( serializedMessage , signature ? ) { if ( ! ! signature ) { try { await this . storeSignedMessage ( serializedMessage , signature ) ; } catch ( e ) { log . debug ( `Received a message that cannot be parsed. Ignoring. Message: ${ serializedMessage }, error: ${ e . message }, stack: ${ e . stack }` ) ; } } } public async storeSignedMessage ( serializedMessage , signature ) { const signerPublicKey = await this . singatureVerifier . verifyMessage ( serializedMessage , signature ) ; const serializedRecord = SignedByDB . serializeRecord ( { signature , serializedMessage , } ) ; await this . db . bucket ( Buffer . from ( signerPublicKey ) ) . put ( SignedByDB . getKey ( serializedMessage ) , serializedRecord ) ; } public async getMessageSignature ( serializedMessage , signerPublicKey ) { const recordBuffer = await this . db . bucket ( Buffer . from ( signerPublicKey ) ) . get ( SignedByDB . getKey ( serializedMessage ) ) ; if ( ! recordBuffer ) { return undefined ; } return SignedByDB . deserializeRecord ( recordBuffer ) . signature ; } public async getAllSignedBy ( signerPublicKey ) { const signed = await this . db . bucket ( Buffer . from ( signerPublicKey ) ) . iterator ( ) . values ( ) ; return signed . map ( ( m ) => SignedByDB . deserializeRecord ( m ) ) ; } private static getKey ( message ) { return Buffer . from ( Md5Hash ( message ) ) ; } private static serializeRecord ( signedMessage ) { return Buffer . from ( serializeObject ( signedMessage ) ) ; } private static deserializeRecord ( serialized ) { const obj = deserializeObject ( serialized . toString ( ) ) ; return { signature : obj [ 'signature' ] , serializedMessage : obj [ 'serializedMessage' ] , } ; } }