diff --git a/examples/electricity-trade/BusinessLogicElectricityTrade.ts b/examples/electricity-trade/BusinessLogicElectricityTrade.ts index f5caaf6b8e..313bb90ebc 100644 --- a/examples/electricity-trade/BusinessLogicElectricityTrade.ts +++ b/examples/electricity-trade/BusinessLogicElectricityTrade.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * BusinessLogicElectricityTrade.ts @@ -7,6 +7,8 @@ import { Request } from 'express'; import { RequestInfo } from './RequestInfo'; +import { MeterManagement } from './MeterManagement'; +import { MeterInfo } from './MeterInfo'; import { TradeInfo } from '../../packages/routing-interface/TradeInfo'; import { transactionManagement } from '../../packages/routing-interface/routes/index'; import { BusinessLogicBase } from '../../packages/business-logic-plugin/BusinessLogicBase'; @@ -24,10 +26,12 @@ logger.level = config.logLevel; export class BusinessLogicElectricityTrade extends BusinessLogicBase { businessLogicID: string; + meterManagement: MeterManagement; constructor(businessLogicID: string) { super(); this.businessLogicID = businessLogicID; + this.meterManagement = new MeterManagement(); } startTransaction(req: Request, businessLogicID: string, tradeID: string) { @@ -66,7 +70,7 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { const accountInfo = this.getAccountInfo(transactionSubset); if (Object.keys(accountInfo).length === 0) { - logger.debug(`remittanceTransaction(): skip (No target data)`); + logger.debug(`remittanceTransaction(): skip (No target meter)`); return; } @@ -294,23 +298,33 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase { getAccountInfo(transactionSubset: object): object { const transactionInfo = {}; - for (const customer of config.electricityTradeInfo.ethereum.account.customer) { - logger.debug(`customer = ${json2str(customer)}`); - if (transactionSubset['Name'] === customer.number) { - if (transactionSubset['Verb'] === "inc") { - logger.debug('getAccountInfo(): A to B'); - transactionInfo['fromAddress'] = customer.accountA; - transactionInfo['fromAddressPkey'] = config.electricityTradeInfo.ethereum.account.pKey[customer.accountA]; - transactionInfo['toAddress'] = customer.accountB; - } - else if (transactionSubset['Verb'] === "dec"){ - logger.debug('getAccountInfo(): B to A'); - transactionInfo['fromAddress'] = customer.accountB; - transactionInfo['fromAddressPkey'] = config.electricityTradeInfo.ethereum.account.pKey[customer.accountB]; - transactionInfo['toAddress'] = customer.accountA; - } - } + + // Get Meter Information. + const meterInfo: MeterInfo | null = this.meterManagement.getMeterInfo(transactionSubset['Name']); + if (meterInfo === null) { + logger.debug(`Not registered. meterID = ${transactionSubset['Name']}`); + return transactionInfo; } + + logger.debug(`getAccountInfo(): Verb = ${transactionSubset['Verb']}`); + if (transactionSubset['Verb'] === "inc") { + logger.debug('getAccountInfo(): Verb = inc'); + transactionInfo['fromAddress'] = "0x" + meterInfo.bankAccount; + transactionInfo['fromAddressPkey'] = meterInfo.bankAccountPKey; + transactionInfo['toAddress'] = "0x" + meterInfo.powerCompanyAccount; + } + return transactionInfo; } + + setConfig(meterParams: string[]) : object { + + logger.debug("called setConfig()"); + + // add MeterInfo + const meterInfo = new MeterInfo(meterParams); + const result: {} = this.meterManagement.addMeterInfo(meterInfo); + return result; + } + } diff --git a/examples/electricity-trade/MeterInfo.ts b/examples/electricity-trade/MeterInfo.ts new file mode 100644 index 0000000000..a5908d07a8 --- /dev/null +++ b/examples/electricity-trade/MeterInfo.ts @@ -0,0 +1,20 @@ +/* + * Copyright 2021 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * MeterInfo.ts + */ + +export class MeterInfo { + meterID: string; + bankAccount: string; + bankAccountPKey: string; + powerCompanyAccount: string; + + constructor(meterParams: string[]) { + this.meterID = meterParams[0]; + this.bankAccount = meterParams[1]; + this.bankAccountPKey = meterParams[2]; + this.powerCompanyAccount = meterParams[3]; + } +} diff --git a/examples/electricity-trade/MeterManagement.ts b/examples/electricity-trade/MeterManagement.ts new file mode 100644 index 0000000000..3d923859f1 --- /dev/null +++ b/examples/electricity-trade/MeterManagement.ts @@ -0,0 +1,311 @@ +/* + * Copyright 2021 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * MeterManagement.ts + */ + +import { MeterInfo } from './MeterInfo'; +const fs = require('fs'); +const path = require('path'); +const config: any = JSON.parse(fs.readFileSync(path.resolve(__dirname, "./config/default.json"), 'utf8')); +import { getLogger } from "log4js"; +const moduleName = 'MeterManagement'; +const logger = getLogger(`${moduleName}`); +logger.level = config.logLevel; + +// Meter Management Class +export class MeterManagement { + + fileName: string = "MeterInfo.json"; + + constructor() { + ; + } + + // For debugging + fileDump() { + + const confirmData: string = fs.readFileSync(this.fileName, 'utf8'); + const arrayData: MeterInfo[] = JSON.parse(confirmData).table as MeterInfo[]; + logger.debug(arrayData); + + } + + addMeterInfo(addMeterInfo: MeterInfo): object { + + // Existence check of table file + try { + fs.statSync(this.fileName); + } catch (err) { + // Creating an empty table file + const emptyTable = { + table: [] + }; + const emptyTableJson: string = JSON.stringify(emptyTable); + fs.writeFileSync(this.fileName, emptyTableJson, 'utf8'); + } + + // Read table file + const meterInfoFileData: string = fs.readFileSync(this.fileName, 'utf8'); + const meterInfoTable: string[] = JSON.parse(meterInfoFileData).table as string[]; + + // Search target records / replace data + const meterInfoTableNew = { + table: [] + }; + let existFlag: boolean = false; + let action: string = ""; + meterInfoTable.forEach((meterInfoJSON, index) => { + const meterInfo: MeterInfo = JSON.parse(meterInfoJSON) as MeterInfo; + + // Determine if it is a target record + if (meterInfo.meterID === addMeterInfo.meterID) { + // Change Status + meterInfo.bankAccount = addMeterInfo.bankAccount; + meterInfo.bankAccountPKey = addMeterInfo.bankAccountPKey; + meterInfo.powerCompanyAccount = addMeterInfo.powerCompanyAccount; + existFlag = true; + action = "update"; + } + + // Register Record + const meterInfoNewJson: string = JSON.stringify(meterInfo); +// logger.debug(`meter info = ${meterInfoNewJson}`); + meterInfoTableNew.table.push(meterInfoNewJson); + }); + if (existFlag === false) { + const addMeterInfoJson: string = JSON.stringify(addMeterInfo); + logger.debug(`add meter info = ${addMeterInfoJson}`); + meterInfoTableNew.table.push(addMeterInfoJson); + action = "add"; + } + + // Table File Write + const meterInfoTableNewJson: string = JSON.stringify(meterInfoTableNew); + fs.writeFileSync(this.fileName, meterInfoTableNewJson, 'utf8'); + +// this.fileDump(); + + const result = { + "action": action, + "meterID": addMeterInfo.meterID + } + return result; + } + + getMeterInfo(meterID: string): MeterInfo { + + // Existence check of table file + try { + fs.statSync(this.fileName); + } catch (err) { + throw err; + } + + // Read table file + const meterInfoFileData: string = fs.readFileSync(this.fileName, 'utf8'); + const meterInfoTable: string[] = JSON.parse(meterInfoFileData).table as string[]; + + // Search target records + let retMeterInfo: MeterInfo | null = null; + meterInfoTable.forEach((meterInfoJSON, index) => { + const meterInfo: MeterInfo = JSON.parse(meterInfoJSON) as MeterInfo; + + // Determine if it is a target record + if (meterInfo.meterID === meterID) { + retMeterInfo = meterInfo; + return; + } + }); + + return retMeterInfo; + } + + + + +/* + setStatus(tradeInfo: TradeInfo, status: CartradeStatus) { + + // Existence check of table file + try { + fs.statSync(this.fileName); + } catch (err) { + throw err; + } + + // Read table file + const fileData: string = fs.readFileSync(this.fileName, 'utf8'); + const transactionInfoTable: string[] = JSON.parse(fileData).table as string[]; + + // Search target records / replace data + const transactionInfoTableNew = { + table: [] + }; + transactionInfoTable.forEach((transactionInfoJSON, index) => { + const transactionInfo: TransactionInfo = JSON.parse(transactionInfoJSON) as TransactionInfo; + + // Determine if it is a target record + if (transactionInfo.businessLogicID === tradeInfo.businessLogicID && transactionInfo.tradeID === tradeInfo.tradeID) { + // Change Status + transactionInfo.status = status; + } + + // Register Record + const transactionInfoJson: string = JSON.stringify(transactionInfo); + transactionInfoTableNew.table.push(transactionInfoJson); + }); + + // Table File Write + const transactionInfoTableNewJson: string = JSON.stringify(transactionInfoTableNew); + fs.writeFileSync(this.fileName, transactionInfoTableNewJson, 'utf8'); + + this.fileDump(); + } + + setTransactionData(tradeInfo: TradeInfo, transactionData: TransactionData) { + + // Existence check of table file + try { + fs.statSync(this.fileName); + } catch (err) { + throw err; + } + + // Read table file + const fileData: string = fs.readFileSync(this.fileName, 'utf8'); + const transactionInfoTable: string[] = JSON.parse(fileData).table as string[]; + + // Search target records / replace data + const transactionInfoTableNew = { + table: [] + }; + transactionInfoTable.forEach((transactionInfoJSON, index) => { + const transactionInfo: TransactionInfo = JSON.parse(transactionInfoJSON) as TransactionInfo; + + // Determine if it is a target record + if (transactionInfo.businessLogicID === tradeInfo.businessLogicID && transactionInfo.tradeID === tradeInfo.tradeID) { + + // Determine if it is the target transaction + if (transactionData.target === "escrow") { + // escrow: dataset + transactionInfo.escrowLedger = transactionData.ledger; + transactionInfo.escrowTxID = transactionData.txID; + } + else if (transactionData.target === "transfer") { + // transfer: dataset + transactionInfo.transferLedger = transactionData.ledger; + transactionInfo.transferTxID = transactionData.txID; + } + else if (transactionData.target === "settlement") { + // settlement: dataset + transactionInfo.settlementLedger = transactionData.ledger; + transactionInfo.settlementTxID = transactionData.txID; + } + + } + + // Register Record + const transactionInfoJson: string = JSON.stringify(transactionInfo); + transactionInfoTableNew.table.push(transactionInfoJson); + }); + + // Table File Write + const transactionInfoTableNewJson: string = JSON.stringify(transactionInfoTableNew); + fs.writeFileSync(this.fileName, transactionInfoTableNewJson, 'utf8'); + + this.fileDump(); + } + + setTxInfo(tradeInfo: TradeInfo, txInfoData: TxInfoData) { + + // Existence check of table file + try { + fs.statSync(this.fileName); + } catch (err) { + throw err; + } + + // Read table file + const fileData: string = fs.readFileSync(this.fileName, 'utf8'); + const transactionInfoTable: string[] = JSON.parse(fileData).table as string[]; + + // Search target records / replace data + const transactionInfoTableNew = { + table: [] + }; + transactionInfoTable.forEach((transactionInfoJSON, index) => { + const transactionInfo: TransactionInfo = JSON.parse(transactionInfoJSON) as TransactionInfo; + + // Determine if it is a target record + if (transactionInfo.businessLogicID === tradeInfo.businessLogicID && transactionInfo.tradeID === tradeInfo.tradeID) { + + // Determine if it is the target transaction + if (txInfoData.target === "escrow") { + // escrow: dataset + transactionInfo.escrowTxInfo = txInfoData.txInfo; + } + else if (txInfoData.target === "transfer") { + // transfer: dataset + transactionInfo.transferTxInfo = txInfoData.txInfo; + } + else if (txInfoData.target === "settlement") { + // settlement: dataset + transactionInfo.settlementTxInfo = txInfoData.txInfo; + } + + } + + // Register Record + const transactionInfoJson: string = JSON.stringify(transactionInfo); + transactionInfoTableNew.table.push(transactionInfoJson); + }); + + // Table File Write + const transactionInfoTableNewJson: string = JSON.stringify(transactionInfoTableNew); + fs.writeFileSync(this.fileName, transactionInfoTableNewJson, 'utf8'); + + this.fileDump(); + } +*/ + /** + * Get transaction data corresponding to the specified txId. + * (*Return if any of escrowTxID, transferTxID, settlementTxID matches txId) + * + * @return Transaction data corresponding to txId. Returns null if it does not exist. + * + */ +/* + getTransactionInfoByTxId(txId: string): TransactionInfo { + + // Existence check of table file + try { + fs.statSync(this.fileName); + } catch (err) { + throw err; + } + + // Read table file + const fileData: string = fs.readFileSync(this.fileName, 'utf8'); + const transactionInfoTable: string[] = JSON.parse(fileData).table as string[]; + + // Search target records + const transactionInfoTableNew = { + table: [] + }; + let retTransactionInfo: TransactionInfo | null = null; + transactionInfoTable.forEach((transactionInfoJSON, index) => { + const transactionInfo: TransactionInfo = JSON.parse(transactionInfoJSON) as TransactionInfo; + + // Determine if it is a target record + if (transactionInfo.escrowTxID === txId || transactionInfo.transferTxID === txId || transactionInfo.settlementTxID === txId) { + retTransactionInfo = transactionInfo; + return; + } + }); + + return retTransactionInfo; + } +*/ +} diff --git a/examples/electricity-trade/RequestInfo.ts b/examples/electricity-trade/RequestInfo.ts index 663e763dd3..9e64f04452 100644 --- a/examples/electricity-trade/RequestInfo.ts +++ b/examples/electricity-trade/RequestInfo.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * RequestInfo.ts diff --git a/examples/electricity-trade/TransactionEthereum.ts b/examples/electricity-trade/TransactionEthereum.ts index 1446ac7ce7..623cc8c8f5 100644 --- a/examples/electricity-trade/TransactionEthereum.ts +++ b/examples/electricity-trade/TransactionEthereum.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * TransactionEthereum.ts diff --git a/examples/electricity-trade/config/BLP_config.ts b/examples/electricity-trade/config/BLP_config.ts index e2f494bc5c..8081a0636b 100644 --- a/examples/electricity-trade/config/BLP_config.ts +++ b/examples/electricity-trade/config/BLP_config.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * BLP_config.ts diff --git a/examples/electricity-trade/config/default.json b/examples/electricity-trade/config/default.json index 069356c514..b5b3e9680f 100644 --- a/examples/electricity-trade/config/default.json +++ b/examples/electricity-trade/config/default.json @@ -12,27 +12,7 @@ "chainID": 10, "network": "mainnet", "hardfork": "petersburg", - "gas": 21000, - "account": { - "customer": [ - { - "number": "CN000001", - "accountA": "0x06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97", - "accountB": "0x9d624f7995e8bd70251f8265f2f9f2b49f169c55" - }, - { - "number": "CN000002", - "accountA": "0x9d624f7995e8bd70251f8265f2f9f2b49f169c55", - "accountB": "0x06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97" - } - ], - "pKey": { - "0xec709e1774f0ce4aba47b52a499f9abaaa159f71": "40d7e5931a6e0807d3ebd70518f635dbf575975d3bb564ff34c99be416067c89", - "0x36e146d5afab61ab125ee671708eeb380aea05b6": "13a45756bc314465c4ae2ff0eb9ab58cf72453c04604d8fa14393eb25ce96d06", - "0x06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97": "cb5d48d371916a4ea1627189d8af4f642a5d72746a06b559780c3f5932658207", - "0x9d624f7995e8bd70251f8265f2f9f2b49f169c55": "3d966c433eb650f40287debacd92afb9c390024e359f9f719b2ca6c0ab07339a" - } - } + "gas": 21000 } }, "logLevel": "debug" diff --git a/examples/electricity-trade/copyBLPConfig.ts b/examples/electricity-trade/copyBLPConfig.ts index 38932f628d..f47f9041a5 100644 --- a/examples/electricity-trade/copyBLPConfig.ts +++ b/examples/electricity-trade/copyBLPConfig.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * copyBLPConfig.ts diff --git a/examples/electricity-trade/copyStaticAssets.ts b/examples/electricity-trade/copyStaticAssets.ts index 801e45e60a..08db2c6f37 100644 --- a/examples/electricity-trade/copyStaticAssets.ts +++ b/examples/electricity-trade/copyStaticAssets.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * copyStaticAssets.ts diff --git a/examples/electricity-trade/replaceBLPConfigPath.ts b/examples/electricity-trade/replaceBLPConfigPath.ts index 0345e5778a..4fa7bfa3ed 100644 --- a/examples/electricity-trade/replaceBLPConfigPath.ts +++ b/examples/electricity-trade/replaceBLPConfigPath.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * ReplacePath.js diff --git a/examples/electricity-trade/tools/create_batch/create_batch3.py b/examples/electricity-trade/tools/create_batch/create_batch3.py new file mode 100644 index 0000000000..4d62a46e3b --- /dev/null +++ b/examples/electricity-trade/tools/create_batch/create_batch3.py @@ -0,0 +1,327 @@ +#!/usr/bin/python +# +# Copyright 2016 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ------------------------------------------------------------------------------ + +import argparse +import hashlib +import os +import logging +import random +import string +import time +import cbor + +from sawtooth_signing import create_context +from sawtooth_signing import CryptoFactory + +from sawtooth_sdk.protobuf import batch_pb2 +from sawtooth_sdk.protobuf import transaction_pb2 + +from sawtooth_intkey.processor.handler import make_intkey_address + + +LOGGER = logging.getLogger(__name__) + + +class IntKeyPayload: + def __init__(self, verb, name, value): + self._verb = verb + self._name = name + self._value = value + + self._cbor = None + self._sha512 = None + + def to_hash(self): + return { + 'Verb': self._verb, + 'Name': self._name, + 'Value': self._value + } + + def to_cbor(self): + if self._cbor is None: + self._cbor = cbor.dumps(self.to_hash(), sort_keys=True) + return self._cbor + + def sha512(self): + if self._sha512 is None: + self._sha512 = hashlib.sha512(self.to_cbor()).hexdigest() + return self._sha512 + + +def create_intkey_transaction(verb, name, value, deps, signer): + """Creates a signed intkey transaction. + + Args: + verb (str): the action the transaction takes, either 'set', 'inc', + or 'dec' + name (str): the variable name which is altered by verb and value + value (int): the amount to set, increment, or decrement + deps ([str]): a list of transaction header_signatures which are + required dependencies which must be processed prior to + processing this transaction + signer (:obj:`Signer`): the cryptographic signer for signing the + transaction + + Returns: + transaction (transaction_pb2.Transaction): the signed intkey + transaction + """ + payload = IntKeyPayload( + verb=verb, name=name, value=value) + + # The prefix should eventually be looked up from the + # validator's namespace registry. + addr = make_intkey_address(name) + + header = transaction_pb2.TransactionHeader( + signer_public_key=signer.get_public_key().as_hex(), + family_name='intkey', + family_version='1.0', + inputs=[addr], + outputs=[addr], + dependencies=deps, + payload_sha512=payload.sha512(), + batcher_public_key=signer.get_public_key().as_hex(), + nonce=hex(random.randint(0, 2**64))) + + header_bytes = header.SerializeToString() + + signature = signer.sign(header_bytes) + + transaction = transaction_pb2.Transaction( + header=header_bytes, + payload=payload.to_cbor(), + header_signature=signature) + + return transaction + + +def create_batch(transactions, signer): + transaction_signatures = [t.header_signature for t in transactions] + + header = batch_pb2.BatchHeader( + signer_public_key=signer.get_public_key().as_hex(), + transaction_ids=transaction_signatures) + + header_bytes = header.SerializeToString() + + signature = signer.sign(header_bytes) + + batch = batch_pb2.Batch( + header=header_bytes, + transactions=transactions, + header_signature=signature) + + return batch + + +def generate_word(): + return ''.join([random.choice(string.ascii_letters) for _ in range(0, 6)]) + + +def generate_word_list(count): + if os.path.isfile('/usr/share/dict/words'): + with open('/usr/share/dict/words', 'r') as fd: + return {x.strip(): None for x in fd.readlines()[0:count]} + else: + return {generate_word(): None for _ in range(0, count)} + + +def do_populate(batches, keys, value): + context = create_context('secp256k1') + private_key = context.new_random_private_key() + crypto_factory = CryptoFactory(context) + signer = crypto_factory.new_signer(private_key) + + total_txn_count = 0 + txns = [] + for i in range(0, len(keys)): + name = list(keys)[i] + txn = create_intkey_transaction( + verb='set', + name=name, + # value=random.randint(9000, 100000), + value=value, + deps=[], + signer=signer) + total_txn_count += 1 + txns.append(txn) + # Establish the signature of the txn associated with the word + # so we can create good dependencies later + keys[name] = txn.header_signature + + batch = create_batch( + transactions=txns, + signer=signer) + + if value >= 0: + batches.append(batch) + + +def do_generate(args, batches, keys, value, bNeedSetDesp): + context = create_context('secp256k1') + private_key = context.new_random_private_key() + crypto_factory = CryptoFactory(context) + signer = crypto_factory.new_signer(private_key) + + start = time.time() + total_txn_count = 0 + for i in range(1): + txns = [] + for _ in range(1): + name = random.choice(list(keys)) + txn = create_intkey_transaction( + # verb=random.choice(['inc', 'dec']), + verb='inc', + name=name, + # value=random.randint(1, 10), + value=value, + # deps=[keys[name]], + deps= [keys[name]] if bNeedSetDesp else [], + signer=signer) + total_txn_count += 1 + txns.append(txn) + + batch = create_batch( + transactions=txns, + signer=signer) + + batches.append(batch) + + if i % 100 == 0 and i != 0: + stop = time.time() + + txn_count = 0 + for batch in batches[-100:]: + txn_count += len(batch.transactions) + + fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}' + print(fmt.format( + str(i), + 100 / (stop - start), + str(total_txn_count), + txn_count / (stop - start))) + start = stop + + +def write_batch_file(args, batches): + batch_list = batch_pb2.BatchList(batches=batches) + print("Writing to {}...".format(args.output)) + with open(args.output, "wb") as fd: + fd.write(batch_list.SerializeToString()) + + +def do_create_batch(args): + # print("##in do_create_batch") + batches = [] + # print("##args.key_count", args.key_count) + # print("##args.key_name", args.key_name) + # keys = generate_word_list(args.key_count) + keys = {args.key_name: None} + # print("##keys", keys) + # do_populate(batches, keys) + # print("##args.value_set", args.value_set) + do_populate(batches, keys, args.value_set) + # print("##batches", batches) + # do_generate(args, batches, keys) + # print("##args.value_inc", args.value_inc) + # print("##args.value_inc_rand", args.value_inc_rand) + + value_inc = args.value_inc + if args.value_inc_rand >= 1: + value_inc = random.randint(1, args.value_inc_rand) + print("##inc value(random)", value_inc) + + if value_inc >= 0: + # print("##call do_generate()") + do_generate(args, batches, keys, value_inc, args.value_set >= 0) + + # print("##args", args) + write_batch_file(args, batches) + + +def add_create_batch_parser(subparsers, parent_parser): + + epilog = ''' + details: + create sample batch(es) of intkey transactions. + populates state with intkey key/value pairs + then generates batches with inc and dec transactions. + ''' + + parser = subparsers.add_parser( + 'create_batch', + parents=[parent_parser], + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=epilog) + + parser.add_argument( + '-o', '--output', + type=str, + help='location of output file', + default='batches.intkey', + metavar='') + + parser.add_argument( + '-c', '--count', + type=int, + help='number of batches modifying random keys', + default=1, + metavar='') + + parser.add_argument( + '-B', '--max-batch-size', + type=int, + help='max transactions per batch', + default=10, + metavar='') + + parser.add_argument( + '-K', '--key-count', + type=int, + help='number of keys to set initially', + default=1, + metavar='') + + parser.add_argument( + '-n', '--key-name', + type=str, + help='name of key', + default='key1', + metavar='') + + parser.add_argument( + '-s', '--value-set', + type=int, + help='value of set', + default=-1, + metavar='') + + parser.add_argument( + '-i', '--value-inc', + type=int, + help='value of inc', + default=-1, + metavar='') + + parser.add_argument( + '-r', '--value-inc-rand', + type=int, + help='value of inc(random max)', + default=0, + metavar='') diff --git a/examples/electricity-trade/tools/periodicExecuter/package.json b/examples/electricity-trade/tools/periodicExecuter/package.json new file mode 100644 index 0000000000..b33281412a --- /dev/null +++ b/examples/electricity-trade/tools/periodicExecuter/package.json @@ -0,0 +1,17 @@ +{ + "name": "periodicExecuter", + "version": "0.0.1", + "private": true, + "scripts": { + "build": "npm run build-ts", + "build-ts": "tsc", + "tslint": "tslint -c tslint.json -p tsconfig.json" + }, + "dependencies": { + "@types/node": "^14.14.5", + "ts-node": "^9.0.0" + }, + "devDependencies": { + "typescript": "^3.9.3" + } +} diff --git a/examples/electricity-trade/tools/periodicExecuter/periodicExecuter.ts b/examples/electricity-trade/tools/periodicExecuter/periodicExecuter.ts new file mode 100644 index 0000000000..4dbbd539d7 --- /dev/null +++ b/examples/electricity-trade/tools/periodicExecuter/periodicExecuter.ts @@ -0,0 +1,54 @@ +/* + * Copyright 2021 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * periodicExecuter.ts + */ + +const { execSync } = require('child_process'); + +console.log('## start periodicExecuter'); + +if ((process.argv.length !== 5) && (process.argv.length !== 6)) { + console.log('Number of parameters is abnormal.'); + process.exit(-1); +} + +const interval = parseInt(process.argv[2]); +const keyString = process.argv[3]; +const valueAdd = process.argv[4]; +const dockerExecString = 'docker exec sawtooth-shell-default '; +const submitCommand = 'sawtooth batch submit -f batches.intkey --url http://rest-api:8008'; +const incCommand = 'intkey create_batch --key-name ' + keyString + ' --value-inc-rand ' + valueAdd; + +if (process.argv.length === 6) { + const valueInitial = process.argv[5]; + + const setCommand = 'intkey create_batch --key-name ' + keyString + ' --value-set ' + valueInitial; + console.log(`setCommand : ${setCommand}`) + const stdoutSet = execSync(dockerExecString + setCommand); + console.log(`setCommand stdout: ${stdoutSet.toString()}`) + + console.log(`submitCommand(set) : ${submitCommand}`) + const stdoutSetSubmit = execSync(dockerExecString + submitCommand); + console.log(`submitCommand(set) stdout: ${stdoutSetSubmit.toString()}`) +} + +const timerIdArowDown = setInterval(function() { + console.log(`incCommand : ${incCommand}`) + const stdoutInc = execSync(dockerExecString + incCommand); + console.log(`incCommand stdout: ${stdoutInc.toString()}`) + + console.log(`submitCommand(inc) : ${submitCommand}`) + const stdoutIncSubmit = execSync(dockerExecString + submitCommand); + console.log(`submitCommand(inc) stdout: ${stdoutIncSubmit.toString()}`) + + console.log(`##${getCurrentTime()} execute intkey`); +}, interval * 1000); + + +function getCurrentTime() : string { + const now = new Date(); + return '[' + now.getFullYear() + '/' + ('0' + (now.getMonth() + 1)).slice(-2) + '/' + ('0' + (now.getDate())).slice(-2) + ' ' + ('0' + (now.getHours())).slice(-2) + ':' + ('0' + (now.getMinutes())).slice(-2) + ':' + ('0' + (now.getSeconds())).slice(-2) + ']'; +} + diff --git a/examples/electricity-trade/tools/periodicExecuter/tsconfig.json b/examples/electricity-trade/tools/periodicExecuter/tsconfig.json new file mode 100644 index 0000000000..a19738369b --- /dev/null +++ b/examples/electricity-trade/tools/periodicExecuter/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist", + "sourceMap": false, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "ES2017", + "module": "CommonJS", + "typeRoots": [ + "node_modules/@types", + "./typings" + ], + "lib": [ + "es2017", + "dom" + ] + }, + "include": [ + "./*.ts" + ] +} diff --git a/examples/electricity-trade/tools/transferNumericAsset/config/default.js b/examples/electricity-trade/tools/transferNumericAsset/config/default.js new file mode 100644 index 0000000000..e5ce005fea --- /dev/null +++ b/examples/electricity-trade/tools/transferNumericAsset/config/default.js @@ -0,0 +1,18 @@ +/* + * Copyright 2021 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * default.js + */ + +module.exports = { + // URL to validator + "validatorUrl" : 'https://localhost:5050', + "gethUrl" : 'http://localhost:8545', + + // forCustomChain + "chainName": 'geth1', + "networkId": 10, + "chainId": 10 + +}; diff --git a/examples/electricity-trade/tools/transferNumericAsset/copyStaticAssets.ts b/examples/electricity-trade/tools/transferNumericAsset/copyStaticAssets.ts new file mode 100644 index 0000000000..ac50f79147 --- /dev/null +++ b/examples/electricity-trade/tools/transferNumericAsset/copyStaticAssets.ts @@ -0,0 +1,8 @@ +/* + * Copyright 2021 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * copyStaticAssets.ts + */ +import * as shell from 'shelljs'; +shell.cp('config/default.js', './dist/config'); diff --git a/examples/electricity-trade/tools/transferNumericAsset/package.json b/examples/electricity-trade/tools/transferNumericAsset/package.json new file mode 100644 index 0000000000..bd051d2b66 --- /dev/null +++ b/examples/electricity-trade/tools/transferNumericAsset/package.json @@ -0,0 +1,23 @@ +{ + "name": "transferNumericAsset", + "version": "0.0.0", + "private": true, + "scripts": { + "build": "npm run build-ts && npm run copy-static-assets", + "build-ts": "tsc", + "tslint": "tslint -c tslint.json -p tsconfig.json", + "copy-static-assets": "ts-node copyStaticAssets.ts" + }, + "dependencies": { + "@types/node": "^14.14.5", + "config": "^1.26.1", + "ethereumjs-common": "^1.5.1", + "ethereumjs-tx": "^2.1.2", + "ts-node": "^9.0.0", + "web3": "^1.2.9", + "socket.io": "^2.0.4" + }, + "devDependencies": { + "typescript": "^3.9.3" + } +} diff --git a/examples/electricity-trade/tools/transferNumericAsset/transferNumericAsset.ts b/examples/electricity-trade/tools/transferNumericAsset/transferNumericAsset.ts new file mode 100644 index 0000000000..a877a987c3 --- /dev/null +++ b/examples/electricity-trade/tools/transferNumericAsset/transferNumericAsset.ts @@ -0,0 +1,121 @@ +/* + * Copyright 2021 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * transferNumericAsset.ts + */ + +{ + + // Validator test program.(socket.io client) + var io = require('socket.io-client'); + var config = require('config'); + + // Specify the server (Validator) of the communication destination + var validatorUrl = config.validatorUrl; + console.log('validatorUrl: ' + validatorUrl); + var options = { + rejectUnauthorized: false, // temporary avoidance since self-signed certificates are used + reconnection : false, + timeout : 20000 + }; + var socket = io(validatorUrl, options); + + // ## Request for "transferNumericAsset" + if (process.argv.length !== 5) { + console.log('Number of parameters is abnormal.'); + process.exit(-1); + } + const paramAmount: number = parseInt(process.argv[4]); + if (Number.isNaN(paramAmount)) { + console.log(`Third parameter is not numeric. ${process.argv[4]}`); + process.exit(-1); + } + + console.log(`execution parameter : fromAddress = ${process.argv[2]}, toAddress = ${process.argv[3]}, amount = ${process.argv[4]}`); + + const fromAddress = process.argv[2]; + const toAddress = process.argv[3]; + const amount = paramAmount; + const reqID = "reqID_TNA_001"; + + // function param + const requestData = { + contract: {}, + method: { + type: "web3Eth", + command: "sendTransaction" + }, + args: { + "args": [ + { + "from" : fromAddress, + "to" : toAddress, + "value" : amount + } + ] + }, + reqID: reqID + }; + + const json2str = (jsonObj) => { + try { + return JSON.stringify(jsonObj); + } + catch (error) { + return null; + } + } + + socket.on('connect_error', (err) => { + console.log('####connect_error:', err); + // end communication + socket.disconnect(); + process.exit(0); + }); + + socket.on('connect_timeout', (err) => { + console.log('####Error:', err); + // end communication + socket.disconnect(); + process.exit(0); + }); + + socket.on('error', (err) => { + console.log('####Error:', err); + }); + + socket.on('eventReceived', function (res) { + // output the data received from the client + console.log('#[recv]eventReceived, res: ' + json2str(res)); + }); + + const requestStopMonitor = () => { + console.log('##exec requestStopMonitor()'); + socket.emit('stopMonitor'); + + setTimeout(function(){ + // end communication + socket.disconnect(); + process.exit(0); + },5000); + } + + // request StartMonitor + const requestStartMonitor = () => { + console.log('##exec requestStartMonitor()'); + socket.emit('startMonitor'); + + setTimeout(requestStopMonitor,15000); + } + + const sendRequest = () => { + console.log('exec sendRequest()'); + console.log('#[send]requestData: ' + json2str(requestData)); + socket.emit('request2', requestData); + } + + setTimeout(requestStartMonitor, 2000); + setTimeout(sendRequest, 4000); + +} diff --git a/examples/electricity-trade/tools/transferNumericAsset/tsconfig.json b/examples/electricity-trade/tools/transferNumericAsset/tsconfig.json new file mode 100644 index 0000000000..b0f7b49357 --- /dev/null +++ b/examples/electricity-trade/tools/transferNumericAsset/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "outDir": "./dist", + "sourceMap": false, + "declaration": false, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "target": "ES2017", + "module": "CommonJS", + "typeRoots": [ + "node_modules/@types", + "./typings" + ], + "lib": [ + "es2017", + "dom" + ] + }, + "include": [ + "./*.ts" + ], + "exclude": [ + "copyStaticAssets.ts" + ] +} diff --git a/packages/business-logic-plugin/BusinessLogicBase.ts b/packages/business-logic-plugin/BusinessLogicBase.ts index 6f9950066b..7b3d2b9a58 100644 --- a/packages/business-logic-plugin/BusinessLogicBase.ts +++ b/packages/business-logic-plugin/BusinessLogicBase.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * BusinessLogicBase.ts @@ -35,6 +35,11 @@ export class BusinessLogicBase implements BusinessLogicPlugin { return {}; } + setConfig(data: []): object { + // NOTE: This method implements the BisinessLogcPlugin operation(* Override by subclass) + return {}; + } + onEvent(ledgerEvent: LedgerEvent, targetIndex: number): void { // NOTE: This method implements the BisinessLogcPlugin operation(* Override by subclass) } diff --git a/packages/business-logic-plugin/BusinessLogicPlugin.ts b/packages/business-logic-plugin/BusinessLogicPlugin.ts index ac30fab6bd..dc93744640 100644 --- a/packages/business-logic-plugin/BusinessLogicPlugin.ts +++ b/packages/business-logic-plugin/BusinessLogicPlugin.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * BusinessLogicPlugin.ts @@ -11,6 +11,7 @@ import { VerifierEventListener, LedgerEvent } from '../ledger-plugin/LedgerPlugi export interface BusinessLogicPlugin { startTransaction(req: Request, businessLogicID: string, tradeID: string): void; getOperationStatus(tradeID: string): object; + setConfig(data: []): object; onEvent(ledgerEvent: LedgerEvent, targetIndex: number): void; getEventDataNum(ledgerEvent: LedgerEvent): number; getTxIDFromEvent(ledgerEvent: LedgerEvent, targetIndex: number): string | null; diff --git a/packages/business-logic-plugin/LedgerOperation.ts b/packages/business-logic-plugin/LedgerOperation.ts index 705e95e179..7769730d7b 100644 --- a/packages/business-logic-plugin/LedgerOperation.ts +++ b/packages/business-logic-plugin/LedgerOperation.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * LedgerOperation.ts diff --git a/packages/business-logic-plugin/app.ts b/packages/business-logic-plugin/app.ts index dbd1a6fe0e..4f5c0afd51 100644 --- a/packages/business-logic-plugin/app.ts +++ b/packages/business-logic-plugin/app.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * app.ts diff --git a/packages/config/BLP_config.ts b/packages/config/BLP_config.ts index fa0d9b2a1e..fe181b4809 100644 --- a/packages/config/BLP_config.ts +++ b/packages/config/BLP_config.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * BLP_config.ts diff --git a/packages/copyStaticAssets.ts b/packages/copyStaticAssets.ts index 76e94c2f22..d1ac6dad2c 100644 --- a/packages/copyStaticAssets.ts +++ b/packages/copyStaticAssets.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * copyStaticAssets.ts diff --git a/packages/jest.config.js b/packages/jest.config.js index d78a8ff1eb..c9929da97b 100644 --- a/packages/jest.config.js +++ b/packages/jest.config.js @@ -1,3 +1,10 @@ +/* + * Copyright 2020-2021 Hyperledger Cactus Contributors + * SPDX-License-Identifier: Apache-2.0 + * + * jest.config.js + */ + /* * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/en/configuration.html diff --git a/packages/ledger-plugin/DriverCommon.ts b/packages/ledger-plugin/DriverCommon.ts index 16cd16cbad..b82c6b7024 100644 --- a/packages/ledger-plugin/DriverCommon.ts +++ b/packages/ledger-plugin/DriverCommon.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * DriverCommon.ts diff --git a/packages/ledger-plugin/LedgerPlugin.ts b/packages/ledger-plugin/LedgerPlugin.ts index 03d0b659a6..b6f3185f65 100644 --- a/packages/ledger-plugin/LedgerPlugin.ts +++ b/packages/ledger-plugin/LedgerPlugin.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * LedgerPlugin.ts diff --git a/packages/ledger-plugin/ValidatorAuthentication.ts b/packages/ledger-plugin/ValidatorAuthentication.ts index f38e53a0d1..4ae768accb 100644 --- a/packages/ledger-plugin/ValidatorAuthentication.ts +++ b/packages/ledger-plugin/ValidatorAuthentication.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * ValidatorAuthentication.ts diff --git a/packages/ledger-plugin/VerifierAuthentication.ts b/packages/ledger-plugin/VerifierAuthentication.ts index 5fbe480208..d1fcf53cc0 100644 --- a/packages/ledger-plugin/VerifierAuthentication.ts +++ b/packages/ledger-plugin/VerifierAuthentication.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * VerifierAuthentication.ts diff --git a/packages/ledger-plugin/VerifierBase.test.ts b/packages/ledger-plugin/VerifierBase.test.ts index 06157f195d..955130f2ac 100644 --- a/packages/ledger-plugin/VerifierBase.test.ts +++ b/packages/ledger-plugin/VerifierBase.test.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * VerifierBase.test.ts diff --git a/packages/ledger-plugin/VerifierBase.ts b/packages/ledger-plugin/VerifierBase.ts index 081f9ca445..cb8bf4da23 100644 --- a/packages/ledger-plugin/VerifierBase.ts +++ b/packages/ledger-plugin/VerifierBase.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * VerifierBase.ts @@ -261,7 +261,7 @@ export class VerifierBase implements Verifier { }); } - startMonitor(): Promise { + startMonitor(options = {}): Promise { return new Promise((resolve, reject) => { logger.debug('call : startMonitor'); // NOTE: Start the event monitor for the Validator and enable event reception. @@ -334,7 +334,11 @@ export class VerifierBase implements Verifier { // save socket const sIndex: number = addSocket(socket); logger.debug("##emit: startMonitor"); - socket.emit('startMonitor') + if (Object.keys(options).length === 0) { + socket.emit('startMonitor'); + } else { + socket.emit('startMonitor', options); + } const ledgerEvent: LedgerEvent = new LedgerEvent(); ledgerEvent.id = String(sIndex); logger.debug(`##startMonitor, ledgerEvent.id = ${ledgerEvent.id}`); diff --git a/packages/routing-interface/AssetManagement.ts b/packages/routing-interface/AssetManagement.ts index d6d35fc484..9fed6665d2 100644 --- a/packages/routing-interface/AssetManagement.ts +++ b/packages/routing-interface/AssetManagement.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * AssetManagement.ts diff --git a/packages/routing-interface/BalanceManagement.ts b/packages/routing-interface/BalanceManagement.ts index d82d3229ea..793fe66ec1 100644 --- a/packages/routing-interface/BalanceManagement.ts +++ b/packages/routing-interface/BalanceManagement.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * BalanceManagement.ts diff --git a/packages/routing-interface/CarsManagement.ts b/packages/routing-interface/CarsManagement.ts index f64601f4f4..17b9e7e736 100644 --- a/packages/routing-interface/CarsManagement.ts +++ b/packages/routing-interface/CarsManagement.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * CarsManagement.ts diff --git a/packages/routing-interface/RIFError.ts b/packages/routing-interface/RIFError.ts index d94add163a..6bafb42db2 100644 --- a/packages/routing-interface/RIFError.ts +++ b/packages/routing-interface/RIFError.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * RIFError.ts diff --git a/packages/routing-interface/RequestInfo.ts b/packages/routing-interface/RequestInfo.ts index 7dffbf5dcf..7fa9ecd690 100644 --- a/packages/routing-interface/RequestInfo.ts +++ b/packages/routing-interface/RequestInfo.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * RequestInfo.ts diff --git a/packages/routing-interface/TradeInfo.ts b/packages/routing-interface/TradeInfo.ts index 28fe6de18e..d245649bda 100644 --- a/packages/routing-interface/TradeInfo.ts +++ b/packages/routing-interface/TradeInfo.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * TradeInfo.ts diff --git a/packages/routing-interface/TransactionManagement.ts b/packages/routing-interface/TransactionManagement.ts index f5aa2d9e8c..7d35d0d5d1 100644 --- a/packages/routing-interface/TransactionManagement.ts +++ b/packages/routing-interface/TransactionManagement.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * TransactionManagement.ts @@ -110,6 +110,35 @@ export class TransactionManagement { } + // Set business logic config + setBusinessLogicConfig(req: Request): object { + + // businessLogicID + const businessLogicID = req.body.businessLogicID; + logger.info(`businessLogicID: ${businessLogicID}`); + + // object judgment + let result: {} = {}; + if (businessLogicID === "h40Q9eMD") { + + const blp = getTargetBLPInstance(businessLogicID); + if (blp === null) { + logger.warn(`##startBusinessLogic(): not found BusinessLogicPlugin. businessLogicID: ${businessLogicID}`); + return; + } + + logger.debug("created instance"); + + // Set business logic config + logger.debug(`meterParams = ${req.body.meterParams}`); + result = blp.setConfig(req.body.meterParams); + logger.debug("set business logic config"); + } + + return result; + } + + // Get Verifier getVerifier(validatorId: string, monitorOptions = {}): VerifierBase { diff --git a/packages/routing-interface/routes/asset.ts b/packages/routing-interface/routes/asset.ts index 34edd4832a..903a6394b2 100644 --- a/packages/routing-interface/routes/asset.ts +++ b/packages/routing-interface/routes/asset.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * asset.ts diff --git a/packages/routing-interface/routes/balance.ts b/packages/routing-interface/routes/balance.ts index ab66bba3eb..683c5c16c2 100644 --- a/packages/routing-interface/routes/balance.ts +++ b/packages/routing-interface/routes/balance.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * balance.ts diff --git a/packages/routing-interface/routes/cars.ts b/packages/routing-interface/routes/cars.ts index e818efca35..e5ec472405 100644 --- a/packages/routing-interface/routes/cars.ts +++ b/packages/routing-interface/routes/cars.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * cars.ts diff --git a/packages/routing-interface/routes/electricity-trade.ts b/packages/routing-interface/routes/electricity-trade.ts index 8006790e1b..048221b891 100644 --- a/packages/routing-interface/routes/electricity-trade.ts +++ b/packages/routing-interface/routes/electricity-trade.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * electricity-trade.ts @@ -40,15 +40,15 @@ router.post('/', (req: Request, res: Response, next: NextFunction) => { } }); -// Show Current Status of Trade -router.get('/:account', (req: Request, res: Response, next: NextFunction) => { - - res.status(200).json({"message": "Not implemented"}); - -/* +// Request Execution of Trade +router.post('/meter/register/', (req: Request, res: Response, next: NextFunction) => { try { - const result = transactionManagement.getOperationStatus(req.params.id); - res.status(200).json(result); + const result: object = transactionManagement.setBusinessLogicConfig(req); + let status: number = 200; + if (result['action'] === "add") { + status = 201; + } + res.status(status).json(result); } catch (err) { if (err instanceof RIFError) { @@ -59,8 +59,6 @@ router.get('/:account', (req: Request, res: Response, next: NextFunction) => { next(err); } -*/ - }); export default router; diff --git a/packages/routing-interface/routes/index.ts b/packages/routing-interface/routes/index.ts index 699046b527..d7596532c2 100644 --- a/packages/routing-interface/routes/index.ts +++ b/packages/routing-interface/routes/index.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * index.ts diff --git a/packages/routing-interface/routes/login.ts b/packages/routing-interface/routes/login.ts index 6832df0562..2582cd679c 100644 --- a/packages/routing-interface/routes/login.ts +++ b/packages/routing-interface/routes/login.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * login.ts diff --git a/packages/routing-interface/routes/trades.ts b/packages/routing-interface/routes/trades.ts index bb0b5fa48f..0e5abdb9b7 100644 --- a/packages/routing-interface/routes/trades.ts +++ b/packages/routing-interface/routes/trades.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * trades.ts diff --git a/packages/routing-interface/util/BLPRegistry.ts b/packages/routing-interface/util/BLPRegistry.ts index 7bb47067a6..7bb41b88d5 100644 --- a/packages/routing-interface/util/BLPRegistry.ts +++ b/packages/routing-interface/util/BLPRegistry.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * BLPRegistry.ts diff --git a/packages/routing-interface/util/ConfigUtil.ts b/packages/routing-interface/util/ConfigUtil.ts index 27528f5bb6..bb43b1b1a0 100644 --- a/packages/routing-interface/util/ConfigUtil.ts +++ b/packages/routing-interface/util/ConfigUtil.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * ConfigUtil.ts diff --git a/packages/routing-interface/util/ContractInfoHolder.ts b/packages/routing-interface/util/ContractInfoHolder.ts index 8c47f33ffb..14a06ab774 100644 --- a/packages/routing-interface/util/ContractInfoHolder.ts +++ b/packages/routing-interface/util/ContractInfoHolder.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * ContractInfoHolder.ts diff --git a/packages/routing-interface/util/DBAccess.ts b/packages/routing-interface/util/DBAccess.ts index 8642854635..9c5ebe873c 100644 --- a/packages/routing-interface/util/DBAccess.ts +++ b/packages/routing-interface/util/DBAccess.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * DBAccess.ts diff --git a/packages/routing-interface/util/LPInfoHolder.ts b/packages/routing-interface/util/LPInfoHolder.ts index 057d46b63e..494190a521 100644 --- a/packages/routing-interface/util/LPInfoHolder.ts +++ b/packages/routing-interface/util/LPInfoHolder.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * LPInfoHolder.ts diff --git a/packages/routing-interface/util/RIFUtil.test.ts b/packages/routing-interface/util/RIFUtil.test.ts index fda08ff87a..900094c59a 100644 --- a/packages/routing-interface/util/RIFUtil.test.ts +++ b/packages/routing-interface/util/RIFUtil.test.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * RIFUtil.test.ts diff --git a/packages/routing-interface/util/RIFUtil.ts b/packages/routing-interface/util/RIFUtil.ts index b782a07e6d..443a5c049d 100644 --- a/packages/routing-interface/util/RIFUtil.ts +++ b/packages/routing-interface/util/RIFUtil.ts @@ -1,5 +1,5 @@ /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * RIFUtil.ts @@ -43,7 +43,7 @@ export class RIFUtil { return JSON.parse(jsonStr); } catch (error) { - logger.error(error) + // logger.error(error) return null; } } diff --git a/packages/routing-interface/www.ts b/packages/routing-interface/www.ts index 264eb742aa..d4bb0d0d85 100644 --- a/packages/routing-interface/www.ts +++ b/packages/routing-interface/www.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node /* - * Copyright 2020 Hyperledger Cactus Contributors + * Copyright 2020-2021 Hyperledger Cactus Contributors * SPDX-License-Identifier: Apache-2.0 * * www.ts