All files / fabric-shim/lib/contract-spi bootstrap.js

100% Statements 65/65
100% Branches 20/20
100% Functions 6/6
100% Lines 65/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152              18x 18x 18x 18x   18x 18x 18x 18x 18x   18x                                 2x   2x 1x 1x     1x                   2x 2x 2x 2x       5x 5x   5x 5x 5x 5x 5x             5x 4x 4x 4x       4x 2x   2x 1x   1x     1x 1x         3x 2x     1x   1x             3x 3x 3x 3x   3x 2x 2x     3x 2x 2x   1x   3x           3x 3x 3x   3x   3x 3x 3x 3x 3x 1x   2x       18x        
/*
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
*/
'use strict';
 
const path = require('path');
const yargs = require('yargs');
const Ajv = require('ajv');
const fs = require('fs-extra');
 
const shim = require('../chaincode');
const ChaincodeFromContract = require('./chaincodefromcontract');
const Logger = require('../logger');
const StartCommand = require('../cmds/startCommand.js');
const ServerCommand = require('../cmds/serverCommand.js');
 
const logger = Logger.getLogger('contracts-spi/bootstrap.js');
 
class Bootstrap {
    /**
     * This provides SPI level functions to 'bootstrap' or 'get the chaincode going'
     * This is achieved through introspection of the package.json that defines the
     * node module
     */
 
    /**
     * @ignore
     * @param {Contract} contracts contract to register to use
     */
    static async register(contracts, serializers, fileMetadata, title, version, opts, serverMode = false) {
        // load up the meta data that the user may have specified
        // this will need to passed in and rationalized with the
        // code as implemented
        const chaincode = new ChaincodeFromContract(contracts, serializers, fileMetadata, title, version);
 
        if (serverMode) {
            const server = shim.server(chaincode, opts);
            await server.start();
        } else {
            // say hello to the peer
            shim.start(chaincode);
        }
    }
 
    /**
     *
     * @ignore
     * @param {boolean} serverMode set true if the chaincode should be started as a server
     */
    static async bootstrap(serverMode = false) {
        const opts = serverMode ? ServerCommand.getArgs(yargs) : StartCommand.getArgs(yargs);
        const {contracts, serializers, title, version} = this.getInfoFromContract(opts['module-path']);
        const fileMetadata = await Bootstrap.getMetadata(opts['module-path']);
        await Bootstrap.register(contracts, serializers, fileMetadata, title, version, opts, serverMode);
    }
 
    static getInfoFromContract(modulePath) {
        const modPath = path.resolve(process.cwd(), modulePath);
        const jsonPath = path.resolve(modPath, 'package.json');
        // let's find the package.json file
        const json = require(jsonPath);
        logger.debug('starting up and reading package.json at %s', jsonPath);
        logger.debug('read JSON', json);
        const JSONSerializer = require('fabric-contract-api').JSONSerializer;
        const defaultSerialization = {
            transaction: 'jsonSerializer',
            serializers: {
                jsonSerializer : JSONSerializer
            }
        };
 
        if (json.main) {
            logger.debug('Using the main entry %s', json.main);
            const p = (path.resolve(modPath, json.main));
            const r = require(p);
 
            // setup the set of serializers that can be used
            let serializers;
            if (!r.serializers) {
                serializers = defaultSerialization;
            } else {
                if (!r.serializers.transaction) {
                    throw new Error('There should be a \'transaction\' property to define the serializer for use with transactions');
                }
                serializers = r.serializers;
 
                // copy in the default ones if not already set
                for (const s in defaultSerialization.serializers) {
                    serializers.serializers[s] = defaultSerialization.serializers[s];
                }
 
            }
 
            if (r.contracts) {
                return {contracts: r.contracts, serializers, title: json.name, version: json.version};
            }
 
            return {contracts: [r], serializers, title: json.name, version: json.version};
        } else {
            throw new Error('package.json does not contain a \'main\' entry for the module');
        }
    }
    /**
     * Gets meta data associated with this Chaincode deployment
     */
    static async getMetadata(modulePath) {
        let metadata = {};
        const modPath = path.resolve(process.cwd(), modulePath);
        let metadataPath = path.resolve(modPath, 'META-INF', 'metadata.json');
        let pathCheck = await fs.pathExists(metadataPath);
 
        if (!pathCheck) {
            metadataPath = path.resolve(modPath, 'contract-metadata', 'metadata.json');
            pathCheck = await fs.pathExists(metadataPath);
        }
 
        if (pathCheck) {
            metadata = Bootstrap.loadAndValidateMetadata(metadataPath);
            logger.debug('Loaded metadata', metadata);
        } else {
            logger.info('No metadata file supplied in contract, introspection will generate all the data');
        }
        return metadata;
    }
 
    static noop() {}
 
    static loadAndValidateMetadata(metadataPath) {
        const rootPath = path.dirname(__dirname);
        const metadataString = fs.readFileSync(metadataPath).toString();
        const schemaString = fs.readFileSync(path.join(rootPath, '../../fabric-contract-api/schema/contract-schema.json')).toString();
 
        const metadata = JSON.parse(metadataString);
 
        const onlyErrors = {log: Bootstrap.noop, warn: Bootstrap.noop, error: console.error}; // eslint-disable-line no-console
        const ajv = new Ajv({schemaId: 'id', logger: onlyErrors});
        ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
        const valid = ajv.validate(JSON.parse(schemaString), metadata);
        if (!valid) {
            throw new Error('Contract metadata does not match the schema: ' + JSON.stringify(ajv.errors));
        }
        return metadata;
    }
}
 
module.exports = Bootstrap;