Skip to content

Commit

Permalink
feat(cactus-workshop-examples): add hello-world
Browse files Browse the repository at this point in the history
 Co-authored-by: Monica Gomez <monicasrgomez@gmail.com>

Signed-off-by: Rafael Belchior <rafael.belchior@tecnico.ulisboa.pt>
  • Loading branch information
RafaelAPB committed Nov 14, 2022
1 parent f7a172b commit 3ba2ff4
Show file tree
Hide file tree
Showing 4 changed files with 247 additions and 14 deletions.
61 changes: 53 additions & 8 deletions examples/cactus-workshop-examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,63 @@

This folder contains several simple examples using different components of Hyperledger Cacti that are used in the first Hyperledger workshop dedicated to interoperability, using Cacti: https://wiki.hyperledger.org/display/events/Blockchain+Interoperability+with+Hyperledger+Cacti

## Hyperledger Cacti Workshop Examples - Hello World
WARNING: This code IS NOT production-ready nor secure! Namely, cross-site scripting is possible if user input is not sanitized.

#### Hyperledger Cacti Workshop Examples - Substrate test ledger
src/main/typescript/test-ledger.ts
``src/main/typescript/hello-world.ts``

Creates an APIServer and a Keychain Memory client. The server interacts with the key pairs in the Keychain Memory.

#### Hyperledger Cacti Workshop Examples - Hello World
src/main/typescript/hello-world.ts
Runs with the following command ``npx ts-node src/main/typescript/hello-world.ts``

### Running the examples:
The implemented interactions are:
- POST "/set-kcm", which sets a new key-value pair.
```
curl --header "Content-Type: application/json" \
--request POST \
--data '{"key":"1234","value":"xyz"}' \
http://localhost:8000/set-kcm
```
- GET "/get-kcm/:key", which gets a key-value pair.
```
curl --header "Content-Type: application/json" \
--request GET \
--data '{"key":"1234"}' \
http://localhost:8000/get-kcm/1234
```
- DELETE "/delete/:key", which deletes a key-value pair.
```
curl --header "Content-Type: application/json" \
--request POST \
--data '{"key":"1234"}' \
http://localhost:8000/delete-kcm/1234
```
- GET "/has-key/:key", which checks if a key-value pair exits in the client.
```
curl --header "Content-Type: application/json" \
--request GET \
--data '{"key":"1234"}' \
http://localhost:8000/has-key/1234
```
Set a breakpoint and run the "TAP: Current TS File" runner provided in .vscode/.launch
## Hyperledger Cacti Workshop Examples - Simple Consortium
Alternatively run: ``npx ts-node src/main/typescript/[NAME_OF_EXAMPLE].ts``
``src/main/typescript/test-ledger.ts``
E.g. ``npx ts-node src/main/typescript/hello-world.ts``
Creates a simple Cacti Consortium.
Runs with the following command ``npx ts-node src/main/typescript/simple-consortium.ts``
## Hyperledger Cacti Workshop Examples - Substrate test ledger
``src/main/typescript/test-ledger.ts``
Creates a substrate test ledger programmatically.
Runs with the following command ``npx ts-node src/main/typescript/test-ledger.ts``
## Authors
- Rafael Belchior
- Mónica Gomez
- Abhinav Srivastava
13 changes: 8 additions & 5 deletions examples/cactus-workshop-examples/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@hyperledger/cactus-workshop-examples",
"version": "1.1.0",
"description": "Cacti workshop - hello world",
"version": "1.0.0",
"description": "Cacti Workshop Examples",
"keywords": [
"Hyperledger",
"Cactus",
Expand Down Expand Up @@ -32,6 +32,10 @@
{
"name": "Rafael Belchior",
"email": "rbelchior@blockdaemon.com"
},
{
"name": "Mónica Gomez",
"email": "monica.gomez@tecnico.ulisboa.pt"
}
],
"main": "dist/lib/main/typescript/index.js",
Expand All @@ -51,9 +55,8 @@
"dependencies": {
"@hyperledger/cactus-common": "1.1.2",
"@hyperledger/cactus-core": "1.1.2",
"@hyperledger/cactus-test-tooling": "1.1.2",
"typescript-optional": "2.0.1",
"uuid": "8.3.2"
"@hyperledger/cactus-test-tooling": "1.0.0",
"typescript-optional": "2.0.1"
},
"devDependencies": {
},
Expand Down
146 changes: 145 additions & 1 deletion examples/cactus-workshop-examples/src/main/typescript/hello-world.ts
Original file line number Diff line number Diff line change
@@ -1 +1,145 @@
//todo
// WARNING: This code IS NOT production-ready nor secure! Namely, cross-site scripting is possible if user input is not sanitized.
import { ApiServer, ConfigService } from "@hyperledger/cactus-cmd-api-server";
import { Logger, LoggerProvider } from "@hyperledger/cactus-common";
import {
PluginImportAction,
PluginImportType,
} from "@hyperledger/cactus-core-api";
import express, { Request, Response } from "express";
import cors from "cors";
import bodyParser from "body-parser";
import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory";

const log: Logger = LoggerProvider.getOrCreate({
label: "cacti-node-test-app",
level: "info",
});

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const PORT = 8000;

