From b83f52a448621ff26fe1c3659cf50dfcddaf5326 Mon Sep 17 00:00:00 2001 From: DcruBro Date: Fri, 3 Apr 2026 11:43:02 +0200 Subject: [PATCH] balance sheet save/load --- src/balance_sheet.c | 37 +++++++++++++++++++++++++++++++++++-- src/main.c | 5 +++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/balance_sheet.c b/src/balance_sheet.c index 4d54fd6..24e964d 100644 --- a/src/balance_sheet.c +++ b/src/balance_sheet.c @@ -40,15 +40,48 @@ bool BalanceSheet_Lookup(uint8_t* address, balance_sheet_entry_t* out) { return false; } -/* TODO */ bool BalanceSheet_SaveToFile(const char* outPath) { if (!sheetMap) { return false; } + + char outFile[512]; + strcpy(outFile, outPath); + strcat(outFile, "/balance_sheet.data"); + FILE* file = fopen(outFile, "wb"); + if (!file) { return false; } + + khiter_t k; + for (k = kh_begin(sheetMap); k != kh_end(sheetMap); ++k) { + if (kh_exist(sheetMap, k)) { + balance_sheet_entry_t entry = kh_val(sheetMap, k); + if (fwrite(&entry, sizeof(balance_sheet_entry_t), 1, file) != 1) { + fclose(file); + return false; + } + } + } + + fclose(file); return true; } -/* TODO */ bool BalanceSheet_LoadFromFile(const char* inPath) { if (!sheetMap) { return false; } + + char inFile[512]; + strcpy(inFile, inPath); + strcat(inFile, "/balance_sheet.data"); + FILE* file = fopen(inFile, "rb"); + if (!file) { return false; } + + balance_sheet_entry_t entry; + while (fread(&entry, sizeof(balance_sheet_entry_t), 1, file) == 1) { + if (BalanceSheet_Insert(entry) < 0) { + fclose(file); + return false; + } + } + + fclose(file); return true; } diff --git a/src/main.c b/src/main.c index 2f6eb39..5d6824b 100644 --- a/src/main.c +++ b/src/main.c @@ -176,6 +176,10 @@ int main(int argc, char* argv[]) { printf("No existing chain loaded from %s\n", chainDataDir); } + if (!BalanceSheet_LoadFromFile(chainDataDir)) { + printf("Failed to load the balance sheet or none existing\n"); + } + const uint64_t effectivePhase1Blocks = (PHASE1_TARGET_BLOCKS / EMISSION_ACCELERATION_FACTOR) > 0 ? (PHASE1_TARGET_BLOCKS / EMISSION_ACCELERATION_FACTOR) @@ -448,6 +452,7 @@ int main(int argc, char* argv[]) { }*/ BalanceSheet_Print(); + BalanceSheet_SaveToFile(chainDataDir); Chain_Destroy(chain); Block_ShutdownPowContext();