Skip to content

Commit

Permalink
working cluster implementation
Browse files Browse the repository at this point in the history
Signed-off-by: vikastc <vikas.tc@dhiway.com>
  • Loading branch information
Vikastc committed Sep 7, 2023
1 parent 9e43a50 commit d42b447
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 110 deletions.
10 changes: 5 additions & 5 deletions src/controller/credential_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ export async function issueVC(

const url: any = WALLET_URL;

if (url) {
if (url && data.type) {
await fetch(`${url}/message/${holderDidUri}`, {
body: JSON.stringify({
id: data.id,
Expand Down Expand Up @@ -228,6 +228,7 @@ export async function revokeCred(req: express.Request, res: express.Response) {

export async function updateCred(req: express.Request, res: express.Response) {
const data = req.body;

try {
let schemaProp: any = undefined;
let credProp: any = undefined;
Expand Down Expand Up @@ -270,18 +271,17 @@ export async function updateCred(req: express.Request, res: express.Response) {
issuerKeys
);


credProp.identifier = updatedDocument.identifier;
credProp.credential = JSON.stringify(updatedDocument);
credProp.hash = updatedDocument.documentHash;
credProp.details = {
meta: "endpoint-received",
};

await getConnection().manager.save(credProp);

console.log("\n✅ Document updated!");

return res.status(200).json({
result: "Updated successufully",
identifier: credProp.identifier,
Expand Down
72 changes: 36 additions & 36 deletions src/controller/schema_controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,54 +17,54 @@ export async function createSchema(
req: express.Request,
res: express.Response
) {
const data = req.body;
let schemaDetails: any = undefined;
try {
const data = req.body;
let schemaDetails: any = undefined;

if (!issuerDid) {
await setupDidAndIdentities();
}
if (!issuerDid) {
await setupDidAndIdentities();
}

if (!data.schema || !data.schema.properties) {
return res.status(400).json({
error:
"'schema' is a required field in the form of key-value pair, with title and description",
});
}
if (!data.schema || !data.schema.properties) {
return res.status(400).json({
error:
"'schema' is a required field in the form of key-value pair, with title and description",
});
}

schemaDetails = await ensureStoredSchema(
authorIdentity,
issuerDid.uri,
async ({ data }) => ({
signature: issuerKeys.assertionMethod.sign(data),
keyType: issuerKeys.assertionMethod.type,
}),
req,
res
);
schemaDetails = await ensureStoredSchema(
authorIdentity,
issuerDid.uri,
async ({ data }) => ({
signature: issuerKeys.assertionMethod.sign(data),
keyType: issuerKeys.assertionMethod.type,
}),
req,
res
);

if (schemaDetails) {
const schemaData = new Schema();
schemaData.title = data.schema.title ? data.schema.title : "";
schemaData.description = data.schema.description
? data.schema.description
: "";
schemaData.schemaProperties = JSON.stringify(data.schema.properties);
schemaData.cordSchema = JSON.stringify(schemaDetails);
schemaData.identifier = schemaDetails.$id;
if (schemaDetails) {
const schemaData = new Schema();
schemaData.title = data.schema.title ? data.schema.title : "";
schemaData.description = data.schema.description
? data.schema.description
: "";
schemaData.schemaProperties = JSON.stringify(data.schema.properties);
schemaData.cordSchema = JSON.stringify(schemaDetails);
schemaData.identifier = schemaDetails.$id;

try {
await getConnection().manager.save(schemaData);
return res.status(200).json({
result: "SUCCESS",
schemaId: schemaData.id,
identifier: schemaData.identifier,
});
} catch (error) {
console.log("Error: ", error);
return res.status(400).json({ result: "SchemaData not saved in db" });
} else {
res.status(400).json({ error: "SchemaDetails not created" });
}
} else {
res.status(400).json({ error: "SchemaDetails not created" });
} catch (error) {
console.log("err: ", error);
return res.status(400).json({ status: "Schema not anchored" });
}
}

Expand Down
112 changes: 65 additions & 47 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import express from "express";
import bodyParser from "body-parser";
import fs from "fs";
import swaggerUi from "swagger-ui-express";
import cluster from "node:cluster";
import os from "node:os";

import {
getCredById,
Expand All @@ -24,59 +26,75 @@ export const { PORT } = process.env;
app.use(bodyParser.json({ limit: "5mb" }));
app.use(express.json());

const credentialRouter = express.Router({ mergeParams: true });
const schemaRouter = express.Router({ mergeParams: true });
const registryRouter = express.Router({ mergeParams: true });
const numCPUs = os.cpus().length;

credentialRouter.post("/", async (req, res) => {
return await issueCred(req, res);
});
credentialRouter.get("/:id", async (req, res) => {
return await getCredById(req, res);
});
credentialRouter.post("/revoke", async (req, res) => {
return await revokeCred(req, res);
});
credentialRouter.put("/update", async (req, res) => {
return await updateCred(req, res);
});
if (cluster.isMaster) {
console.log(`Primary ${process.pid} is running`);

schemaRouter.post("/", async (req, res) => {
return await createSchema(req, res);
});
schemaRouter.get("/:id", async (req, res) => {
return await getSchemaById(req, res);
});

registryRouter.post("/", async (req, res) => {
return await createRegistry(req, res);
});
registryRouter.get("/:id", async (req, res) => {
return await getRegistryById(req, res);
});
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}

const openApiDocumentation = JSON.parse(
fs.readFileSync("./apis.json").toString()
);
cluster.on("exit", (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
const credentialRouter = express.Router({ mergeParams: true });
const schemaRouter = express.Router({ mergeParams: true });
const registryRouter = express.Router({ mergeParams: true });

app.use("/docs", swaggerUi.serve, swaggerUi.setup(openApiDocumentation));
app.use("/api/v1/cred", credentialRouter);
app.use("/api/v1/schema", schemaRouter);
app.use("/api/v1/registry", registryRouter);
credentialRouter.post("/", async (req, res) => {
return await issueCred(req, res);
});
credentialRouter.get("/:id", async (req, res) => {
return await getCredById(req, res);
});
credentialRouter.post("/revoke", async (req, res) => {
return await revokeCred(req, res);
});
credentialRouter.put("/update", async (req, res) => {
return await updateCred(req, res);
});

async function main() {
try {
await createConnection(dbConfig);
} catch (error) {
console.log("error: ", error);
}
schemaRouter.post("/", async (req, res) => {
return await createSchema(req, res);
});
schemaRouter.get("/:id", async (req, res) => {
return await getSchemaById(req, res);
});

app.listen(PORT, () => {
console.log(`Dhiway gateway is running at http://localhost:${PORT}`);
registryRouter.post("/", async (req, res) => {
return await createRegistry(req, res);
});
registryRouter.get("/:id", async (req, res) => {
return await getRegistryById(req, res);
});
if (!issuerDid) {
await setupDidAndIdentities();

const openApiDocumentation = JSON.parse(
fs.readFileSync("./apis.json").toString()
);

app.use("/docs", swaggerUi.serve, swaggerUi.setup(openApiDocumentation));
app.use("/api/v1/cred", credentialRouter);
app.use("/api/v1/schema", schemaRouter);
app.use("/api/v1/registry", registryRouter);

async function main() {
try {
await createConnection(dbConfig);
} catch (error) {
console.log("error: ", error);
}

app.listen(PORT, () => {
console.log(`Dhiway gateway is running at http://localhost:${PORT}`);
});
if (!issuerDid) {
await setupDidAndIdentities();
}
}
}

main().catch((e) => console.log(e));
main().catch((e) => console.log(e));
console.log(`Worker ${process.pid} started`);
}
44 changes: 22 additions & 22 deletions src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export async function setupDidAndIdentities() {
AUTHOR_URI ?? "//Alice",
"sr25519"
);
console.log("Author: ", authorIdentity.address);

try {
const didDoc = await createDid(MNEMONIC, AGENT_DID_NAME);
if (didDoc) {
Expand Down Expand Up @@ -439,39 +439,39 @@ export async function updateStream(
signingkeys: any
) {
const updatedDocument = await Cord.Document.updateFromContent(
document,
updatedContent,
schema,
signCallback,
{}
document,
updatedContent,
schema,
signCallback,
{}
);

const api = Cord.ConfigService.get('api');
const api = Cord.ConfigService.get("api");
const { streamHash } = Cord.Stream.fromDocument(updatedDocument);
const authorization = Cord.Registry.uriToIdentifier(
updatedDocument.authorization
updatedDocument.authorization
);

const streamTx = api.tx.stream.update(
updatedDocument.identifier.replace('stream:cord:', ''),
streamHash,
authorization
updatedDocument.identifier.replace("stream:cord:", ""),
streamHash,
authorization
);

const authorizedStreamTx = await Cord.Did.authorizeTx(
authorDid,
streamTx,
async ({ data }) => ({
signature: signingkeys.assertionMethod.sign(data),
keyType: signingkeys.assertionMethod.type,
}),
authorIdentity.address
authorDid,
streamTx,
async ({ data }) => ({
signature: signingkeys.assertionMethod.sign(data),
keyType: signingkeys.assertionMethod.type,
}),
authorIdentity.address
);

try {
await Cord.Chain.signAndSubmitTx(authorizedStreamTx, authorIdentity);
return updatedDocument;
await Cord.Chain.signAndSubmitTx(authorizedStreamTx, authorIdentity);
return updatedDocument;
} catch (e) {
console.log('Error: \n', e);
console.log("Error: \n", e);
}
}
}

0 comments on commit d42b447

Please sign in to comment.