shogun-core
Version:
SHOGUN CORE - Core library for Shogun Ecosystem
288 lines (287 loc) • 13.8 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { Group } from '@semaphore-protocol/group';
import { generateProof, verifyProof } from '@semaphore-protocol/proof';
import { ethers } from 'ethers';
import { ErrorHandler, ErrorType } from '../../utils/errorHandler.js';
/**
* Types of verifiable credentials
*/
export var CredentialType;
(function (CredentialType) {
CredentialType["AGE"] = "age";
CredentialType["CITIZENSHIP"] = "citizenship";
CredentialType["EDUCATION"] = "education";
CredentialType["INCOME"] = "income";
CredentialType["EMPLOYMENT"] = "employment";
CredentialType["HEALTH"] = "health";
CredentialType["CUSTOM"] = "custom";
})(CredentialType || (CredentialType = {}));
/**
* ZK Credentials Manager
* Extends ZK-Proof functionality to support verifiable credentials
*/
var ZkCredentials = /** @class */ (function () {
function ZkCredentials() {
this.groups = new Map();
}
/**
* Create a verifiable credential from private data
*/
ZkCredentials.prototype.createCredential = function (identity, credentialData) {
try {
// Hash the private data to create a credential commitment
var privateDataString = JSON.stringify(credentialData.privateData);
var credentialHash = ethers.keccak256(ethers.toUtf8Bytes(privateDataString));
// For now, return a basic credential structure
// Full proof generation requires circuit files
var credential = {
type: credentialData.type,
claim: credentialData.claim,
proof: {
merkleTreeRoot: '',
nullifierHash: '',
signal: credentialHash,
externalNullifier: '',
proof: [],
},
credentialHash: credentialHash,
timestamp: Date.now(),
};
return {
credential: credential,
credentialHash: credentialHash,
};
}
catch (error) {
ErrorHandler.handle(ErrorType.ENCRYPTION, 'CREDENTIAL_CREATION_FAILED', "Failed to create verifiable credential: ".concat(error.message), error);
throw error;
}
};
/**
* Prove an attribute about yourself without revealing the underlying data
*/
ZkCredentials.prototype.proveAttribute = function (identity_1, credentialData_1) {
return __awaiter(this, arguments, void 0, function (identity, credentialData, groupId) {
var _a, credential, credentialHash, signal, signalBigInt, group, externalNullifier, fullProof, error_1;
if (groupId === void 0) { groupId = 'verified-credentials'; }
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_b.trys.push([0, 2, , 3]);
_a = this.createCredential(identity, credentialData), credential = _a.credential, credentialHash = _a.credentialHash;
signal = ethers.keccak256(ethers.toUtf8Bytes(credentialData.claim));
signalBigInt = BigInt(signal);
group = this.getOrCreateGroup(groupId);
// Add identity if not already in group
if (group.indexOf(identity.commitment) === -1) {
group.addMember(identity.commitment);
}
externalNullifier = BigInt(ethers.keccak256(ethers.toUtf8Bytes(credentialData.type)));
return [4 /*yield*/, generateProof(identity, group, signalBigInt, externalNullifier, {
wasmFilePath: './circuits/semaphore/20/semaphore.wasm',
zkeyFilePath: './circuits/semaphore/20/semaphore.zkey',
})];
case 1:
fullProof = _b.sent();
return [2 /*return*/, {
type: credentialData.type,
claim: credentialData.claim,
proof: {
merkleTreeRoot: fullProof.merkleTreeRoot.toString(),
nullifierHash: fullProof.nullifierHash.toString(),
signal: fullProof.signal.toString(),
externalNullifier: fullProof.externalNullifier.toString(),
proof: fullProof.proof.map(function (p) { return p.toString(); }),
},
credentialHash: credentialHash,
timestamp: Date.now(),
}];
case 2:
error_1 = _b.sent();
ErrorHandler.handle(ErrorType.ENCRYPTION, 'ATTRIBUTE_PROOF_FAILED', "Failed to prove attribute: ".concat(error_1.message), error_1);
throw error_1;
case 3: return [2 /*return*/];
}
});
});
};
/**
* Verify a credential proof
*/
ZkCredentials.prototype.verifyCredential = function (proof_1) {
return __awaiter(this, arguments, void 0, function (proof, treeDepth) {
var verified, error_2;
if (treeDepth === void 0) { treeDepth = 20; }
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, verifyProof(proof.proof, treeDepth)];
case 1:
verified = _a.sent();
return [2 /*return*/, {
verified: verified,
type: proof.type,
claim: proof.claim,
timestamp: proof.timestamp,
}];
case 2:
error_2 = _a.sent();
ErrorHandler.handle(ErrorType.ENCRYPTION, 'CREDENTIAL_VERIFICATION_FAILED', "Failed to verify credential: ".concat(error_2.message), error_2);
return [2 /*return*/, {
verified: false,
error: error_2.message,
}];
case 3: return [2 /*return*/];
}
});
});
};
/**
* Create a group for credential holders
*/
ZkCredentials.prototype.getOrCreateGroup = function (groupId) {
if (!this.groups.has(groupId)) {
var groupIdHash = ethers.keccak256(ethers.toUtf8Bytes(groupId));
var groupIdNumber = BigInt(groupIdHash);
this.groups.set(groupId, new Group(groupIdNumber));
}
return this.groups.get(groupId);
};
/**
* Add an identity to a credentials group
*/
ZkCredentials.prototype.addToCredentialGroup = function (identity, groupId) {
if (groupId === void 0) { groupId = 'verified-credentials'; }
var group = this.getOrCreateGroup(groupId);
if (group.indexOf(identity.commitment) === -1) {
group.addMember(identity.commitment);
}
};
/**
* Common credential proofs
*/
/**
* Prove age without revealing exact birthdate
*/
ZkCredentials.prototype.proveAge = function (identity, birthDate, minimumAge) {
return __awaiter(this, void 0, void 0, function () {
var age;
return __generator(this, function (_a) {
age = Math.floor((Date.now() - birthDate.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
if (age < minimumAge) {
throw new Error("Age ".concat(age, " is less than required ").concat(minimumAge));
}
return [2 /*return*/, this.proveAttribute(identity, {
type: CredentialType.AGE,
claim: "Age is ".concat(minimumAge, " or older"),
privateData: {
birthDate: birthDate.toISOString(),
actualAge: age,
},
})];
});
});
};
/**
* Prove citizenship without revealing country
*/
ZkCredentials.prototype.proveCitizenship = function (identity_1, country_1) {
return __awaiter(this, arguments, void 0, function (identity, country, region) {
if (region === void 0) { region = 'EU'; }
return __generator(this, function (_a) {
return [2 /*return*/, this.proveAttribute(identity, {
type: CredentialType.CITIZENSHIP,
claim: "Citizen of ".concat(region),
privateData: {
country: country,
passportNumber: 'hidden',
},
})];
});
});
};
/**
* Prove education without revealing institution
*/
ZkCredentials.prototype.proveEducation = function (identity, degree, university, year) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.proveAttribute(identity, {
type: CredentialType.EDUCATION,
claim: "Has ".concat(degree, " degree"),
privateData: {
university: university,
degree: degree,
year: year,
},
})];
});
});
};
/**
* Prove income range without revealing exact amount
*/
ZkCredentials.prototype.proveIncome = function (identity_1, amount_1, minimumRequired_1) {
return __awaiter(this, arguments, void 0, function (identity, amount, minimumRequired, currency) {
if (currency === void 0) { currency = 'USD'; }
return __generator(this, function (_a) {
if (amount < minimumRequired) {
throw new Error("Income ".concat(amount, " is less than required ").concat(minimumRequired));
}
return [2 /*return*/, this.proveAttribute(identity, {
type: CredentialType.INCOME,
claim: "Income \u2265 ".concat(minimumRequired, " ").concat(currency),
privateData: {
actualIncome: amount,
currency: currency,
verified: true,
},
})];
});
});
};
/**
* Cleanup resources
*/
ZkCredentials.prototype.cleanup = function () {
this.groups.clear();
};
return ZkCredentials;
}());
export { ZkCredentials };