Source: operations/messages.js

'use strict';
/**
 * @module lib/operations/messages
 * @summary Whiteflag API messages endpoints handler module
 * @description Module with api messages endpoint handlers
 * @tutorial modules
 * @tutorial openapi
 */
module.exports = {
    send,
    receive,
    validate,
    encode,
    decode,
    getMessages,
    getReferences,
    getSequence
};

/* Common internal functions and classes */
const arr = require('../_common/arrays');
const msg = require('../protocol/_common/messages');
const { ProcessingError } = require('../_common/errors');
const { createBody,
        sendImperative,
        sendIndicative } = require('./_common/response');

/* Whiteflag modules */
const wfCodec = require('../protocol/codec');
const wfRetrieve = require('../protocol/retrieve');
const wfReference = require('../protocol/references');
const wfRxEvent = require('../protocol/events').rxEvent;
const wfTxEvent = require('../protocol/events').txEvent;

/* MAIN MODULE FUNCTIONS */
/**
 * Transmits messages to the blockchain through the tx event chain
 * @function send
 * @alias module:lib/operations/messages.send
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function send(req, res, operationId, callback) {
    const wfMessage = req.body;
    if (wfMessage.MetaHeader?.autoGenerated) wfMessage.MetaHeader.autoGenerated = false;
    wfTxEvent.emit('messageCommitted', wfMessage, function opsSendCb(err, wfMessage) {
        // Create response body and preserve information before responding
        let resBody = createBody(req, operationId);
        if (!err) resBody.meta = addMessageMetaInfo(wfMessage, resBody.meta);

        // Send response using common endpoint response function
        return sendImperative(res, err, resBody, wfMessage, callback);
    });
}

/**
 * Receives messages by triggering the rx event chain
 * @function receive
 * @alias module:lib/operations/messages.receive
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function receive(req, res, operationId, callback) {
    const wfMessage = req.body;
    wfRxEvent.emit('messageReceived', wfMessage, function opsReceiveCb(err, wfMessage) {
        // Create response body and preserve information before responding
        let resBody = createBody(req, operationId);

        // Add message info to meta data
        if (!err) resBody.meta = addMessageMetaInfo(wfMessage, resBody.meta);

        // Send response using common endpoint response function
        return sendImperative(res, err, resBody, wfMessage, callback);
    });
}

/**
 * Checks whether a Whiteflag message is valid
 * @function validate
 * @alias module:lib/operations/messages.validate
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function validate(req, res, operationId, callback) {
    const wfMessage = req.body;
    wfCodec.verifyFormat(wfMessage, function opsVerifyFormatCb(err, wfMessage) {
        // Create response body and preserve information before responding
        let resBody = createBody(req, operationId);
        if (err) return sendIndicative(res, err, resBody, wfMessage, callback);

        // Verify message reference
        wfReference.verify(wfMessage, function opsVerifyReferenceCb(err, wfMessage) {
            if (!err) resBody.meta = addMessageMetaInfo(wfMessage, resBody.meta);
            return sendIndicative(res, err, resBody, wfMessage, callback);
        });
    });
}

/**
 * Encodes a Whiteflag message
 * @function encode
 * @alias module:lib/operations/messages.encode
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function encode(req, res, operationId, callback) {
    const wfMessage = req.body;
    wfCodec.encode(wfMessage, function opsEncodeCb(err, wfMessage) {
        // Create response body and preserve information before responding
        let resBody = createBody(req, operationId);
        if (!err) resBody.meta = addMessageMetaInfo(wfMessage, resBody.meta);

        // Send response using common endpoint response function
        return sendImperative(res, err, resBody, wfMessage, callback);
    });
}

/**
 * Decodes a Whiteflag message
 * @function decode
 * @alias module:lib/operations/messages.decode
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function decode(req, res, operationId, callback) {
    let wfMessage = {};
    // Do not complain if plain metaheader provided
    if (Object.hasOwn(req.body, 'MetaHeader')) {
        wfMessage = req.body;
    } else {
        wfMessage.MetaHeader = req.body;
    }
    wfCodec.decode(wfMessage, function opsDecodeCb(err, wfMessage, ivMissing) {
        // Create response body and preserve information before responding
        let resBody = createBody(req, operationId);

        // Check for missing decryption key
        if (err?.code === 'WF_ENCRYPTION_ERROR' && !wfMessage.MetaHeader.encryptionKeyInput) {
            err = new ProcessingError('Could not decrypt message', [ 'Encryption key input is missing', err.message ], 'WF_API_BAD_REQUEST');
        }
        // Check for missing intitialisation vector
        if (!err && ivMissing) {
            err = new ProcessingError('Could not decrypt message', [ 'Initialisation vector is missing' ], 'WF_API_BAD_REQUEST');
        }
        // Add message info to meta data
        if (!err) resBody.meta = addMessageMetaInfo(wfMessage, resBody.meta);

        // Send response using common endpoint response function
        return sendImperative(res, err, resBody, wfMessage, callback);
    });
}

/**
 * Retrieves all messages from the database
 * @function getMessages
 * @alias module:lib/operations/messages.getMessages
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function getMessages(req, res, operationId, callback) {
    let wfQuery = {};
    let resBody = createBody(req, operationId);
    resBody.meta.query = req.query;

    let parameters = Object.keys(req.query);
    if (parameters.length !== 0) {
        parameters.forEach(parameter => {
            switch (parameter) {
                // Integers
                case 'blockNumber':
                case 'blockDepth': {
                    wfQuery[`MetaHeader.${parameter}`] = parseInt(req.query[parameter]);
                    break;
                }
                // Booleans
                case 'autoGenerated':
                case 'transmissionSuccess':
                case 'confirmed':
                case 'originatorValid':
                case 'referenceValid':
                case 'formatValid': {
                    wfQuery[`MetaHeader.${parameter}`] = (req.query[parameter] === 'true');
                    break;
                }
                // Message Header fiels
                case 'Version':
                case 'EncryptionIndicator':
                case 'MessageCode':
                case 'DuressIndicator':
                case 'ReferenceIndicator':
                case 'ReferencedMessage': {
                    wfQuery[`MessageHeader.${parameter}`] = req.query[parameter];
                    break;
                }
                // Metaheader strings
                default: {
                    wfQuery[`MetaHeader.${parameter}`] = req.query[parameter];
                }
            }
        });
    }
    wfRetrieve.getQuery(wfQuery, function opsGetMessagesDbCb(err, wfMessages) {
        return processMessages(err, res, resBody, wfMessages, callback);
    });
}

/**
 * Retrieves message references from the database
 * @function getReferences
 * @alias module:lib/operations/messages.getReferences
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function getReferences(req, res, operationId, callback) {
    const query = req.query || {};
    let resBody = createBody(req, operationId);
    resBody.meta.query = query;

    // Retrieve references if transaction hash is specified as query parameter
    if (query.transactionHash && query.blockchain) {
        return wfRetrieve.getReferences(query.transactionHash, query.blockchain,
            function opsGetReferencesBcCb(err, wfMessages) {
                if (!err) resBody.meta.info = arr.addItem(resBody.meta.info, `Known Whiteflag messages on ${query.blockchain} referencing message ${query.transactionHash}`);
                processMessages(err, res, resBody, wfMessages, callback);
            }
        );
    }
    if (query.transactionHash) {
        return wfRetrieve.getReferences(query.transactionHash, null,
            function opsGetReferencesCb(err, wfMessages) {
                if (!err) resBody.meta.info = arr.addItem(resBody.meta.info, `Known Whiteflag messages referencing message ${query.transactionHash}`);
                processMessages(err, res, resBody, wfMessages, callback);
            }
        );
    }
    // Cannot retrieve message references without transaction hash
    let err = new ProcessingError('Query does not contain transactionHash of referencing message', null, 'WF_API_BAD_REQUEST');
    return processMessages(err, res, resBody, null, callback);
}

/**
 * Retrieves message sequences from the database
 * @function getSequence
 * @alias module:lib/operations/messages.getSequence
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {string} operationId the operation id as defined in the openapi definition
 * @param {logEndpointEventCb} callback
 */
