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

100% Statements 170/170
100% Branches 73/73
100% Functions 14/14
100% Lines 169/169

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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439              1x   1x 1x 1x 1x 1x 1x 1x   1x                                       28x 1x   27x 1x     26x 26x     26x 26x     26x 26x       26x       25x 25x 1x         24x       24x   24x     24x                   4x 4x 1x   1x     4x     1x     1x 1x 1x 1x 1x         4x 4x     7x 7x                                         5x   5x 2x 2x 4x 1x         5x             13x 13x   13x   13x 27x 27x 1x     26x 26x 10x 10x 16x 1x     26x     12x               11x 10x     11x 5x 5x   5x   5x 8x   8x 17x 7x       8x   8x 8x           11x 5x 5x 5x 5x       11x 6x 6x 6x     11x         11x 11x 11x 10x   10x 30x 30x 2x 28x 10x 18x 6x 12x 1x     11x       11x 7x       11x 7x 7x 14x                   11x       11x   11x                 8x 8x 1x   7x                           3x                 3x                   8x 8x 2x 2x     6x 6x   6x 6x 6x 6x 6x 6x     6x 6x 1x     5x   5x 5x     5x 5x 5x 5x     2x         5x 3x       5x 3x     3x     3x     3x     3x   3x   3x 1x   3x     3x   2x   2x 1x   1x           1x 1x                                     11x 11x   11x 11x 11x   11x 3x     11x         1x  
/*
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
*/
'use strict';
 
const shim = require('../chaincode');
 
const utils = require('../utils/utils');
const Logger = require('../logger');
const logger = Logger.getLogger('contracts-spi/chaincodefromcontract.js');
const DataMarshall = require('./datamarshall.js');
const ClientIdentity = require('../chaincode').ClientIdentity;
const Ajv = require('ajv');
const Contract = require('fabric-contract-api').Contract;
 
require('reflect-metadata');
 
/**
 * The user will have written a class than extends the 'Contract' interface; this
 * is expressed in terms of domain specific functions - that need to be called in the
 * lower-level 'invoke' and 'init' functions.
 *
 * This class implements the 'invoke' and 'init' functions and does the 'routing'
 * @ignore
 **/
class ChaincodeFromContract {
 
    /**
     * Takes an array contract classes, and looks for the functions within those files.
     * Stores a reference to those, so they can be specifically called at a later time
     *
     * @param {Contract[]} contractClasses array of contracts to register
     */
    constructor(contractClasses, serializers, metadata = {}, title, version) {
 
        if (!contractClasses) {
            throw new Error('Missing argument: array of contract classes');
        }
        if (!serializers) {
            throw new Error('Missing argument: serialization implement information');
        }
 
        this.serializers = serializers;
        logger.debug('Using serializers', serializers);
 
 
        this.title = title;
        this.version = version;
 
        // always add in the 'meta' class that has general abilities
        const SystemContract = require('./systemcontract');
        contractClasses.push(SystemContract);
 
        // Produce the internal data structure that represents the code that is
        // loaded.This should be optimized for the invocation of functions at runtime
        this.contractImplementations = this._resolveContractImplementations(contractClasses);
 
 
        // validate the supplied metadata against what code we have (just in case)
        const errors = this._checkAgainstSuppliedMetadata(metadata);
        if (errors.length > 0) {
            throw new Error(JSON.stringify(errors));
        }
 
        // process the metadata. If nothing supplied the code has to be introspected
        // as much as possible
        this.metadata = this._augmentMetadataFromCode(metadata);
 
        // really do not like this method of duplicating an object
        // But it works and is quick (allegedly)
        const systemContract = this.contractImplementations['org.hyperledger.fabric'].contractInstance;
 
        systemContract._setMetadata(JSON.parse(JSON.stringify(this.metadata)));
 
        // compile the schemas, and in addition sets upt eh data marhsalls with this information
        this._compileSchemas();
 
    }
 
    /**
     * Compile the complex object schemas into validator functions that can be used
     * for arguments.
     */
    _compileSchemas() {
 
        const schemaList = [];
        for (const name in this.metadata.components.schemas) {
            const s = this.metadata.components.schemas[name];
 
            schemaList.push(s);
        }
 
        if (schemaList.length > 0) {
            // provide the list of schemas (of the complex types) to AJV, identified by name
 
            const ajv = this._ajv(schemaList);
            // create validators for each complex type
            // have lowercases the ids
            this.contractImplementations.schemas = {};
            schemaList.forEach((e) => {
                const id = e.$id;
                this.contractImplementations.schemas[id] = {};
                this.contractImplementations.schemas[id].validator = ajv.getSchema(id);
            });
 
        }
        // final step is to setup up data marhsall instances
        const requestedSerializer = this.serializers.transaction;
        for (const contractName in this.contractImplementations) {
            // determine the serialization structure that is needed for this contract
            // create and store the dataMarshall that is needed
            const dataMarshall = this._dataMarshall(requestedSerializer);
            this.contractImplementations[contractName].dataMarshall = dataMarshall;
        }
    }
    /* istanbul ignore next */
    _dataMarshall(requestedSerializer) {
        return new DataMarshall(requestedSerializer, this.serializers.serializers, this.metadata.components.schemas);
    }
    /* istanbul ignore next */
    _ajv(schemaList) {
        return new Ajv({
            useDefaults: true,
            coerceTypes: false,
            allErrors: true,
            schemas: schemaList
        });
    }
 
