Commit c6e6f973 authored by Ishini Kiridena's avatar Ishini Kiridena

Issuer generation with new asset code-patient

parent 42fac8fb
......@@ -8,6 +8,9 @@ const Patient = new mongoose.Schema({
rsa: String,
genesishash: String,
currenthash: String,
keysequence: String,
issuerpk: String,
issuersk: String,
timestamp: String,
});
......
......@@ -7,6 +7,8 @@ const EncryptionService = require("./../../services/encryptionservice");
const AccountCreateCollection = require("../../model/stellar/accountCreate");
const UserSchema = require("../../model/patient/patient");
const { generateKeyPairSync } = require("crypto");
const GenerateRandomAssetCode = require("./../../services/assetCodeGenerator");
const GenerateKeyPairAndCreateAccount = require("./../../services/accountCreator");
let timestamp;
router.post("/", async (req, res) => {
......@@ -287,49 +289,104 @@ router.post("/", async (req, res) => {
const b64RSApk = btoa(RSAPK);
const b64RSAsk = btoa(RSASK);
//create the user collection object to be added to the DB
const userCollectionObject = new UserSchema({
username: decryptedUserName,
password: req.body.password,
email: decryptedEmail,
publickey: userKeyPair.publicKey(),
rsa: b64RSApk,
genesishash: genesisTxnResult.hash,
currenthash: genesisTxnResult.hash,
timestamp: timestamp,
});
var newAssetCode = "";
//save the user collection object to the database
try {
const saveUserInCollection = await userCollectionObject.save();
console.log("User details added to the DB " + saveUserInCollection);
console.log("Public key: " + userKeyPair.publicKey());
console.log("Secret: " + userKeyPair.secret());
res.status(200).json({
message: "User details added to the blockchain",
hash: genesisTxnResult.hash,
pubkey: EncryptionService.EncryptWithServerKey(
userKeyPair.publicKey()
),
seed: EncryptionService.EncryptWithServerKey(userKeyPair.secret()),
rsapk: EncryptionService.EncryptWithServerKey(b64RSApk),
rsask: EncryptionService.EncryptWithServerKey(b64RSAsk),
});
console.log(
"/patient/register - register patient details successful"
);
} catch (error) {
console.log(
"Error when adding user details to the blockchain : " + error
);
res.status(500).json({
message:
"Error when adding user details to the blockchain : " + error,
//generate NFT sequence NO as asset ID
GenerateRandomAssetCode()
.then(async (assetCode) => {
newAssetCode = assetCode;
console.log("New asset code generated : ", newAssetCode);
//generate new account
try {
const result = await GenerateKeyPairAndCreateAccount();
console.log("Issuer Public Key:", result.publicKey);
console.log("Issuer Private Key:", result.privateKey);
//create the user collection object to be added to the DB
const userCollectionObject = new UserSchema({
username: decryptedUserName,
password: req.body.password,
email: decryptedEmail,
publickey: userKeyPair.publicKey(),
rsa: b64RSApk,
genesishash: genesisTxnResult.hash,
currenthash: genesisTxnResult.hash,
timestamp: timestamp,
keysequence: newAssetCode,
issuerpk: EncryptionService.EncryptWithServerKey(
result.publicKey
),
issuersk: EncryptionService.EncryptWithServerKey(
result.privateKey
),
});
//save the user collection object to the database
try {
const saveUserInCollection = await userCollectionObject.save();
console.log(
"User details added to the DB " + saveUserInCollection
);
console.log("Public key: " + userKeyPair.publicKey());
console.log("Secret: " + userKeyPair.secret());
res.status(200).json({
message: "User details added to the blockchain",
hash: genesisTxnResult.hash,
pubkey: EncryptionService.EncryptWithServerKey(
userKeyPair.publicKey()
),
seed: EncryptionService.EncryptWithServerKey(
userKeyPair.secret()
),
rsapk: EncryptionService.EncryptWithServerKey(b64RSApk),
rsask: EncryptionService.EncryptWithServerKey(b64RSAsk),
});
console.log(
"/patient/register - register patient details successful"
);
} catch (errorWhenAddingUserToDB) {
console.log(
"Error when adding user details to the database : " +
errorWhenAddingUserToDB
);
res.status(500).json({
message:
"Error when adding user details to the database : " +
errorWhenAddingUserToDB,
});
console.log(
"/patient/register - register patient details unsuccessful"
);
}
} catch (errWhenGeneratingIssuerAccount) {
console.log(
"Error when generating issuer account : " +
errWhenGeneratingIssuerAccount
);
res.status(500).json({
message:
"Error when generating issuer account : " +
errWhenGeneratingIssuerAccount,
});
console.log(
"/patient/register - register patient details unsuccessful"
);
}
})
.catch((errWhenGeneratingAssetCode) => {
console.log(
"Error when generating asset code : " + errWhenGeneratingAssetCode
);
res.status(500).json({
message:
"Error when generating asset code : " +
errWhenGeneratingAssetCode,
});
console.log(
"/patient/register - register patient details unsuccessful"
);
});
console.log(
"/patient/register - register patient details unsuccessful"
);
}
} catch (error) {
console.log(
"Error when sending genesis transaction to blockchain: " + error
......
const StellarSDK = require("stellar-sdk");
const AccountCreateCollection = require("./../model/stellar/accountCreate");
require("dotenv").config();
async function GenerateKeyPairAndCreateAccount() {
//get the server key pair
const serverSourceKeyPair = StellarSDK.Keypair.fromSecret(
process.env.STELLARSEED
);
const serverPubKey = serverSourceKeyPair.publicKey();
const server = new StellarSDK.Server(process.env.STELLARTESTNET);
//load server account
const account = await server.loadAccount(serverPubKey);
const fee = await server.fetchBaseFee();
//generate random keypair
const userKeyPair = StellarSDK.Keypair.random();
//build the account funding transaction
const accCreateTransaction = new StellarSDK.TransactionBuilder(account, {
fee,
networkPassphrase: StellarSDK.Networks.TESTNET,
})
.addMemo(StellarSDK.Memo.text("Create account"))
.addOperation(
StellarSDK.Operation.createAccount({
destination: userKeyPair.publicKey(),
startingBalance: "100",
})
)
.setTimeout(30)
.build();
//sign the transaction
accCreateTransaction.sign(serverSourceKeyPair);
//send account creation transaction to BC
try {
const accCreateTxnResult = await server.submitTransaction(
accCreateTransaction
);
console.log("New user account created: HASH : ", accCreateTxnResult.hash);
console.log(
"View account creation transaction 22222 at : https://horizon-testnet.stellar.org/transactions/" +
accCreateTxnResult.hash
);
const timestamp = new Date();
//create the account creation details collection object
const createAccountObj = new AccountCreateCollection({
publickey: userKeyPair.publicKey(),
amount: "10XLM",
timestamp: timestamp,
transactionhash: accCreateTxnResult.hash,
});
//save the account creation details to the database
const saveInCollection = await createAccountObj.save();
console.log(
"Account creation 22222 details saved in the database " + saveInCollection
);
return {
publicKey: userKeyPair.publicKey(),
privateKey: userKeyPair.secret(),
};
} catch (err) {
console.log("Error submitting transaction:", err);
throw err;
}
}
module.exports = GenerateKeyPairAndCreateAccount;
const { MongoClient } = require("mongodb");
require("dotenv").config();
const url = process.env.DATABASE_URL;
async function generateRandomAssetCode() {
const client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
try {
const db = client.db();
const collection = db.collection("assetcodes");
let assetCode = generateCode();
// Check if the generated asset code is already in the database
let found = await isAssetCodeInDatabase(collection, assetCode);
while (found) {
// If so, generate a new random asset code
assetCode = generateCode();
found = await isAssetCodeInDatabase(collection, assetCode);
}
// At this point, assetCode is guaranteed to be a unique asset code
// and can be used for further processing
// Insert the new asset code into the collection
const result = await collection.insertOne({ code: assetCode });
return assetCode;
} finally {
// Close the client connection after the query has completed
client.close();
}
}
function generateCode() {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < 12; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function isAssetCodeInDatabase(collection, assetCode) {
return new Promise((resolve, reject) => {
collection.findOne({ code: assetCode }, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result !== null);
}
});
});
}
module.exports = generateRandomAssetCode;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment