-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
867 additions
and
22 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
import { Request, Response } from "express"; | ||
import { getSecretKeys } from "../utils/secret"; | ||
import { base_encode } from "near-api-js/lib/utils/serialize"; | ||
import { getVoterPublicKey, isNominee, getAllVotes, sendResultsToContract } from "../utils/near"; | ||
import { decrypt, verifySignature } from "../../cryptography"; | ||
import { VotingPackage } from "../../cryptography/types"; | ||
|
||
export const getPublicKey = async (_: Request, res: Response) => { | ||
const secretKeys = await getSecretKeys(); | ||
|
||
if (secretKeys.error || !secretKeys.data) { | ||
console.error("Error while getting secret keys", secretKeys.error); | ||
return res.status(500).send({ message: "Error while getting secret keys" }); | ||
} | ||
|
||
return res.status(200).send(base_encode(secretKeys.data.public)); | ||
} | ||
|
||
export const postDecryption = async (req: Request, res: Response) => { | ||
const secretKeys = await getSecretKeys(); | ||
|
||
if (secretKeys.error || !secretKeys.data) { | ||
console.error("Error while getting secret keys", secretKeys.error); | ||
return res.status(500).send({ message: "Error while getting secret keys" }); | ||
} | ||
|
||
if (secretKeys.data.private === undefined) { | ||
const endTime = new Date(secretKeys.data.end_time / 1_000_000).toUTCString() | ||
return res.status(425).send({ message: `Secret key not available yet. Please come after ${endTime} UTC` }); | ||
} | ||
|
||
const encryptedVotes = await getAllVotes(); | ||
if (encryptedVotes.length === 0) { | ||
return res.status(400).send({ message: "No votes to decrypt" }); | ||
} | ||
|
||
const decryptedVotes = new Map<string, VotingPackage>(); | ||
for (let i = 0; i < encryptedVotes.length; i++) { | ||
const vote = encryptedVotes[i]; | ||
let result = await decrypt(vote, secretKeys.data.private); | ||
|
||
if (result.error || !result.data) { | ||
console.log(`Discard vote ${i}: ${result.error}`); | ||
continue; | ||
} | ||
|
||
let isValid = await validateVote(result.data, i); | ||
if (!isValid) { | ||
continue; | ||
} | ||
|
||
if (decryptedVotes.has(result.data.accountId)) { | ||
console.log(`Found new vote for ${result.data.accountId}. Replacing the old vote`); | ||
} | ||
decryptedVotes.set(result.data.accountId, result.data); | ||
} | ||
|
||
const results = new Map<string, number>(); | ||
decryptedVotes.forEach((vote) => { | ||
vote.votes.forEach((v) => { | ||
results.set(v.candidate, (results.get(v.candidate) ?? 0) + v.weight); | ||
}); | ||
}); | ||
|
||
if (await sendResultsToContract(Array.from(results.entries()))) { | ||
return res.status(200).send(decryptedVotes); | ||
} | ||
return res.status(500).send({ message: "Error while submitting results to the contract" }); | ||
} | ||
|
||
const validateVote = async (vote: VotingPackage, voteNumber: number): Promise<boolean> => { | ||
const { accountId, votes, signature } = vote; | ||
|
||
const voterInfo = await getVoterPublicKey(accountId); | ||
if (!voterInfo) { | ||
console.log(`Discard vote ${voteNumber}: Voter is not registered`); | ||
return false; | ||
} | ||
|
||
const data = base_encode(JSON.stringify({ accountId, votes })); | ||
if (!verifySignature(data, voterInfo.public_key, signature)) { | ||
console.log(`Discard vote ${voteNumber}: Invalid user signature`); | ||
return false; | ||
} | ||
|
||
|
||
let totalWeightUsed = 0; | ||
for (let i = 0; i < votes.length; i++) { | ||
let vote = votes[i]; | ||
if (vote.weight < 0) { | ||
console.log(`Discard vote ${voteNumber}: Invalid vote weight`); | ||
return false; | ||
} | ||
totalWeightUsed += vote.weight; | ||
|
||
let status = await isNominee(vote.candidate); | ||
if (!status) { | ||
console.log(`Discard vote ${voteNumber}: Invalid candidate`); | ||
return false; | ||
} | ||
} | ||
|
||
if (totalWeightUsed > voterInfo.vote_weight) { | ||
console.log(`Discard vote ${voteNumber}: Vote weight exceeds the voter's total weight`); | ||
return false; | ||
} | ||
|
||
return true; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,12 @@ | ||
import express from "express"; | ||
import { postVote } from "./controllers/submitVote"; | ||
import { getPublicKey, postDecryption } from "./controllers/decryption"; | ||
|
||
const routes = express.Router(); | ||
|
||
routes.get("/encryption-public-key", getPublicKey); | ||
|
||
routes.post("/vote", postVote) | ||
routes.post("/decrypt", postDecryption); | ||
|
||
export { routes }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
import { SecretNetworkClient, Wallet } from "secretjs"; | ||
import ecdsa from "secp256k1"; | ||
import { NETWORK_ID, SECRET_CODE_HASH, SECRET_CONTRACT } from "../.."; | ||
import { Result } from "../../cryptography"; | ||
|
||
|
||
const wallet = new Wallet(); | ||
|
||
let secretjs: SecretNetworkClient; | ||
|
||
if (NETWORK_ID === "mainnet") { | ||
secretjs = new SecretNetworkClient({ | ||
chainId: "secret-4", | ||
url: "https://rpc.ankr.com/http/scrt_cosmos", | ||
wallet: wallet, | ||
walletAddress: wallet.address, | ||
}); | ||
} | ||
else { | ||
secretjs = new SecretNetworkClient({ | ||
chainId: "pulsar-3", | ||
url: "https://lcd.pulsar-3.secretsaturn.net", | ||
wallet: wallet, | ||
walletAddress: wallet.address, | ||
}); | ||
} | ||
|
||
type SecretResponse = { | ||
public: number[], | ||
private: number[] | undefined, | ||
end_time: number | ||
} | ||
|
||
type Response = { | ||
public: Uint8Array, | ||
private: Uint8Array | undefined, | ||
end_time: number | ||
} | ||
|
||
type Request = { | ||
get_keys: {} | ||
} | ||
|
||
export async function getSecretKeys(): Promise<Result<Response>> { | ||
let query = await secretjs.query.compute.queryContract<Request, SecretResponse>({ | ||
contract_address: SECRET_CONTRACT!, | ||
query: { | ||
get_keys: {}, | ||
}, | ||
code_hash: SECRET_CODE_HASH, | ||
}); | ||
|
||
if (query.private !== undefined && query.private.length > 0) { | ||
const derivedPubKey = ecdsa.publicKeyCreate(Uint8Array.from(query.private), true); | ||
const publicKey = query.public; | ||
|
||
if (!derivedPubKey.every((value, index) => value === publicKey[index])) { | ||
return { | ||
error: 'Secret key is invalid', | ||
data: undefined | ||
} | ||
} | ||
} | ||
|
||
return { | ||
error: undefined, | ||
data: { | ||
public: Uint8Array.from(query.public), | ||
private: query.private ? Uint8Array.from(query.private) : undefined, | ||
end_time: query.end_time | ||
} | ||
} | ||
}; | ||
|
Oops, something went wrong.