    /**
     * TODO: Review the supplied metadata and check that the functions that have been given are the same ones as have been supplied
     */
    _checkAgainstSuppliedMetadata(metadata) {
        const errors = [];
 
        if (metadata.contracts) {
            const contracts = JSON.parse(JSON.stringify(this.contractImplementations));
            for (const contractKey in contracts) {
                if (!metadata.contracts[contractKey]) {
                    errors.push(`Missing contract ${contractKey} in metadata`);
                }
            }
        }
 
        return errors;
    }
 
    /**
     * Load the contract implementation code
     */
    _resolveContractImplementations(contractClasses) {
        logger.debug('Supplied contract classes', contractClasses);
        this.defaultContractName = Reflect.getMetadata('fabric:default', global);
 
        const implementations = {};
 
        for (const contractClass of contractClasses) {
            const contract = new (contractClass);
            if (!(Contract._isContract(contract))) {
                throw new Error(`invalid contract instance ${JSON.stringify(contract)}`);
            }
 
            const name = contract.getName();
            if (!this.defaultContractName) {
                this.defaultContractName = name;
                contract.default = true;
            } else if (this.defaultContractName === contract.getName()) {
                contract.default = true;
            }
 
            implementations[name] = {name, contractInstance: contract};
 
        }
        return implementations;
    }
 
    /** Create the standard method from the code that has been loaded
     * This can use introspection and, if applicable, typescript annotations
     */
    _augmentMetadataFromCode(metadata) {
 
        if (!metadata.$schema) {
            metadata.$schema = 'https://hyperledger.github.io/fabric-chaincode-node/main/api/contract-schema.json';
        }
 
        if (!metadata.contracts || Object.keys(metadata.contracts).length === 0) {
            logger.debug('_augmentMetadataFromCode - Contracts not supplied. Generating default');
            const skipNames = Object.getOwnPropertyNames(Contract.prototype);
 
            metadata.contracts = JSON.parse(JSON.stringify(this.contractImplementations));
 
            for (const contractKey in metadata.contracts) {
                const contract = metadata.contracts[contractKey];
 
                for (const instanceKey in contract.contractInstance) {
                    if (instanceKey.startsWith('_')) {
                        delete contract.contractInstance[instanceKey];
                    }
                }
 
                const impl = this.contractImplementations[contractKey].contractInstance;
 
                contract.transactions = this._processContractTransactions(impl, skipNames);
                contract.info = this._processContractInfo(impl);
            }
        }
 
        // look for the general information representing all the contracts
        // add if nothing has been given by the application
        if (!metadata.info) {
            logger.debug('_augmentMetadataFromCode - Info not supplied. Generating default');
            metadata.info = {};
            metadata.info.version = this.version ? this.version : '';
            metadata.info.title = this.title ? this.title : '';
        }
 
        // obtain the information relating to the complex objects
        if (!metadata.components) {
            logger.debug('_augmentMetadataFromCode - Components not supplied. Generating default');
            metadata.components = {};
            metadata.components.schemas = Reflect.getMetadata('fabric:objects', global) || {};
        }
 
        return metadata;
    }
 
    /** read the code and create the internal structure representing the code */
    _processContractTransactions(contract, ignore) {
        let transactions = [];
        transactions = Reflect.getMetadata('fabric:transactions', contract) || [];
        if (transactions.length === 0) {
            const propNames = Object.getOwnPropertyNames(Object.getPrototypeOf(contract));
 
            for (const propName of propNames) {
                const propValue = contract[propName];
                if (typeof propValue !== 'function') {
                    continue;
                } else if (propName === 'constructor') {
                    continue;
                } else if (propName.startsWith('_')) {
                    continue;
                } else if (ignore.includes(propName)) {
                    continue;
                }
 
                const transaction = {
                    name: propName
                };
 
                if (contract.getName() !== 'org.hyperledger.fabric') {
                    transaction.tags = ['SUBMIT', 'submitTx'];
                }
 
                // add 'argN' parameters, skipping the first (stub) parameter
                if (propValue.length > 1) {
                    transaction.parameters = [];
                    for (let param = 1; param < propValue.length; param++) {
                        transaction.parameters.push({
                            name: `arg${param - 1}`,
                            description: `Argument ${param - 1}`,
                            schema: {
                                type: 'string'
                            }
                        });
                    }
                }
 
                transactions.push(transaction);
            }
        }
 
        logger.debug('Transactions for contract ' + contract.name, transactions);
 
        return transactions;
    }
 
