Skip to content

Commit

Permalink
feat(cactus-example-discounted-asset-trade): use openapi sawtooth con…
Browse files Browse the repository at this point in the history
…nector

- Refactor discounted asset trade sample to use openapi sawtooth connector
    instead of sawtooth-socketio.
- Remove sawtooth-socketio connector since it's not used any more.

Depends on: #2825

Signed-off-by: Michal Bajer <michal.bajer@fujitsu.com>
  • Loading branch information
outSH authored and petermetz committed Nov 3, 2023
1 parent 63e5702 commit 86d6b38
Show file tree
Hide file tree
Showing 30 changed files with 186 additions and 1,380 deletions.
1 change: 0 additions & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,6 @@
"**/src/main/typescript/generated/**",
"packages/cactus-plugin-verifier-cc/**",
"packages/cactus-cmd-socketio-server/**",
"packages/cactus-plugin-ledger-connector-sawtooth-socketio/**",
"packages/cactus-plugin-ledger-connector-go-ethereum-socketio/**",
"packages/cactus-plugin-ledger-connector-*-socketio/**"
]
Expand Down
1 change: 0 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
packages/cactus-verifier/src/main/typescript/

packages/cactus-cmd-socketio-server/**
packages/cactus-plugin-ledger-connector-sawtooth-socketio/**
packages/cactus-plugin-ledger-connector-go-ethereum-socketio/**
packages/cactus-plugin-ledger-connector-*-socketio/**

Expand Down
26 changes: 0 additions & 26 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1359,32 +1359,6 @@ jobs:
with:
node-version: v16.14.2
- uses: actions/checkout@v3.5.2
- id: yarn-cache
name: Restore Yarn Cache
uses: actions/cache@v3.3.1
with:
key: ${{ runner.os }}-yarn-${{ hashFiles('./yarn.lock') }}
path: ./.yarn/
restore-keys: |
${{ runner.os }}-yarn-${{ hashFiles('./yarn.lock') }}
- run: ./tools/ci.sh
cactus-plugin-ledger-connector-sawtooth-socketio:
continue-on-error: false
env:
DEV_BUILD_DISABLED: false
FULL_BUILD_DISABLED: true
JEST_TEST_PATTERN: packages/cactus-plugin-ledger-connector-sawtooth-socketio/src/test/typescript/(unit|integration|benchmark)/.*/*.test.ts
JEST_TEST_RUNNER_DISABLED: true
TAPE_TEST_RUNNER_DISABLED: true
needs: build-dev
runs-on: ubuntu-20.04
steps:
- name: Use Node.js v16.14.2
uses: actions/setup-node@v3.6.0
with:
node-version: v16.14.2
- uses: actions/checkout@v3.5.2

- id: yarn-cache
name: Restore Yarn Cache
uses: actions/cache@v3.3.1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,42 +10,25 @@ import { RequestInfo } from "./RequestInfo";
import { MeterManagement } from "./MeterManagement";
import { MeterInfo } from "./MeterInfo";
import {
TradeInfo,
routesTransactionManagement,
BusinessLogicBase,
LedgerEvent,
json2str,
ConfigUtil,
LPInfoHolder,
} from "@hyperledger/cactus-cmd-socketio-server";
import { sendEthereumTransaction } from "./TransactionEthereum";

const config: any = ConfigUtil.getConfig() as any;
import { getLogger } from "log4js";
import { getSawtoothApiClient } from "./sawtooth-connector";
import {
VerifierFactory,
VerifierFactoryConfig,
} from "@hyperledger/cactus-verifier-client";
isWatchBlocksV1CactiTransactionsResponse,
WatchBlocksV1ListenerType,
WatchBlocksV1Progress,
} from "@hyperledger/cactus-plugin-ledger-connector-sawtooth";

const moduleName = "BusinessLogicElectricityTrade";
const logger = getLogger(`${moduleName}`);
logger.level = config.logLevel;
const connectInfo = new LPInfoHolder();
const routesVerifierFactory = new VerifierFactory(
connectInfo.ledgerPluginInfo as VerifierFactoryConfig,
config.logLevel,
);

interface SawtoothEventData {
status: number | string;
blockData: [];
}

interface SawtoothBlockDataData {
header_signature: string;
hash: string;
payload_decoded: { Verb: string; Name: string; Value: string }[];
}

