Skip to content

Commit

Permalink
improve: add custom encrypt/decrypt
Browse files Browse the repository at this point in the history
  • Loading branch information
james-a-morris committed Sep 25, 2023
1 parent b8c9a70 commit 2b4f5e5
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/helpers/oshhhnap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { timelockDecrypt, timelockEncrypt } from 'tlock-js';
import { HttpChainClient, HttpCachingChain } from 'drand-client';

const testnetUnchainedUrl =
'https://pl-eu.testnet.drand.sh/7672797f548f3f4748ac4bf3352fc6c6b6468c9ad40ad456a397545c6e2df5bf';

const getFastestNode = async () => {
const chain = new HttpCachingChain(testnetUnchainedUrl);
const client = new HttpChainClient(chain);

return client;
};

export async function timelockEncryption(message: string, duration: number) {
if (duration < 30)
throw new Error(
'Duration must be positive and greater or equal to 30 seconds'
);
const fastestNodeClient = await getFastestNode();
const latestRound = await fastestNodeClient.latest();
const chain = new HttpCachingChain(testnetUnchainedUrl);

const { period } = await chain.info();

const roundNumber = latestRound.round + Math.floor(duration / period);

const result = await timelockEncrypt(
latestRound.round + roundNumber,
Buffer.from(message),
fastestNodeClient
);

return result;
}

export async function timelockEncryptionForOshhhnap(
message: string,
proposalId: string,
duration: number
) {
let result = await timelockEncryption(message, duration);

// We need to append the ID to the ciphertext, so we can decrypt it later
// and know which proposal it belongs to.
result = `${result}__ID__${proposalId}`;

return result;
}

export async function timelockDecryption(ciphertext: string) {
const fastestNodeClient = await getFastestNode();
const result = await timelockDecrypt(ciphertext, fastestNodeClient);
return result;
}

export async function timelockDecryptionForOshhhnap(ciphertext: string) {
// We need to remove the ID from the ciphertext, so we can decrypt it.
const [ciphertextWithoutId, proposalId] = ciphertext.split('__ID__');
const result = await timelockDecryption(ciphertextWithoutId);
return {
result,
proposalId
};
}

0 comments on commit 2b4f5e5

Please sign in to comment.