const main = async () => {
// Handling GET / Request
app.get("/", (req: Request, res: Response) => {
log.info("Cacti: Hello World");
res.send("Welcome to the Hello World server!");
});

// Server port setup
app.listen(PORT, () => {
log.info(`Application running on port ${PORT}`);
console.log(
"The application is listening " + "on port http://localhost:" + PORT,
);
});

//Configuring APIServer
const configService = new ConfigService();
const apiServerOptions: any = await configService.newExampleConfig();
apiServerOptions.configFile = "";
apiServerOptions.authorizationProtocol = "NONE";
apiServerOptions.apiPort = 3001;
apiServerOptions.cockpitPort = 3100;
apiServerOptions.grpcPort = 5000;
apiServerOptions.apiTlsEnabled = true; //Disable TLS (or provide TLS certs for secure HTTP if you are deploying to production)
apiServerOptions.plugins = [
//Hyperledger cacti add plugin keychain-aws-sm
{
packageName: "@hyperledger/cactus-plugin-keychain-memory",
type: PluginImportType.Remote,
action: PluginImportAction.Install,
options: {
instanceId: "keychain",
keychainId: "1",
},
},
];
const config = await configService.newExampleConfigConvict(apiServerOptions);

//Creating Cacti APIServer
const apiServer = new ApiServer({
config: config.getProperties(),
});

//Starting the Cacti APIServer
apiServer.start();
};

const client = async () => {
//Creating keychain memory client
const apiClient = new PluginKeychainMemory({
instanceId: "keychain",
keychainId: "1",
logLevel: "info",
});

//Setting a key value pair
app.post("/set-kcm", async (req: Request, res: Response) => {
const key = req.body.key;
const value = req.body.value;
try {
// TODO Security: Sanitize user input
await apiClient.set(key, value);
log.info("Key value pair set; Key: " + key + " Value: " + value);
res.status(201).end();
} catch (err: any) {
res.status(404).send("error setting key");
}
});

//Getting a key value pair
app.get("/get-kcm/:key", async (req: Request, res: Response) => {
try {
const { key } = req.params;
// TODO Security: Sanitize user input
const response = await apiClient.get(key);
log.info("Got key-value pair: (" + key + ", " + response + ")");
res.end(response);
} catch (err: any) {
res.status(404).send("error getting key");
}
});

//Deleting a key value pair
app.post("/delete-kcm/:key", async (req: Request, res: Response) => {
try {
const { key } = req.params;
// TODO Security: Sanitize user input
await apiClient.delete(key);
log.info("Deleted key: " + key);
res.status(200).end();
} catch (err: unknown) {
res.status(404).send("error deleting key");
}
});

//Checking if a specific key exists
app.get("/has-key/:key", async (req: Request, res: Response) => {
try {
const { key } = req.params;
const response = await apiClient.has(key);
log.info("Key exists? " + response);
res.status(200).send(response);
} catch (err: unknown) {
res.status(404).send("error checking existence of key");
}
});
};

export async function launchApp(): Promise<void> {
try {
await main();
await client();
log.info(`Cacti Keychain example ran OK `);
} catch (ex) {
log.error(`Cacti Keychain example crashed: `, ex);
process.exit(1);
}
}

if (require.main === module) {
launchApp();
}
41 changes: 41 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2814,6 +2814,47 @@
secp256k1 "4.0.2"
sha3 "2.1.4"

"@hyperledger/cactus-common@1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@hyperledger/cactus-common/-/cactus-common-1.0.0.tgz#c1adfc4bac84b1c45ed4ef3392105f4f0b27d768"
integrity sha512-8PrvfHJCXRyhnHCXCMlXMbq2fmxSozTvOWnCW1zUyX46qko8vF+lp1XYFRvAsC0Xr02PcMZqTjlHhg7FnpslhQ==
dependencies:
json-stable-stringify "1.0.1"
key-encoder "2.0.3"
loglevel "1.7.1"
loglevel-plugin-prefix "0.8.4"
secp256k1 "4.0.2"
sha3 "2.1.4"

"@hyperledger/cactus-test-tooling@1.0.0":
version "1.0.0"
resolved "https://registry.yarnpkg.com/@hyperledger/cactus-test-tooling/-/cactus-test-tooling-1.0.0.tgz#113bdadaaa78323a3b3c728552b95190ce245943"
integrity sha512-kSpWBznc/KSCKOptChD6lDdeHRBysBsUX1czKrGthT18RGtc4G5x5K9LKbG4a8UU8/cE4CBa894ErEEloRMQCg==
dependencies:
"@hyperledger/cactus-common" "1.0.0"
axios "0.21.4"
compare-versions "3.6.0"
dockerode "3.3.0"
elliptic "6.5.4"
execa "5.1.1"
fabric-ca-client "2.2.10"
fabric-network "2.2.10"
fs-extra "10.0.0"
internal-ip "6.2.0"
is-port-reachable "3.0.0"
joi "17.4.2"
js-yaml "4.1.0"
keycloak-admin "1.14.21"
lodash "4.17.21"
node-ssh "12.0.0"
p-retry "4.6.1"
run-time-error "1.4.0"
tar-stream "2.2.0"
temp "0.9.4"
typescript-optional "2.0.1"
web3 "1.5.2"
web3-core "1.5.2"

"@improbable-eng/grpc-web-node-http-transport@^0.13.0":
version "0.13.0"
resolved "https://registry.yarnpkg.com/@improbable-eng/grpc-web-node-http-transport/-/grpc-web-node-http-transport-0.13.0.tgz#a8680c7a8bce4c2b44fe48ba4b7c55b320cf5f54"
Expand Down

0 comments on commit 3ba2ff4

Please sign in to comment.