3 Commits
12 changed files with 800 additions and 385 deletions
+4 -3
View File
@@ -1,6 +1,7 @@
*.o *.o
*.exe *.exe
*.dat bank.dat
AGENTS.md
.vscode/launch.json .vscode/launch.json
.vscode/tasks.json .vscode/tasks.json
a.out
bank_system
+53
View File
@@ -0,0 +1,53 @@
# BankManager — C 语言银行账户管理系统
## 构建 & 运行
```sh
gcc bank.c account.c transaction.c file_io.c utils.c log.c graph.c hash.c -o bank_system
./bank_system
```
`bank.h` 是唯一头文件,所有 `.c` 编译顺序无要求。
## 项目布局
所有源文件在根目录,无 `src/` 子目录。无包管理器、无构建系统、无测试框架。
| 文件 | 职责 |
|------|------|
| `bank.c` | 主循环、菜单、权限路由 |
| `account.c` | 开户、销户、登录、修改密码、查询全部账户 |
| `transaction.c` | 存款、取款、查余额、转账 |
| `file_io.c` | 二进制文件读写 (bank.dat) |
| `utils.c` | 输入校验工具(`GetInputInt`/`GetInputDouble` 已定义但未被使用) |
| `log.c` | 环形队列日志,支持 KMP 关键词搜索 |
| `graph.c` | 从转账日志建邻接矩阵,分析客户间资金来往关系 |
| `hash.c` | 哈希表,映射账户ID到数组下标,线性探测+墓碑标记 |
| `bank.h` | 唯一头文件,声明所有公有函数和类型 |
## 重要数据/约束
- **Max 50 账户** (`MAX_ACCOUNTS`),全局数组 `g_astAccounts`,不使用 `malloc`
- **`g_iAccCount` 初始值=1**(非0),槽位 0 预留给管理员。
- **默认管理员**: ID=1000, name="admin", password=123456, quanxian=1。首次运行时自动创建。
- **密码**: 纯 6 位数字(100000-999999)。
- **权限**: 1=管理员,2=普通用户。
- **数据持久化**: 二进制文件 `bank.dat`(已加入 `.gitignore`)。`SaveData()` 总是写入恰好 50 条记录。
- **全局日志队列**: 环形队列 `g_logQueue`,最多 100 条 (`MAX_LOGS`),溢出时队头出队覆盖旧记录。
- **哈希表**: `HASH_SIZE=101`(质数),开放寻址法+线性探测,删除用墓碑标记(id=-2)。
## 代码约定
- 中文注释和中文菜单字符串。
- 全局变量命名前缀 `g_`(如 `g_iAccCount`, `g_astAccounts`)。
- 无测试。
## 已知陷阱
- **`InitAdminAccount()` 双重调用导致密码重置** — `LoadData()` 内无文件时调用一次,`main()` 第 21 行无条件再调用一次。管理员密码修改在重启后必然丢失。
- **`SaveData()` 内部调用 `LoadData()`**`file_io.c:22`),写盘后立即重读以重新计数 `g_iAccCount`。注意这会导致刚保存的数组被覆盖读回。
- **`GenerateDummyData()`(graph.c)会清空全部日志并修改账户余额**,仅用于测试演示,非生产操作。
- **`DeleteAccount()` 不递减 `g_iAccCount`** — 递减由调用方 `bank.c:84` 负责。函数内 `for (; i < g_iAccCount-i; i++)` 边界有误(应为 `g_iAccCount-1`)。
- **`exit(0)` 短路** — `bank.c:53` 直接 `exit(0)`,不会执行 `main()` 末尾的清理代码(当前无实质性清理,但未来加逻辑时需注意)。
- **`ChangePassword()` 已定义但未接入菜单**`account.c:159`),无法从界面调用。
- **`utils.c``GetInputInt`/`GetInputDouble` 已定义但未被任何调用方使用**,全部输入仍用裸 `scanf`
+137 -198
View File
@@ -1,224 +1,163 @@
# BankManager # 简易银行账户管理系统
Windows 命令行银行账户管理系统,使用 C 语言实现,支持账户管理、交易记录和基于 Merkle 树的数据完整性校验。 ## 项目简介
这是一个基于C语言开发的简易银行账户管理系统,支持基本的银行账户操作功能,包括开户、登录、存款、取款、查询余额、账户管理等。系统采用模块化设计,代码结构清晰,易于维护和扩展。
## 构建 ## 功能特性
- **账户管理**
- 创建普通用户账户(权限2
- 创建管理员账户(权限1
- 删除账户(仅管理员可操作)
- 修改密码
- **账户操作**
- 存款
- 取款
- 查询余额
- 转账(账户间资金转移)
- **系统功能**
- 用户登录验证
- 权限分级(管理员/普通用户)
- 数据持久化(自动保存到文件)
- 交易流水查询(管理员)
- 资金关系图分析(管理员):从转账日志建图,分析客户间资金来往关系
- 自动初始化默认管理员账户
```powershell ## 系统架构
gcc *.c -o bank.exe -ladvapi32 ### 核心模块
``` 1. **主程序 (bank.c)**
- 程序入口点
- 菜单显示和用户交互
- 权限控制逻辑
运行:`.\bank.exe` 2. **账户管理 (account.c)**
- 账户创建、删除
- 账户查找
- 登录验证
- 密码修改
- 显示所有账户信息
--- 3. **交易处理 (transaction.c)**
- 存款功能
- 取款功能
- 余额查询
- 转账功能(账户间资金转移)
## 数据结构总览 4. **数据持久化 (file_io.c)**
- 数据保存到文件(bank.dat
- 从文件加载数据
- 初始化默认管理员账户
项目围绕 **4 个核心数据结构** 构建,它们共同决定了系统的存储、操作和校验能力: 5. **工具函数 (utils.c)**
- 输入验证和清理
- 安全的整数和浮点数输入
| 数据结构 | 定义位置 | 用途 | 6. **头文件 (bank.h)**
|----------|----------|------| - 全局常量定义
| `STACCOUNT` | `bank.h:8-15` | 账户信息记录 | - 账户结构体定义
| `LogEntry` | `bank.h:55-62` | 单笔交易日志 | - 函数声明
| `LogQueue` | `bank.h:64-69` | 交易日志的环形缓冲队列 |
| `HashValue` | `bank.h:87-89` | SHA-256 哈希值(Merkle 树节点) |
--- 7. **日志模块(log.c)**
- 日志记录和存储(环形队列)
## 1. STACCOUNT — 账户信息 8. **资金关系图分析(graph.c)**
- 从转账日志构建邻接矩阵
- 显示全部转账关系图
- 查看指定账户关联关系
- 最活跃账户排名(度中心性)
- BFS最短转账路径查找
9. **哈希表模块(hash.c)**
- 映射账户ID到数组下标,O(1)快速查找
- 开放寻址法,线性探测解决冲突
- 墓碑标记处理删除操作
- 支持从数组重建哈希表
### 数据结构
```c ```c
#define MAX_ACCOUNTS 50 typedef struct strAccount
#define NAME_LEN 31 {
int id; // 账户ID(从1000开始)
typedef struct strAccount { char name[31]; // 姓名(最多30字符)
int id; // 唯一账户 ID double balance; // 账户余额
char name[NAME_LEN]; // 户名(最长 30 字符) int password; // 6位数字密码
double balance; // 账户余额 int quanxian; // 权限(1=管理员,2=普通用户)
int password; // 6 位数字密码 (100000999999)
int quanxian; // 权限级别: 0=访客, 1=管理员, 2=普通用户
} STACCOUNT; } STACCOUNT;
``` ```
### 全局实例 ## 使用说明
### 编译
```c ```bash
STACCOUNT g_astAccounts[MAX_ACCOUNTS]; // bank.c:6 — 固定 50 槽位数组 gcc bank.c account.c transaction.c file_io.c utils.c log.c graph.c hash.c -o bank_system
int g_iAccCount; // bank.c:8 — 当前有效账户数量
``` ```
### 设计要点 ### 运行
```bash
- **固定容量**:最多 50 个账户,由 `MAX_ACCOUNTS` 宏控制。 ./bank_system
- **删除策略**:删除账户时将其槽位**全部置零**(`memset`),而非移动元素。`LoadData` 通过统计 `id != 0` 的槽位重新计算 `g_iAccCount`
- **管理员硬编码**id=1000, password=123456`InitAdminAccount()` 每次启动都会强制覆盖第一个槽位(`account.c:18-22`)。
- **内存布局**`sizeof(STACCOUNT)` = 4 + 31 + 3(padding) + 8 + 4 + 4 = 54 字节(假设 64 位, 对齐后 56)。
---
## 2. LogEntry — 交易日志条目
```c
typedef struct {
int account_id; // 关联的账户 ID
char type[10]; // 操作类型: "Deposit" 或 "Withdraw"
double amount; // 交易金额
double balance; // 交易后余额
char timestamp[20]; // 时间戳 (格式: YYYY-MM-DD HH:MM:SS)
char location[50]; // 地点信息 (固定 "宇宙总行")
} LogEntry;
``` ```
### 数据来源 ### 操作流程
1. **初始界面**(未登录状态)
- 选项1:开户(创建普通用户账户)
- 选项2:登录
- 选项0:退出系统
- `type``amount``balance``Deposit()` / `Withdraw()` 填充。 2. **普通用户界面**(登录后)
- `timestamp``EnqueueLog()` 调用时通过 `time()` + `localtime()` 生成。 - 选项1:存款
- `location``log.c:55` 硬编码为 `"宇宙总行"` - 选项2:取款
- **不可变**:一旦入队,LogEntry 不再被修改(除非被环形队列覆盖)。 - 选项3:查询余额
- 选项4:转账
- 选项0:退出账户
--- 3. **管理员界面**(登录后)
- 选项1:存款
- 选项2:取款
- 选项3:查询余额
- 选项4:显示所有账户
- 选项5:删除账户
- 选项6:创建管理员账户
- 选项7:查看交易流水
- 选项8:搜索交易日志
- 选项9:转账
- 选项10:资金关系图分析
- 选项0:退出账户
## 3. LogQueue — 环形缓冲队列 ### 默认账户
系统首次运行时会自动创建一个默认管理员账户:
- **账户ID**: 1000
- **姓名**: admin
- **密码**: 123456
- **权限**: 管理员
```c ## 技术细节
#define MAX_LOGS 100 - **最大账户数量**: 50个
- **密码规则**: 6位数字(100000-999999
- **数据存储**: 二进制文件(bank.dat
- **输入验证**: 所有数值输入都包含错误处理
- **内存管理**: 使用全局数组存储账户数据,哈希表加速ID查找
typedef struct { ## 文件说明
LogEntry logs[MAX_LOGS]; // 固定 100 条日志存储 - `bank.c` - 主程序文件
int front; // 队头指针(最旧记录) - `account.c` - 账户管理功能实现
int rear; // 队尾指针(下一插入位) - `transaction.c` - 交易处理功能实现
} LogQueue; - `file_io.c` - 文件读写功能实现
``` - `utils.c` - 工具函数实现
- `log.c` - 日志记录和存储(环形队列)
- `graph.c` - 资金关系图分析模块
- `hash.c` - 哈希表模块,映射账户ID到数组下标
- `bank.h` - 头文件,包含结构体定义和函数声明
- `bank.dat` - 数据存储文件(运行时自动生成)
### 全局实例 ## 注意事项
1. 密码必须为6位数字
2. 存款和取款金额必须为正数
3. 取款时会检查账户余额是否充足
4. 删除账户功能仅管理员可用
5. 系统会自动保存所有操作到文件,确保数据持久化
```c ## 扩展建议
LogQueue g_logQueue; // bank.c:5 - ~~添加交易记录功能~~
``` - ~~实现账户快速搜索~~(已通过哈希表实现)
- 增加更多权限级别
### 工作原理 - 改进用户界面(如使用图形界面)
- 添加数据加密功能
``` - 实现多用户并发访问
初始状态: front = 0, rear = 0
入队 3 条: front = 0, rear = 3, 有效记录: [0, 1, 2]
入队 100 条后继续入队: front = 1, rear = 0, 有效记录: [1..99, 0](循环覆盖)
```
- **满判断**`(rear + 1) % MAX_LOGS == front` — 始终保留一个空位以区分满/空。
- **空判断**`front == rear`
- **容量上限**`MAX_LOGS - 1 = 99` 条有效记录。
- **溢出行为**:当队列满时,`EnqueueLog()` 静默覆盖最旧记录,并同步更新 Merkle 根。
- **遍历逻辑**`ShowTransactionLogs()``front``(rear - 1) % MAX_LOGS` 依次输出。
### 持久化
整个 `LogQueue` 结构体以二进制形式写入 `log.dat`
```
文件大小 = sizeof(LogQueue) = 100 * sizeof(LogEntry) + 2 * sizeof(int)
≈ 100 * 96 + 8 = 9608 字节
```
---
## 4. HashValue — SHA-256 哈希值
```c
#define HASH_SIZE 32
typedef struct {
unsigned char data[HASH_SIZE]; // 32 字节 RAW SHA-256 摘要
} HashValue;
```
### 全局实例
```c
HashValue g_merkleRoot; // merkle.c:8 — 所有日志的 Merkle 树根哈希
```
### 依赖
- 使用 **Windows CryptoAPI** (`wincrypt.h`) 计算 SHA-256。
- 编译时需链接 `-ladvapi32`
### Merkle 树构建流程 (`BuildMerkleTree`)
1. 读取 `g_logQueue` 中的所有有效日志条目(从 `front``rear`)。
2. 对每条 `LogEntry` 调用 `HashLogEntry()`,生成 **leaf hashes**(叶子节点)。
3. 将所有叶子哈希存储在**动态分配的 `HashValue* leaves` 数组**中(堆内存,使用后释放)。
4. 自底向上两两哈希合并,直到产生唯一的根哈希 → `g_merkleRoot`
5. 持久化到 `merkle.dat`32 字节固定大小)。
```
日志条目: [E1] [E2] [E3] [E4] [E5]
│ │ │ │ │
叶子哈希: [H1] [H2] [H3] [H4] [H5]
│ │ │ │ │
中间层: [H12] [H34] H5
│ │ │
顶层: [ H1234 ] H5
│ │
Merkle根: [ H12345 ] → g_merkleRoot
```
---
## 数据流与文件布局
```
┌──────────┐ 二进制块 (50 × sizeof(STACCOUNT)) ┌──────────┐
│ bank.dat │ ◄──────────────────────────────────► │ accounts │
│ 2700 B │ │ 内存数组 │
└──────────┘ └────┬─────┘
┌──────────┐ sizeof(LogQueue) 二进制块 ┌────────────┐ │
│ log.dat │ ◄──────────────────────────► │ logQueue │◄┘
│ ≈9608 B │ │ 环形队列 │ 交易操作
└──────────┘ └──┬─────────┘ 触发日志
┌──────────┐ 32 字节固定块 │ BuildMerkleTree()
│merkle.dat│ ◄───────────────── g_merkleRoot│
│ 32 B │ │
└──────────┘ │
▲ │
└────────── VerifyMerkleTree() ──────┘
```
### 文件一览
| 文件 | 大小 | 格式 | 内容 |
|------|------|------|------|
| `bank.dat` | 2700+ B | 二进制 | 50 个 `STACCOUNT` 连续存储 |
| `log.dat` | ~9608 B | 二进制 | 完整 `LogQueue` 结构体 |
| `merkle.dat` | 32 B | 二进制 | Merkle 根哈希 |
---
## 辅助数据结构
### KMP 部分匹配表(`log.c:111`
```c
int* lps = (int*)malloc(M * sizeof(int)); // 动态分配,搜索后释放
```
用于在日志中执行模式搜索(`SearchLogs``KMPSearch`),支持任意字符串模式匹配,而非简单的 `strstr`
### 全局状态变量
| 变量 | 类型 | 位置 | 说明 |
|------|------|------|------|
| `quanxian` | `int` | `bank.c:9` | 当前会话权限:0=未登录, 1=管理员, 2=用户, -2=退出 |
| `user_id` | `int` | `bank.c:10` | 当前登录用户 ID |
| `g_iAccCount` | `int` | `bank.c:8` | 有效账户数(不含已删除的空槽) |
---
## 已知限制
- **Windows 独占**:依赖 `<io.h>` 和 Windows CryptoAPI,无法在 POSIX 系统编译。
- **固定容量**:账户 50 个,日志 99 条有效记录,超出后日志自动覆盖。
- **明文密码**:密码以 `int` 类型存储,无哈希保护。
- **管理员硬编码**:每次启动强制重置,不支持持久化管理员的密码修改。
- **单用户会话**`quanxian``user_id` 是全局变量,不支持多用户并发。
+3 -6
View File
@@ -62,6 +62,7 @@ void CreateAccount(int quanxian)
g_astAccounts[g_iAccCount] = stNewAcc; g_astAccounts[g_iAccCount] = stNewAcc;
//把记录账户数量的全局变量自增。加过之后自增,所以下标0占用,数量是1个 //把记录账户数量的全局变量自增。加过之后自增,所以下标0占用,数量是1个
HashInsert(stNewAcc.id, g_iAccCount);
g_iAccCount++; g_iAccCount++;
printf("开户成功! 账户ID: %d\n", stNewAcc.id); printf("开户成功! 账户ID: %d\n", stNewAcc.id);
@@ -133,12 +134,7 @@ int LoginAccount(int temp_id) {
*/ */
int FindAccount(int id) int FindAccount(int id)
{ {
for(int i = 0; i < g_iAccCount; i++) return HashSearch(id);
{
if(g_astAccounts[i].id == id) return i;
}
return -1;
} }
//删除账户 //删除账户
void DeleteAccount(int id) { void DeleteAccount(int id) {
@@ -151,6 +147,7 @@ void DeleteAccount(int id) {
printf("正在删除一下账户..."); printf("正在删除一下账户...");
printf("%-8d %-30s %-10.2f %-3d\n", printf("%-8d %-30s %-10.2f %-3d\n",
g_astAccounts[i].id, g_astAccounts[i].name, g_astAccounts[i].balance,g_astAccounts[i].quanxian); g_astAccounts[i].id, g_astAccounts[i].name, g_astAccounts[i].balance,g_astAccounts[i].quanxian);
HashDelete(id);
for (; i < g_iAccCount-i; i++) for (; i < g_iAccCount-i; i++)
{ {
g_astAccounts[i]=g_astAccounts[i+1]; g_astAccounts[i]=g_astAccounts[i+1];
+57 -8
View File
@@ -19,7 +19,8 @@ int main(void)
printf("=== 简易银行账户管理系统 ===\n"); printf("=== 简易银行账户管理系统 ===\n");
printf("欢迎使用! 系统已加载%d个账户\n", g_iAccCount); printf("欢迎使用! 系统已加载%d个账户\n", g_iAccCount);
InitAdminAccount();//初始化管理员账号 InitAdminAccount();//初始化管理员账号
LoadMerkleRoot(); RebuildHashTable();
InitLogQueue();
int iChoice=-1; //选择标志 int iChoice=-1; //选择标志
int pChoice=-1; int pChoice=-1;
while (1) { while (1) {
@@ -59,7 +60,7 @@ int main(void)
} }
break; break;
case 1: case 1:
printf("1. 存款\n2. 取款\n3. 查询\n4. 显示所有账户\n5. 删除账户\n6. 创建管理员账户\n7.查看交易日志\n8.搜索交易日志\n9.查看默克尔根\n10.验证日志完整性\n0. 退出账户"); printf("1. 存款\n2. 取款\n3. 查询\n4. 显示所有账户\n5. 删除账户\n6. 创建管理员账户\n7.查看交易日志\n8.搜索交易日志\n9.转账\n10.资金关系图分析\n0. 退出账户");
pChoice=-1; pChoice=-1;
scanf("%d", &pChoice); scanf("%d", &pChoice);
@@ -81,6 +82,7 @@ int main(void)
scanf("%d", &d_id); scanf("%d", &d_id);
DeleteAccount(d_id); DeleteAccount(d_id);
g_iAccCount--; g_iAccCount--;
RebuildHashTable();
break; break;
case 6: case 6:
CreateAccount(1); CreateAccount(1);
@@ -90,18 +92,62 @@ int main(void)
break; break;
case 8: case 8:
printf("请输入搜索内容"); printf("请输入搜索内容");
{
char pattern[50]; char pattern[50];
scanf("%s", pattern); scanf("%s", pattern);
SearchLogs(pattern); SearchLogs(pattern);
}
break; break;
case 9: case 9:
PrintMerkleRoot(); Transfer(user_id);
break; break;
case 10: case 10:
if (VerifyMerkleTree()) {
printf("\n默克尔树验证通过,日志未被篡改。\n"); int g_choice;
else do {
printf("\n警告:默克尔树验证失败,日志可能已被篡改!\n"); printf("\n=== 资金关系图分析 ===\n");
printf("1. 显示全部转账关系图\n");
printf("2. 查看指定账户关联关系\n");
printf("3. 查看最活跃账户排名\n");
printf("4. 查找转账路径\n");
printf("5. 生成虚拟交易记录\n");
printf("0. 返回\n");
printf("请选择: ");
scanf("%d", &g_choice);
switch(g_choice) {
case 1:
ShowTransferGraph();
break;
case 2: {
int search_id;
printf("请输入账户ID: ");
scanf("%d", &search_id);
ShowAccountRelations(search_id);
break;
}
case 3:
ShowMostActiveNodes();
break;
case 4: {
int from, to;
printf("请输入起始账户ID: ");
scanf("%d", &from);
printf("请输入目标账户ID: ");
scanf("%d", &to);
FindTransferPaths(from, to);
break;
}
case 5:
GenerateDummyData();
break;
case 0:
break;
default:
printf("无效选择!\n");
break;
}
} while (g_choice != 0);
}
break; break;
case 0://EXIT case 0://EXIT
printf("谢谢使用!\n按任意键退出"); printf("谢谢使用!\n按任意键退出");
@@ -116,7 +162,7 @@ int main(void)
} }
break; break;
case 2: case 2:
printf("1. 存款\n2. 取款\n3. 查询\n0.退出账户"); printf("1. 存款\n2. 取款\n3. 查询\n4.转账\n0.退出账户");
pChoice=-1; pChoice=-1;
scanf("%d", &pChoice); scanf("%d", &pChoice);
switch(pChoice) { switch(pChoice) {
@@ -129,6 +175,9 @@ int main(void)
case 3: case 3:
QueryBalance(user_id); QueryBalance(user_id);
break; break;
case 4:
Transfer(user_id);
break;
case 0://EXIT case 0://EXIT
printf("谢谢使用!\n按任意键退出"); printf("谢谢使用!\n按任意键退出");
getchar(); getchar();
+27 -18
View File
@@ -3,6 +3,7 @@
#define MAX_LOGS 100 // 日志队列最大容量,防止无限增长 #define MAX_LOGS 100 // 日志队列最大容量,防止无限增长
#define MAX_ACCOUNTS 50 //系统规格为50个账户 #define MAX_ACCOUNTS 50 //系统规格为50个账户
#define NAME_LEN 31 //用户名字最长30字符,因此需要多1个字符串结束符 #define NAME_LEN 31 //用户名字最长30字符,因此需要多1个字符串结束符
#define HASH_SIZE 101 //哈希表大小,取质数以减少冲突
// 账户信息,每个账户id对应了名字、账户余额等信息,是不是用数据结构定义比较合适? // 账户信息,每个账户id对应了名字、账户余额等信息,是不是用数据结构定义比较合适?
typedef struct strAccount typedef struct strAccount
@@ -15,6 +16,21 @@ typedef struct strAccount
} STACCOUNT; } STACCOUNT;
// strAccount STACCOUNT; // strAccount STACCOUNT;
// 哈希表条目,映射账户ID到g_astAccounts数组下标
typedef struct {
int id; // 账户ID-1表示空槽位
int index; // g_astAccounts中的下标
} HashEntry;
extern HashEntry g_hashTable[HASH_SIZE];
// 哈希表操作
void InitHashTable();
int HashInsert(int id, int index);
int HashSearch(int id);
void HashDelete(int id);
void RebuildHashTable();
// 函数声明,main函数中调用的各模块函数需要在程序公用的.h中声明 // 函数声明,main函数中调用的各模块函数需要在程序公用的.h中声明
// 公开出来被其他模块调用的函数,也应该在公用的.h中声明 // 公开出来被其他模块调用的函数,也应该在公用的.h中声明
@@ -54,7 +70,8 @@ void InitAdminAccount();
// 日志条目结构 // 日志条目结构
typedef struct { typedef struct {
int account_id; // 涉及的账户ID int account_id; // 涉及的账户ID
char type[10]; // 操作类型: "Deposit" 或 "Withdraw" int target_id; // 转账目标账户ID,非转账为-1
char type[10]; // 操作类型: "Deposit","Withdraw","Transfer","Receive"
double amount; // 交易金额 double amount; // 交易金额
double balance; // 交易后的余额 double balance; // 交易后的余额
char timestamp[20]; // 时间戳 (格式: YYYY-MM-DD HH:MM:SS) char timestamp[20]; // 时间戳 (格式: YYYY-MM-DD HH:MM:SS)
@@ -75,27 +92,19 @@ extern LogQueue g_logQueue;
void InitLogQueue(); // 初始化队列 void InitLogQueue(); // 初始化队列
int IsLogQueueFull(); // 检查队列是否满 int IsLogQueueFull(); // 检查队列是否满
int IsLogQueueEmpty(); // 检查队列是否空 int IsLogQueueEmpty(); // 检查队列是否空
int EnqueueLog(int id, const char* type, double amt, double bal); // 入队 int EnqueueLog(int id, const char* type, double amt, double bal, int target); // 入队
void ShowTransactionLogs(); // 显示所有日志 void ShowTransactionLogs(); // 显示所有日志
void SearchLogs(const char* pattern);//日志搜索 void SearchLogs(const char* pattern);//日志搜索
int GetLogCount(); // 转账功能
void Transfer(int from_id);
#define HASH_SIZE 32 // 资金关系图分析
void ShowTransferGraph();
typedef struct { void ShowAccountRelations(int id);
unsigned char data[HASH_SIZE]; void ShowMostActiveNodes();
} HashValue; void FindTransferPaths(int from_id, int to_id);
void GenerateDummyData();
extern HashValue g_merkleRoot;
void HashLogEntry(const LogEntry* entry, HashValue* out);
void BuildMerkleTree(HashValue* root);
void HashToHex(const HashValue* hash, char* hex_out);
void PrintMerkleRoot();
int VerifyMerkleTree();
void SaveMerkleRoot();
void LoadMerkleRoot();
#endif #endif
-32
View File
@@ -1,9 +1,6 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include "bank.h" #include "bank.h"
#include <io.h>
#define FILE_NAME bank.bat
//要操作的全局变量,但不在本模块定义需要声明为外部引入 //要操作的全局变量,但不在本模块定义需要声明为外部引入
extern STACCOUNT g_astAccounts[]; extern STACCOUNT g_astAccounts[];
@@ -22,11 +19,6 @@ void SaveData()
FILE *file = fopen("bank.dat", "wb"); FILE *file = fopen("bank.dat", "wb");
fwrite(g_astAccounts, sizeof(STACCOUNT), 50, file); fwrite(g_astAccounts, sizeof(STACCOUNT), 50, file);
fclose(file); fclose(file);
FILE *logfile = fopen("log.dat", "wb");
fwrite(&g_logQueue, sizeof(LogQueue), 1, logfile);
fclose(logfile);
LoadData(); LoadData();
} }
@@ -57,28 +49,4 @@ void LoadData()
} }
} }
g_iAccCount= result; g_iAccCount= result;
InitLogQueue();
FILE *logfile = fopen("log.dat", "rb");
if (logfile != NULL) {
fread(&g_logQueue, sizeof(LogQueue), 1, logfile);
fclose(logfile);
}
}
void SaveMerkleRoot() {
FILE* f = fopen("merkle.dat", "wb");
if (!f) return;
fwrite(g_merkleRoot.data, 1, HASH_SIZE, f);
fclose(f);
}
void LoadMerkleRoot() {
FILE* f = fopen("merkle.dat", "rb");
if (!f) {
memset(g_merkleRoot.data, 0, HASH_SIZE);
return;
}
fread(g_merkleRoot.data, 1, HASH_SIZE, f);
fclose(f);
} }
+354
View File
@@ -0,0 +1,354 @@
#include <stdio.h>
#include <string.h>
#include "bank.h"
extern LogQueue g_logQueue;
extern STACCOUNT g_astAccounts[];
extern int g_iAccCount;
// 从转账日志构建邻接矩阵,matrix[i][j] = 账户i向账户j的累计转账金额
static void BuildAdjMatrix(int matrix[MAX_ACCOUNTS][MAX_ACCOUNTS])
{
int i, j;
for (i = 0; i < g_iAccCount; i++)
for (j = 0; j < g_iAccCount; j++)
matrix[i][j] = 0;
if (IsLogQueueEmpty()) return;
int idx = g_logQueue.front;
while (idx != g_logQueue.rear) {
LogEntry e = g_logQueue.logs[idx];
if (strcmp(e.type, "Transfer") == 0 && e.target_id > 0) {
int from_idx = FindAccount(e.account_id);
int to_idx = FindAccount(e.target_id);
if (from_idx != -1 && to_idx != -1) {
matrix[from_idx][to_idx] += (int)e.amount;
}
}
idx = (idx + 1) % MAX_LOGS;
}
}
// 显示全部转账关系图
void ShowTransferGraph()
{
int matrix[MAX_ACCOUNTS][MAX_ACCOUNTS];
BuildAdjMatrix(matrix);
printf("\n=== 客户资金关系图 ===\n");
printf("(连线表示转账关系,数字为累计转账金额)\n\n");
int has_transfer = 0;
int i, j;
for (i = 0; i < g_iAccCount; i++) {
for (j = 0; j < g_iAccCount; j++) {
if (matrix[i][j] > 0) {
has_transfer = 1;
printf("%s(%d) --[%d元]--> %s(%d)\n",
g_astAccounts[i].name, g_astAccounts[i].id,
matrix[i][j],
g_astAccounts[j].name, g_astAccounts[j].id);
}
}
}
if (!has_transfer) {
printf("暂无转账记录,无法构建关系图。\n");
}
}
// 查看指定账户的关联关系
void ShowAccountRelations(int id)
{
int idx = FindAccount(id);
if (idx == -1) {
printf("账户不存在!\n");
return;
}
int matrix[MAX_ACCOUNTS][MAX_ACCOUNTS];
BuildAdjMatrix(matrix);
printf("\n=== 账户关系分析: %s(%d) ===\n",
g_astAccounts[idx].name, g_astAccounts[idx].id);
int j;
int out_count = 0;
int out_total = 0;
printf("\n[转出记录]\n");
for (j = 0; j < g_iAccCount; j++) {
if (matrix[idx][j] > 0) {
printf(" -> %s(%d): %d元\n",
g_astAccounts[j].name, g_astAccounts[j].id, matrix[idx][j]);
out_total += matrix[idx][j];
out_count++;
}
}
if (out_count == 0) printf(" 无转出记录\n");
else printf(" 共转出 %d 笔, 合计 %d 元\n", out_count, out_total);
int i;
int in_count = 0;
int in_total = 0;
printf("\n[转入记录]\n");
for (i = 0; i < g_iAccCount; i++) {
if (matrix[i][idx] > 0) {
printf(" <- %s(%d): %d元\n",
g_astAccounts[i].name, g_astAccounts[i].id, matrix[i][idx]);
in_total += matrix[i][idx];
in_count++;
}
}
if (in_count == 0) printf(" 无转入记录\n");
else printf(" 共转入 %d 笔, 合计 %d 元\n", in_count, in_total);
printf("\n总结: 转出%d笔(共%d元), 转入%d笔(共%d元)\n",
out_count, out_total, in_count, in_total);
}
// 查看最活跃账户排名(按转账关系数量排序)
void ShowMostActiveNodes()
{
int matrix[MAX_ACCOUNTS][MAX_ACCOUNTS];
BuildAdjMatrix(matrix);
int degrees[MAX_ACCOUNTS];
int account_ids[MAX_ACCOUNTS];
int i, j;
int count = 0;
for (i = 0; i < g_iAccCount; i++) {
int deg = 0;
for (j = 0; j < g_iAccCount; j++) {
if (matrix[i][j] > 0) deg++;
if (matrix[j][i] > 0) deg++;
}
if (deg > 0) {
degrees[count] = deg;
account_ids[count] = i;
count++;
}
}
if (count == 0) {
printf("\n暂无转账关系数据。\n");
return;
}
// 冒泡排序(最多50个元素)
for (i = 0; i < count - 1; i++) {
for (j = 0; j < count - 1 - i; j++) {
if (degrees[j] < degrees[j + 1]) {
int tmp_d = degrees[j];
degrees[j] = degrees[j + 1];
degrees[j + 1] = tmp_d;
int tmp_id = account_ids[j];
account_ids[j] = account_ids[j + 1];
account_ids[j + 1] = tmp_id;
}
}
}
printf("\n=== 最活跃账户排名 ===\n");
printf("%-4s %-8s %-20s %-10s\n", "排名", "ID", "姓名", "关系数");
printf("-----------------------------------------\n");
int top = count < 10 ? count : 10;
for (i = 0; i < top; i++) {
int idx = account_ids[i];
printf("%-4d %-8d %-20s %-10d\n",
i + 1, g_astAccounts[idx].id,
g_astAccounts[idx].name, degrees[i]);
}
}
// 用BFS查找两个账户间的最短转账路径
void FindTransferPaths(int from_id, int to_id)
{
int from_idx = FindAccount(from_id);
int to_idx = FindAccount(to_id);
if (from_idx == -1) { printf("源账户不存在!\n"); return; }
if (to_idx == -1) { printf("目标账户不存在!\n"); return; }
if (from_id == to_id) { printf("同一账户无需查找路径。\n"); return; }
int matrix[MAX_ACCOUNTS][MAX_ACCOUNTS];
BuildAdjMatrix(matrix);
// BFS
int visited[MAX_ACCOUNTS] = {0};
int parent[MAX_ACCOUNTS];
int queue[MAX_ACCOUNTS];
int q_front = 0, q_rear = 0;
int i;
for (i = 0; i < MAX_ACCOUNTS; i++) parent[i] = -1;
queue[q_rear++] = from_idx;
visited[from_idx] = 1;
int found = 0;
while (q_front < q_rear) {
int curr = queue[q_front++];
if (curr == to_idx) { found = 1; break; }
int j;
for (j = 0; j < g_iAccCount; j++) {
if (matrix[curr][j] > 0 && !visited[j]) {
visited[j] = 1;
parent[j] = curr;
queue[q_rear++] = j;
}
}
}
if (!found) {
printf("未找到从 %d 到 %d 的转账路径。\n", from_id, to_id);
return;
}
// 回溯路径
int path[MAX_ACCOUNTS];
int path_len = 0;
int curr = to_idx;
while (curr != -1) {
path[path_len++] = curr;
curr = parent[curr];
}
printf("\n=== 转账路径: %s(%d) -> %s(%d) ===\n",
g_astAccounts[from_idx].name, from_id,
g_astAccounts[to_idx].name, to_id);
printf("最短路径长度: %d 步\n", path_len - 1);
for (i = path_len - 1; i >= 0; i--) {
printf("%s(%d)", g_astAccounts[path[i]].name, g_astAccounts[path[i]].id);
if (i > 0) {
printf(" --[%d元]--> ", matrix[path[i]][path[i - 1]]);
}
}
printf("\n");
}
// 生成虚拟交易记录,用于测试资金关系图分析
void GenerateDummyData()
{
int i;
int orig_count = g_iAccCount;
// 如果账户不足5个,先创建测试账户(密码统一123456)
if (g_iAccCount < 5 && g_iAccCount < MAX_ACCOUNTS) {
int target = 5;
if (target > MAX_ACCOUNTS) target = MAX_ACCOUNTS;
for (i = g_iAccCount; i < target; i++) {
g_astAccounts[i].id = 1000 + i;
g_astAccounts[i].balance = (i + 1) * 5000.0;
g_astAccounts[i].password = 123456;
g_astAccounts[i].quanxian = 2;
g_astAccounts[i].name[0] = '\0';
}
// 给账户起中文名
if (orig_count <= 1) strcpy(g_astAccounts[1].name, "张三");
if (orig_count <= 2) strcpy(g_astAccounts[2].name, "李四");
if (orig_count <= 3) strcpy(g_astAccounts[3].name, "王五");
if (orig_count <= 4) strcpy(g_astAccounts[4].name, "赵六");
g_iAccCount = target;
SaveData();
printf("已补充创建%d个测试账户\n", target - orig_count);
}
// 如果有第6个槽位,创建一个钱七
if (g_iAccCount < 6 && g_iAccCount < MAX_ACCOUNTS) {
i = g_iAccCount;
g_astAccounts[i].id = 1000 + i;
strcpy(g_astAccounts[i].name, "钱七");
g_astAccounts[i].balance = 20000.0;
g_astAccounts[i].password = 123456;
g_astAccounts[i].quanxian = 2;
g_iAccCount++;
SaveData();
printf("已创建测试账户: 钱七(1005)\n");
}
// 清空旧日志,生成新的虚拟交易流水
InitLogQueue();
int id[6];
for (i = 0; i < g_iAccCount && i < 6; i++)
id[i] = g_astAccounts[i].id;
// 为每个账户存入初始资金(留痕)
for (i = 1; i < g_iAccCount && i < 6; i++) {
double bal = g_astAccounts[i].balance;
EnqueueLog(id[i], "Deposit", bal, bal, -1);
}
// 构建一个互联的转账网络:
// 张三 -> 李四 3000
// 李四 -> 王五 2000
// 王五 -> 赵六 1500
// 赵六 -> 钱七 1000
// 钱七 -> 张三 800 (形成闭环,可测路径查找)
// 张三 -> 王五 1200 (增加多条边)
// 李四 -> 钱七 600
if (g_iAccCount >= 2) {
// 张三(1) -> 李四(2): 3000
g_astAccounts[1].balance -= 3000;
g_astAccounts[2].balance += 3000;
EnqueueLog(id[1], "Transfer", 3000, g_astAccounts[1].balance, id[2]);
EnqueueLog(id[2], "Receive", 3000, g_astAccounts[2].balance, id[1]);
}
if (g_iAccCount >= 3) {
// 李四(2) -> 王五(3): 2000
g_astAccounts[2].balance -= 2000;
g_astAccounts[3].balance += 2000;
EnqueueLog(id[2], "Transfer", 2000, g_astAccounts[2].balance, id[3]);
EnqueueLog(id[3], "Receive", 2000, g_astAccounts[3].balance, id[2]);
// 张三(1) -> 王五(3): 1200
g_astAccounts[1].balance -= 1200;
g_astAccounts[3].balance += 1200;
EnqueueLog(id[1], "Transfer", 1200, g_astAccounts[1].balance, id[3]);
EnqueueLog(id[3], "Receive", 1200, g_astAccounts[3].balance, id[1]);
}
if (g_iAccCount >= 4) {
// 王五(3) -> 赵六(4): 1500
g_astAccounts[3].balance -= 1500;
g_astAccounts[4].balance += 1500;
EnqueueLog(id[3], "Transfer", 1500, g_astAccounts[3].balance, id[4]);
EnqueueLog(id[4], "Receive", 1500, g_astAccounts[4].balance, id[3]);
}
if (g_iAccCount >= 5) {
// 赵六(4) -> 钱七(5): 1000
g_astAccounts[4].balance -= 1000;
g_astAccounts[5].balance += 1000;
EnqueueLog(id[4], "Transfer", 1000, g_astAccounts[4].balance, id[5]);
EnqueueLog(id[5], "Receive", 1000, g_astAccounts[5].balance, id[4]);
// 钱七(5) -> 张三(1): 800 (闭环)
g_astAccounts[5].balance -= 800;
g_astAccounts[1].balance += 800;
EnqueueLog(id[5], "Transfer", 800, g_astAccounts[5].balance, id[1]);
EnqueueLog(id[1], "Receive", 800, g_astAccounts[1].balance, id[5]);
// 李四(2) -> 钱七(5): 600
g_astAccounts[2].balance -= 600;
g_astAccounts[5].balance += 600;
EnqueueLog(id[2], "Transfer", 600, g_astAccounts[2].balance, id[5]);
EnqueueLog(id[5], "Receive", 600, g_astAccounts[5].balance, id[2]);
}
// 为部分账户生成取款记录
if (g_iAccCount >= 3) {
g_astAccounts[1].balance -= 500;
EnqueueLog(id[1], "Withdraw", 500, g_astAccounts[1].balance, -1);
g_astAccounts[3].balance -= 300;
EnqueueLog(id[3], "Withdraw", 300, g_astAccounts[3].balance, -1);
}
SaveData();
printf("已生成 %d 条虚拟交易记录\n",
(g_logQueue.rear - g_logQueue.front + MAX_LOGS) % MAX_LOGS);
printf("账户数量: %d\n", g_iAccCount);
printf("转账网络已构建: 张三->李四->王五->赵六->钱七->张三(闭环)\n");
}
+91
View File
@@ -0,0 +1,91 @@
#include <stdio.h>
#include "bank.h"
extern STACCOUNT g_astAccounts[];
extern int g_iAccCount;
HashEntry g_hashTable[HASH_SIZE];
static int HashFunc(int id)
{
return id % HASH_SIZE;
}
void InitHashTable()
{
int i;
for (i = 0; i < HASH_SIZE; i++) {
g_hashTable[i].id = -1;
g_hashTable[i].index = -1;
}
}
int HashInsert(int id, int index)
{
int pos = HashFunc(id);
int first_tombstone = -1;
int i;
for (i = 0; i < HASH_SIZE; i++) {
int probe = (pos + i) % HASH_SIZE;
if (g_hashTable[probe].id == id) {
g_hashTable[probe].index = index;
return 0;
}
if (g_hashTable[probe].id == -1) {
if (first_tombstone != -1) {
probe = first_tombstone;
}
g_hashTable[probe].id = id;
g_hashTable[probe].index = index;
return 0;
}
if (g_hashTable[probe].id == -2 && first_tombstone == -1) {
first_tombstone = probe;
}
}
return -1;
}
int HashSearch(int id)
{
int pos = HashFunc(id);
int i;
for (i = 0; i < HASH_SIZE; i++) {
int probe = (pos + i) % HASH_SIZE;
if (g_hashTable[probe].id == id) {
return g_hashTable[probe].index;
}
if (g_hashTable[probe].id == -1) {
return -1;
}
}
return -1;
}
void HashDelete(int id)
{
int pos = HashFunc(id);
int i;
for (i = 0; i < HASH_SIZE; i++) {
int probe = (pos + i) % HASH_SIZE;
if (g_hashTable[probe].id == -1) {
return;
}
if (g_hashTable[probe].id == id) {
g_hashTable[probe].id = -2;
g_hashTable[probe].index = -1;
return;
}
}
}
void RebuildHashTable()
{
int i;
InitHashTable();
for (i = 0; i < g_iAccCount; i++) {
if (g_astAccounts[i].id != 0) {
HashInsert(g_astAccounts[i].id, i);
}
}
}
+16 -19
View File
@@ -4,13 +4,6 @@
#include <time.h> #include <time.h>
#include "bank.h" #include "bank.h"
int GetLogCount() {
if (g_logQueue.rear >= g_logQueue.front)
return g_logQueue.rear - g_logQueue.front;
else
return MAX_LOGS - g_logQueue.front + g_logQueue.rear;
}
// 初始化日志队列 // 初始化日志队列
void InitLogQueue() { void InitLogQueue() {
g_logQueue.front = 0; g_logQueue.front = 0;
@@ -38,7 +31,7 @@ void GetCurrentTimeStr(char* buf) {
// 入队操作:记录交易 // 入队操作:记录交易
// 参数: 账户ID, 类型("Deposit"/"Withdraw"), 交易金额, 交易后余额 // 参数: 账户ID, 类型("Deposit"/"Withdraw"), 交易金额, 交易后余额
int EnqueueLog(int id, const char* type, double amt, double bal) { int EnqueueLog(int id, const char* type, double amt, double bal, int target) {
// 如果队列满,通过移动 front 指针覆盖最旧的日志 (环形队列特性) // 如果队列满,通过移动 front 指针覆盖最旧的日志 (环形队列特性)
if (IsLogQueueFull()) { if (IsLogQueueFull()) {
// 覆盖旧数据,队头自动出队 // 覆盖旧数据,队头自动出队
@@ -51,15 +44,13 @@ int EnqueueLog(int id, const char* type, double amt, double bal) {
strcpy(g_logQueue.logs[pos].type, type); strcpy(g_logQueue.logs[pos].type, type);
g_logQueue.logs[pos].amount = amt; g_logQueue.logs[pos].amount = amt;
g_logQueue.logs[pos].balance = bal; g_logQueue.logs[pos].balance = bal;
g_logQueue.logs[pos].target_id = target;
GetCurrentTimeStr(g_logQueue.logs[pos].timestamp); GetCurrentTimeStr(g_logQueue.logs[pos].timestamp);
strcpy(g_logQueue.logs[pos].location, "宇宙总行"); // 根据你的需求固定地点 strcpy(g_logQueue.logs[pos].location, "宇宙总行"); // 根据你的需求固定地点
// 队尾指针后移 // 队尾指针后移
g_logQueue.rear = (g_logQueue.rear + 1) % MAX_LOGS; g_logQueue.rear = (g_logQueue.rear + 1) % MAX_LOGS;
BuildMerkleTree(&g_merkleRoot);
SaveMerkleRoot();
return 1; // 成功 return 1; // 成功
} }
@@ -71,14 +62,18 @@ void ShowTransactionLogs() {
} }
printf("\n=== 交易流水日志 ===\n"); printf("\n=== 交易流水日志 ===\n");
printf("%-5s %-8s %-10s %-10s %-15s %-20s\n", "ID", "操作", "金额", "余额", "时间", "地点"); printf("%-5s %-8s %-10s %-10s %-10s %-15s %-20s\n", "ID", "操作", "金额", "余额", "目标", "时间", "地点");
printf("--------------------------------------------------------------\n"); printf("-----------------------------------------------------------------------\n");
int i = g_logQueue.front; int i = g_logQueue.front;
while (i != g_logQueue.rear) { while (i != g_logQueue.rear) {
LogEntry e = g_logQueue.logs[i]; LogEntry e = g_logQueue.logs[i];
printf("%-5d %-8s %-10.2f %-10.2f %-15s %-20s\n", printf("%-5d %-8s %-10.2f %-10.2f ", e.account_id, e.type, e.amount, e.balance);
e.account_id, e.type, e.amount, e.balance, e.timestamp, e.location); if (e.target_id > 0)
printf("%-10d ", e.target_id);
else
printf("%-10s ", "-");
printf("%-15s %-20s\n", e.timestamp, e.location);
i = (i + 1) % MAX_LOGS; i = (i + 1) % MAX_LOGS;
} }
} }
@@ -167,17 +162,19 @@ void SearchLogs(const char* pattern) {
LogEntry e = g_logQueue.logs[i]; LogEntry e = g_logQueue.logs[i];
// 将日志条目格式化为字符串(模拟一行文本) // 将日志条目格式化为字符串(模拟一行文本)
char logLine[200]; char logLine[256];
sprintf(logLine, "ID:%d Type:%s Amount:%.2f Balance:%.2f Time:%s", sprintf(logLine, "ID:%d Type:%s Amount:%.2f Balance:%.2f Target:%d Time:%s",
e.account_id, e.type, e.amount, e.balance, e.timestamp); e.account_id, e.type, e.amount, e.balance, e.target_id, e.timestamp);
// 使用KMP检查这一行是否包含模式 // 使用KMP检查这一行是否包含模式
// 这里为了演示调用了标准 strstr,你可以将其替换为上面的 KMPSearch // 这里为了演示调用了标准 strstr,你可以将其替换为上面的 KMPSearch
// 但考虑到单行文本较短,KMP优势不大;如果是超长日志文件,KMP优势巨大 // 但考虑到单行文本较短,KMP优势不大;如果是超长日志文件,KMP优势巨大
if (strstr(logLine, pattern) != NULL) { if (strstr(logLine, pattern) != NULL) {
printf("%-3d %-8d %-10s %-10.2f %-15s\n", printf("%-3d %-8d %-10s %-10.2f %-15s",
lineNum, e.account_id, e.type, e.amount, e.timestamp); lineNum, e.account_id, e.type, e.amount, e.timestamp);
if (e.target_id > 0) printf(" -> %d", e.target_id);
printf("\n");
} }
i = (i + 1) % MAX_LOGS; i = (i + 1) % MAX_LOGS;
-98
View File
@@ -1,98 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <wincrypt.h>
#include "bank.h"
HashValue g_merkleRoot;
static HCRYPTPROV g_hProv = 0;
static void ensureProvider() {
if (g_hProv == 0)
CryptAcquireContext(&g_hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
}
static void sha256(unsigned char* out, const unsigned char* data1, unsigned int len1,
const unsigned char* data2, unsigned int len2) {
HCRYPTHASH hHash = 0;
DWORD hashLen = HASH_SIZE;
ensureProvider();
CryptCreateHash(g_hProv, CALG_SHA_256, 0, 0, &hHash);
if (data1 && len1) CryptHashData(hHash, data1, len1, 0);
if (data2 && len2) CryptHashData(hHash, data2, len2, 0);
CryptGetHashParam(hHash, HP_HASHVAL, out, &hashLen, 0);
CryptDestroyHash(hHash);
}
/* ==================== Merkle Tree ==================== */
void HashLogEntry(const LogEntry* entry, HashValue* out) {
char buf[256];
sprintf(buf, "ID:%d Type:%s Amount:%.2f Balance:%.2f Time:%s Loc:%s",
entry->account_id, entry->type, entry->amount,
entry->balance, entry->timestamp, entry->location);
sha256(out->data, (unsigned char*)buf, (unsigned int)strlen(buf), NULL, 0);
}
static void hashPair(const HashValue* a, const HashValue* b, HashValue* out) {
sha256(out->data, a->data, HASH_SIZE, b->data, HASH_SIZE);
}
void BuildMerkleTree(HashValue* root) {
int count = GetLogCount();
if (count == 0) {
memset(root->data, 0, HASH_SIZE);
return;
}
HashValue* leaves = (HashValue*)malloc(count * sizeof(HashValue));
if (!leaves) return;
int i = g_logQueue.front;
int idx = 0;
while (i != g_logQueue.rear) {
HashLogEntry(&g_logQueue.logs[i], &leaves[idx]);
i = (i + 1) % MAX_LOGS;
idx++;
}
int n = count;
while (n > 1) {
int j;
for (j = 0; j < n / 2; j++)
hashPair(&leaves[2 * j], &leaves[2 * j + 1], &leaves[j]);
if (n % 2 == 1) {
hashPair(&leaves[n - 1], &leaves[n - 1], &leaves[n / 2]);
n = n / 2 + 1;
} else {
n = n / 2;
}
}
memcpy(root->data, leaves[0].data, HASH_SIZE);
free(leaves);
}
void HashToHex(const HashValue* hash, char* hex_out) {
int i;
for (i = 0; i < HASH_SIZE; i++)
sprintf(hex_out + i * 2, "%02x", hash->data[i]);
hex_out[HASH_SIZE * 2] = '\0';
}
void PrintMerkleRoot() {
char hex[65];
HashToHex(&g_merkleRoot, hex);
printf("\n当前默克尔根: %s\n", hex);
}
int VerifyMerkleTree() {
HashValue computed;
BuildMerkleTree(&computed);
return memcmp(computed.data, g_merkleRoot.data, HASH_SIZE) == 0;
}
+58 -3
View File
@@ -31,7 +31,7 @@ void Deposit(int id)
g_astAccounts[FindAccount(id)].balance+=amount; g_astAccounts[FindAccount(id)].balance+=amount;
printf("success"); printf("success");
QueryBalance(id); QueryBalance(id);
EnqueueLog(id, "Deposit", amount, g_astAccounts[FindAccount(id)].balance); EnqueueLog(id, "Deposit", amount, g_astAccounts[FindAccount(id)].balance, -1);
SaveData(); SaveData();
break; break;
} }
@@ -67,9 +67,9 @@ void Withdraw(int id)
printf("请输入密码"); printf("请输入密码");
scanf("%d",&temp_password); scanf("%d",&temp_password);
if (g_astAccounts[FindAccount(id)].password==temp_password) { if (g_astAccounts[FindAccount(id)].password==temp_password) {
if (g_astAccounts[FindAccount(id)].balance>=amount) { if (g_astAccounts[FindAccount(id)].balance>amount) {
g_astAccounts[FindAccount(id)].balance-=amount; g_astAccounts[FindAccount(id)].balance-=amount;
EnqueueLog(id, "Withdraw", amount, g_astAccounts[FindAccount(id)].balance); EnqueueLog(id, "Withdraw", amount, g_astAccounts[FindAccount(id)].balance, -1);
printf("success"); printf("success");
QueryBalance(id); QueryBalance(id);
SaveData(); SaveData();
@@ -100,3 +100,58 @@ void QueryBalance(int id)
printf("你现在还有%f块\n",g_astAccounts[FindAccount(id)].balance); printf("你现在还有%f块\n",g_astAccounts[FindAccount(id)].balance);
return; return;
} }
void Transfer(int from_id)
{
int to_id;
int amount;
int temp_password;
int from_idx = FindAccount(from_id);
int to_idx;
printf("请输入目标账户ID: ");
scanf("%d", &to_id);
to_idx = FindAccount(to_id);
if (to_idx == -1) {
printf("目标账户不存在!\n");
return;
}
if (from_id == to_id) {
printf("不能给自己转账!\n");
return;
}
while (1) {
printf("请输入转账金额: ");
scanf("%d", &amount);
if (amount > 0) break;
printf("金额必须为正数!\n");
}
printf("请输入密码验证身份: ");
while (1) {
scanf("%d", &temp_password);
if (g_astAccounts[from_idx].password == temp_password) {
if (g_astAccounts[from_idx].balance >= amount) {
g_astAccounts[from_idx].balance -= amount;
g_astAccounts[to_idx].balance += amount;
EnqueueLog(from_id, "Transfer", amount,
g_astAccounts[from_idx].balance, to_id);
EnqueueLog(to_id, "Receive", amount,
g_astAccounts[to_idx].balance, from_id);
printf("转账成功! %d -> %d, 金额: %d\n",
from_id, to_id, amount);
printf("当前余额: %.2f\n", g_astAccounts[from_idx].balance);
SaveData();
return;
} else {
printf("余额不足! 当前余额: %.2f\n",
g_astAccounts[from_idx].balance);
return;
}
} else {
printf("密码错误,请重新输入: ");
}
}
}