    /**
     * get information on this contract
     * @param {*} contract
     */
    _processContractInfo(contract) {
 
        const info = Reflect.getMetadata('fabric:info', global) || {};
        if (info[contract.constructor.name]) {
            return info[contract.constructor.name];
        } else {
            return {
                title: '',
                version: ''
            };
        }
    }
 
    /**
     * The init fn is called for updated and init operations; the user though can include any function
     * in these calls. Therefore we are giving the user the responsibility to put the correct function in
     *
     * @param {ChaincodeStub} stub Stub class giving the full api
     */
    async Init(stub) {
        return this.invokeFunctionality(stub);
    }
 
    /**
     * The invoke fn is called for all the invoke operations
     *
     * @param {ChaincodeStub} stub Stub class giving the full api
     */
    async Invoke(stub) {
        return this.invokeFunctionality(stub);
    }
 
    /**
     * The invokeFunctionality function is called for all the invoke operations; init is also redirected to here
     *
     * @param {ChaincodeStub} stub Stub class giving the full api
     * @param {Object} fAndP Function and Paramters obtained from the smart contract argument
     */
    async invokeFunctionality(stub) {
        const bufferArgs = stub.getBufferArgs();
        if ((!bufferArgs) || (bufferArgs.length < 1)) {
            const message = 'Default initiator successful.';
            return shim.success(Buffer.from(message));
        }
 
        const fAndP = bufferArgs[0].toString();
        const txArgs = bufferArgs.slice(1);
 
        const txID = stub.getTxID();
        const channelID = stub.getChannelID();
        const loggerPrefix = utils.generateLoggingPrefix(channelID, txID);
        try {
            const {contractName: cn, function: fn} = this._splitFunctionName(fAndP);
            logger.debug(`${loggerPrefix} Invoking ${cn} ${fn}`);
 
 
            const contractData = this.contractImplementations[cn];
            if (!contractData) {
                throw new Error(`Contract name is not known: ${cn}`);
            }
 
            const transactionDescriptor = this.metadata.contracts[cn];
 
            const contractInstance = contractData.contractInstance;
            const dataMarshall = contractData.dataMarshall;
 
            // setup the transaction context that is passed to each transaction function
            const ctx = contractInstance.createContext();
            ctx.setChaincodeStub(stub);
            ctx.setClientIdentity(new ClientIdentity(stub));
            ctx.logging = {
                setLevel: Logger.setLevel,
                getLogger: (name) => {
                    return Logger.getLogger(name ? `${cn}:${name}` : cn);
                }
            };
 
            // get the specific information for this tx function
            const functionExists = transactionDescriptor.transactions.find((transaction) => {
                return transaction.name === fn;
            });
 
            // if the function exists, then we can call it otherwise, call the unkownn tx handler
            if (functionExists) {
                logger.debug(`${JSON.stringify(functionExists)}`);
                // marhsall the parameters into the correct types for hanlding by
                // the tx function
                const parameters = dataMarshall.handleParameters(functionExists, txArgs, loggerPrefix);
 
                // before tx
                await contractInstance.beforeTransaction(ctx);
 
                // around tx
                const result = await contractInstance.aroundTransaction(ctx, fn, parameters);
 
                // after tx fn, assuming that the smart contract hasn't gone wrong
                await contractInstance.afterTransaction(ctx, result);
 
                let returnSchema = {};
                // javascript/typescript so there will only be one type
                if (functionExists.returns) {
                    returnSchema = functionExists.returns;
                }
                logger.debug(`${JSON.stringify(result)},${returnSchema.schema}`);
                // returnSchema can be undefined if there is no return value - the datamarshall can handle that
                // return the data value, if any to the shim. Including converting the result to the wire format
                return shim.success(dataMarshall.toWireBuffer(result, returnSchema.schema, loggerPrefix));
            } else {
                try {
                    // if we've never heard of this function, then call the unknown tx function
                    await contractInstance.unknownTransaction(ctx);
                    return shim.success();
                } catch (error) {
                    return shim.error(error.message);
                }
            }
 
        } catch (error) {
            // log the error and then fail the transaction
            logger.error(`${loggerPrefix} ${error}`);
            return shim.error(error.message);
        }
    }
 
    /**
     * Parse the fcn name to be name and function.  These are separated by a :
     * Anything after the : is treated as the function name
     * No : implies that the whole string is a function name
     *
     * @param {String} fcn the combined function and name string
     * @return {Object} split into name and string
     */
    _splitFunctionName(fcn) {
        // Did consider using a split(':') call to do this; however I chose regular expression for
        // the reason that it provides definitive description.
        // Split will just split - you would then need to write the code to handle edge cases
        // for no input, for multiple :, for multiple : without intervening characters
        // https://regex101.com/ is very useful for understanding
 
        const regex = /([^:]*)(?::|^)(.*)/g;
        const result = {contractName: '', function: ''};
 
        const m = regex.exec(fcn);
        result.contractName = m[1];
        result.function = m[2];
 
        if (!result.contractName || result.contractName.trim() === '') {
            result.contractName = this.defaultContractName;
        }
 
        return result;
    }
 
}
 
module.exports = ChaincodeFromContract;