export class BusinessLogicElectricityTrade extends BusinessLogicBase {
businessLogicID: string;
Expand All @@ -71,39 +54,54 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase {
// set TradeID
requestInfo.setTradeID(tradeID);

// Create trade information
const tradeInfo: TradeInfo = new TradeInfo(
requestInfo.businessLogicID,
requestInfo.tradeID,
);

this.startMonitor(tradeInfo);
this.startSawtoothMonitor();
}

startMonitor(tradeInfo: TradeInfo): void {
// Get Verifier Instance
logger.debug(
`##startMonitor(): businessLogicID: ${tradeInfo.businessLogicID}`,
);
const useValidator = JSON.parse(
routesTransactionManagement.getValidatorToUse(tradeInfo.businessLogicID),
);
logger.debug(
`filterKey: ${config.electricityTradeInfo.sawtooth.filterKey}`,
);
const options = {
filterKey: config.electricityTradeInfo.sawtooth.filterKey,
};
// const verifierSawtooth = transactionManagement.getVerifier(useValidator['validatorID'][0], options);
const verifierSawtooth = routesVerifierFactory.getVerifier(
useValidator["validatorID"][0],
);
verifierSawtooth.startMonitor(
"BusinessLogicElectricityTrade",
options,
routesTransactionManagement,
);
logger.debug("getVerifierSawtooth");
startSawtoothMonitor(): void {
// Start monitoring
const sawtoothApiClient = getSawtoothApiClient();
const watchObservable = sawtoothApiClient.watchBlocksV1({
type: WatchBlocksV1ListenerType.CactiTransactions,
txFilterBy: {
family_name: config.electricityTradeInfo.sawtooth.filterKey,
},
});
watchObservable.subscribe({
next: (event: WatchBlocksV1Progress) => {
logger.debug(`##in onEventSawtooth()`);

if (!isWatchBlocksV1CactiTransactionsResponse(event)) {
logger.error("Wrong input block format!", event);
return;
}

for (const tx of event.cactiTransactionsEvents) {
try {
const txId = tx.header_signature;
logger.debug(`##txId = ${txId}`);

const txPayload = tx.payload_decoded[0];
if (txPayload && txPayload.Verb !== "set") {
this.remittanceTransaction({
Name: txPayload.Name,
Value: txPayload.Value,
Verb: txPayload.Verb,
});
}
} catch (err) {
logger.error(
`##onEventSawtooth(): onEvent, err: ${err}, event: ${JSON.stringify(
tx,
)}`,
tx,
);
}
}
},
error(err: unknown) {
logger.error("Sawtooth watchBlocksV1() error:", err);
},
});
}

remittanceTransaction(transactionSubset: Record<string, string>): void {
Expand Down Expand Up @@ -144,158 +142,17 @@ export class BusinessLogicElectricityTrade extends BusinessLogicBase {
}

onEvent(ledgerEvent: LedgerEvent, targetIndex: number): void {
logger.debug(`##in BLP:onEvent()`);
logger.debug(
`##onEvent(): ${json2str(ledgerEvent["data"]["blockData"][targetIndex])}`,
logger.error(
"onEvent() ERROR - No monitors are running, should not be called!",
);

switch (ledgerEvent.verifierId) {
case config.electricityTradeInfo.sawtooth.validatorID:
this.onEventSawtooth(ledgerEvent.data, targetIndex);
break;
default:
logger.error(
`##onEvent(), invalid verifierId: ${ledgerEvent.verifierId}`,
);
return;
}
}

onEventSawtooth(event: SawtoothEventData, targetIndex: number): void {
logger.debug(`##in onEventSawtooth()`);
const tx = this.getTransactionFromSawtoothEvent(event, targetIndex);
if (tx == null) {
logger.error(`##onEventSawtooth(): invalid event: ${json2str(event)}`);
return;
}

try {
const txId = tx["header_signature"];
logger.debug(`##txId = ${txId}`);

if (tx["payload_decoded"][0].Verb !== "set") {
const transactionSubset = {
Name: tx["payload_decoded"][0].Name,
Value: tx["payload_decoded"][0].Value,
Verb: tx["payload_decoded"][0].Verb,
};
this.remittanceTransaction(transactionSubset);
}
} catch (err) {
logger.error(
`##onEventSawtooth(): err: ${err}, event: ${json2str(event)}`,
);
}
}

getTransactionFromSawtoothEvent(
event: SawtoothEventData,
targetIndex: number | string,
): SawtoothBlockDataData | undefined {
try {
if (typeof targetIndex === "number") {
const retTransaction = event["blockData"][targetIndex];

logger.debug(
`##getTransactionFromSawtoothEvent(), retTransaction: ${retTransaction}`,
);
return retTransaction;
}
} catch (err) {
logger.error(
`##getTransactionFromSawtoothEvent(): invalid even, err:${err}, event:${event}`,
);
}
return;
}

getOperationStatus(): Record<string, unknown> {
logger.debug(`##in getOperationStatus()`);
return {};
}

getTxIDFromEvent(
ledgerEvent: LedgerEvent,
targetIndex: number,
): string | null {
logger.debug(`##in getTxIDFromEvent`);
// logger.debug(`##event: ${json2str(ledgerEvent)}`);

switch (ledgerEvent.verifierId) {
case config.electricityTradeInfo.sawtooth.validatorID:
return this.getTxIDFromEventSawtooth(ledgerEvent.data, targetIndex);
default:
logger.error(
`##getTxIDFromEvent(): invalid verifierId: ${ledgerEvent.verifierId}`,
);
}
return null;
}

getTxIDFromEventSawtooth(
event: SawtoothEventData,
targetIndex: number | string,
): string | null {
logger.debug(`##in getTxIDFromEventSawtooth()`);
const tx = this.getTransactionFromSawtoothEvent(event, targetIndex);
if (tx == null) {
logger.warn(`#getTxIDFromEventSawtooth(): skip(not found tx)`);
return null;
}

try {
const txId = tx["header_signature"];

if (typeof txId !== "string") {
logger.warn(
`#getTxIDFromEventSawtooth(): skip(invalid block, not found txId.), event: ${json2str(
event,
)}`,
);
return null;
}

logger.debug(`###getTxIDFromEventSawtooth(): txId: ${txId}`);
return txId;
} catch (err) {
logger.error(
`##getTxIDFromEventSawtooth(): err: ${err}, event: ${json2str(event)}`,
);
return null;
}
}

getEventDataNum(ledgerEvent: LedgerEvent): number {
logger.debug(
`##in BLP:getEventDataNum(), ledgerEvent.verifierId: ${ledgerEvent.verifierId}`,
);
const event = ledgerEvent.data;
let retEventNum = 0;

try {
logger.error(ledgerEvent.data);

switch (ledgerEvent.verifierId) {
case config.electricityTradeInfo.sawtooth.validatorID:
retEventNum = event["blockData"].length;
break;
default:
logger.error(
`##getEventDataNum(): invalid verifierId: ${ledgerEvent.verifierId}`,
);
break;
}
logger.debug(
`##getEventDataNum(): retEventNum: ${retEventNum}, verifierId: ${ledgerEvent.verifierId}`,
);
return retEventNum;
} catch (err) {
logger.error(
`##getEventDataNum(): invalid even, err: ${err}, event: ${event}`,
);
return 0;
}
}

getAccountInfo(
transactionSubset: Record<string, string>,
): Record<string, string> {
Expand Down
11 changes: 0 additions & 11 deletions examples/cactus-example-electricity-trade/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ In this example, we use the Sawtooth intkey transaction processor as an applicat

## Prerequisites

- Available ports:
- `5034`: the port of `cactus-cmd-socketio-server`
- `5140`: the port of `cactus-plugin-ledger-connector-sawtooth-socketio`
- You can modify port exported to the host in `./docker-compose.yml`
- Available directory (This directory must be empty):
- `./etc/cactus`: the directory for storing the config files of `cactus-cmd-socketio-server`, will be mounted by the containers.

Expand Down Expand Up @@ -59,11 +55,6 @@ In this example, we use the Sawtooth intkey transaction processor as an applicat
```
cmd-socketio-base-dummy | OK - Exit
cmd-socketio-base-dummy exited with code 0
cactus-example-electricity-trade-sawtooth-validator |
cactus-example-electricity-trade-sawtooth-validator | > @hyperledger/cactus-plugin-ledger-connector-sawtooth-socketio@1.0.0-rc.3 start /root/cactus
cactus-example-electricity-trade-sawtooth-validator | > cd ./dist && node common/core/bin/www.js
cactus-example-electricity-trade-sawtooth-validator |
cactus-example-electricity-trade-sawtooth-validator | listening on *:5140
cactus-example-electricity-trade-blp | [2022-02-14T15:47:47.312] [INFO] www - Using BLP with id = h40Q9eMD
cactus-example-electricity-trade-blp | start Dynamic loading.
cactus-example-electricity-trade-blp | path: /api/v1/bl/cactus-example-electricity-trade/, routerJs: /root/cactus/dist/cactus-example-electricity-trade.js
Expand All @@ -77,8 +68,6 @@ For development purposes, it might be useful to run the sample application outsi

1. Configure cactus and start the ledgers as described above.
1. Run `./script-dockerless-config-patch.sh` from `cactus-example-electricity-trade/` directory. This will patch the configs and copy it to global location.
1. Start sawtooth validators (in separate cmd window, ethereum connector started as part of BLP).
1. `cd packages/cactus-plugin-ledger-connector-sawtooth-socketio/ && npm run start`
1. Start electricity-trade: `npm run start-dockerless`

## How to use this application
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
blpRegistry:
-
businessLogicID: h40Q9eMD
validatorID: [sUr7d10R]
validatorID: []

logLevel: debug

Expand All @@ -24,10 +24,9 @@ appRouters:
# BLP Config
electricityTradeInfo:
sawtooth:
validatorID: sUr7d10R
filterKey: intkey
restApiURL: http://localhost:8008
ethereum:
validatorID: 84jUisrs
gethURL: ws://localhost:8546
chainName: geth1
networkID: 10
Expand Down
Loading

0 comments on commit 86d6b38

Please sign in to comment.