function getSequence(req, res, operationId, callback) {
    const query = req.query || {};
    let resBody = createBody(req, operationId);
    resBody.meta.query = query;

    // Retrieve sequence if transaction hash is specified as query parameter
    if (query.transactionHash && query.blockchain) {
        return wfRetrieve.getSequence(query.transactionHash, query.blockchain,
            function opsGetSequenceBcCb(err, wfMessages) {
                if (!err) resBody.meta.info = arr.addItem(resBody.meta.info, `Known Whiteflag message sequence on ${query.blockchain} starting with message ${query.transactionHash}`);
                processMessages(err, res, resBody, wfMessages, callback);
            }
        );
    }
    if (query.transactionHash) {
        return wfRetrieve.getSequence(query.transactionHash, null,
            function opsGetSequenceCb(err, wfMessages) {
                if (!err) resBody.meta.info = arr.addItem(resBody.meta.info, `Known Whiteflag message sequence starting with message ${query.transactionHash}`);
                processMessages(err, res, resBody, wfMessages, callback);
            }
        );
    }
    // Cannot retrieve message sequence without trabsaction hash
    let err = new ProcessingError('Query does not contain transactionHash of first message in sequence', null, 'WF_API_BAD_REQUEST');
    return processMessages(err, res, resBody, null, callback);
}

/* PRIVATE MODULE FUNCTIONS */
/**
 * Returns messages from queries on resource endpoints
 * @private
 * @param {Object} req the http request
 * @param {Object} res the http response
 * @param {Object} resBody the response body
 * @param {Array} wfMessages Whiteflag messages
 * @param {logEndpointEventCb} callback
 */
function processMessages(err, res, resBody, wfMessages, callback) {
    // Ensure message are in an array
    let resData = [];
    if (!err) {
        if (Array.isArray(wfMessages)) resData = wfMessages;
            else resData = [ wfMessages ];
    }
    // Send response using common endpoint response function
    return sendIndicative(res, err, resBody, resData, callback);
}

/**
 * Adds message inforamtion to the meta property of the response body
 * @private
 * @param {@wfMessage} wfMessage 
 * @param {Object} meta the meta property of the response body
 * @returns {Object} the updated meta property of the response body
 */
function addMessageMetaInfo(wfMessage, meta) {
    meta.message = msg.type(wfMessage);
    meta.type = msg.title(wfMessage);
    meta.info = arr.addItem(meta.info, msg.descr(wfMessage));
    if (wfMessage.MetaHeader.formatValid) {
        meta.info = arr.addItem(meta.info, 'Message format is valid');
    }
    if (wfMessage.MetaHeader.referenceValid) {
        meta.info = arr.addItem(meta.info, 'Message reference is valid');
    }
    if (wfMessage.MetaHeader.originatorValid) {
        meta.info = arr.addItem(meta.info, 'Message originator has been authenticated');
    }
    return meta;
}