import { HashAlgorithm , Logger , getLogger , hashFunctionFor , deserializeObject , } from '@pigi/core-utils' ; import { DB } from '@pigi/core-db' ; import { HashPreimageDBInterface } from '../../types/db' ; import { Message } from '../../types/serialization' ; const log = getLogger ( 'hash-preimage-db' ) ; interface Record { preimage : string ; hashAlgorithm : HashAlgorithm ; hash : string ; } export class HashPreimageDB implements HashPreimageDBInterface { public constructor ( private readonly db ) { } public async handleMessage ( serializedMessage ) { try { const message = deserializeObject ( serializedMessage ) as Message ; if ( message . data && 'preimage' in message . data ) { await this . storePreimage ( message . data [ 'preimage' ] , HashAlgorithm . KECCAK256 ) ; } } catch ( e ) { log . debug ( `Received a message that cannot be parsed. Ignoring. Message: ${ serializedMessage }, error: ${ e . message }, stack: ${ e . stack }` ) ; } } public async storePreimage ( preimage , hashAlgorithm ) { const hash = hashFunctionFor ( hashAlgorithm ) ( preimage ) ; const serialized = HashPreimageDB . serializeRecord ( { preimage , hashAlgorithm , hash , } ) ; await this . db . bucket ( Buffer . from ( hashAlgorithm ) ) . put ( Buffer . from ( hash ) , serialized ) ; } public async getPreimage ( hash , hashAlgorithm ) { const recordBuffer = await this . db . bucket ( Buffer . from ( hashAlgorithm ) ) . get ( Buffer . from ( hash ) ) ; if ( ! recordBuffer ) { return undefined ; } return HashPreimageDB . deserializeRecord ( recordBuffer ) . preimage ; } private static serializeRecord ( record ) { return Buffer . from ( JSON . stringify ( { preimage : record . preimage . toString ( ) , hashAlgorithm : record . hashAlgorithm , hash : record . hash . toString ( ) , } ) ) ; } private static deserializeRecord ( serialized ) { const obj = JSON . parse ( serialized . toString ( ) ) ; return { preimage : obj [ 'preimage' ] , hashAlgorithm : obj [ 'hashAlgorithm' ] , hash : obj [ 'hash' ] , } ; } }