From 90b31ca06ca7add7f3648f673853b2ff78e0b45c Mon Sep 17 00:00:00 2001 From: Martin Minkov Date: Tue, 15 Aug 2023 17:11:01 -0700 Subject: [PATCH] feat(consensus): add new config.ts file to handle consensus configuration This new file includes a Config type and a readConfig function to read and parse the configuration from a file. It also includes helper functions to extract values from the configuration file and to generate the grace period end value. This change allows for more flexible and maintainable configuration handling. --- src/consensus/config.ts | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 src/consensus/config.ts diff --git a/src/consensus/config.ts b/src/consensus/config.ts new file mode 100644 index 0000000..9eb46ce --- /dev/null +++ b/src/consensus/config.ts @@ -0,0 +1,51 @@ +import fs from 'fs'; +export { Config, readConfig }; + +type Config = { + k: number; + delta: number; + slotsPerEpoch: number; + slotsPerSubWindow: number; + subWindowsPerWindow: number; + blockWindowDuration: number; + gracePeriodEnd: number; +}; + +function extractValue(contents: string, key: string): number { + const regex = new RegExp(`\\[%%define ${key} (?:")?(\\d+)(?:")?\\]`); + const match = contents.match(regex); + if (!match) { + throw new Error(`Key ${key} not found in config file.`); + } + return parseInt(match[1], 10); +} + +function genGracePeriodEnd( + slotsPerEpoch: number, + blockWindowDuration: number +): number { + const numDays = 3; + const gracePeriodEnd = Math.min( + (numDays * 24 * 60 * 60 * 1000) / blockWindowDuration, + slotsPerEpoch + ); + return gracePeriodEnd; +} + +function readConfig(path: string): Config { + const contents = fs.readFileSync(path, 'utf8'); + + const blockWindowDuration = extractValue(contents, 'block_window_duration'); + const slotsPerEpoch = extractValue(contents, 'slots_per_epoch'); + const gracePeriodEnd = genGracePeriodEnd(slotsPerEpoch, blockWindowDuration); + + return { + k: extractValue(contents, 'k'), + delta: extractValue(contents, 'delta'), + slotsPerEpoch, + slotsPerSubWindow: extractValue(contents, 'slots_per_sub_window'), + subWindowsPerWindow: extractValue(contents, 'sub_windows_per_window'), + blockWindowDuration, + gracePeriodEnd, + }; +}