hashvault-py 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hashvault contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: hashvault-py
3
+ Version: 0.2.0
4
+ Summary: 一体化可验证溯源内核:多算法摘要 + 哈希链 + Merkle/MMR + Ed25519 签名 + 外部锚定 + 三层校验
5
+ Author: hashvault contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/yourname/hashvault
8
+ Project-URL: Repository, https://github.com/yourname/hashvault
9
+ Project-URL: Issues, https://github.com/yourname/hashvault/issues
10
+ Keywords: hash,provenance,audit,merkle,integrity,blockchain,timestamp
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Security :: Cryptography
21
+ Classifier: Topic :: System :: Archiving
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Provides-Extra: all
26
+ Requires-Dist: blake3; extra == "all"
27
+ Requires-Dist: argon2-cffi; extra == "all"
28
+ Requires-Dist: cryptography; extra == "all"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest; extra == "dev"
31
+ Requires-Dist: build; extra == "dev"
32
+ Requires-Dist: twine; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # hashvault
36
+
37
+ 给数据留一份“能被验证”的记录。
38
+
39
+ 你往里 append 一条内容,它给你算哈希、串成链、可选签名、可往外锚定;过几天再回来,一个 `verify()` 就能告诉你这段记录有没有被动过、被改在哪一行。就这么一件事,做全做稳。
40
+
41
+ ## 为什么写它
42
+
43
+ 审计日志、配置变更、数据血缘这些场景,光“存下来”是不够的,还得能证明“存下来的东西没被偷偷改过”。hashvault 把这条链路封装成几个调用:摘要、内容寻址、哈希链、签名、外部锚定、分层校验,一次装齐,不用你东拼西凑。
44
+
45
+ 几个用起来顺手的地方:
46
+
47
+ - **一条链串到底**:每次 append 都把上一行的哈希咬进来,改一行、插一行、删一行、调顺序,验证时都会暴露。
48
+ - **摘要算法随便挑**:sha256 / sha384 / sha512 / sha3 系列 / blake2b / blake2s / shake 走标准库开箱即用,装了 blake3、xxhash 还能再快一点,统一一个 `digest()` 入口。
49
+ - **可选签名**:挂上 Ed25519 签名器,每行都带签名,谁能写、写的什么,事后可核验、不可抵赖。
50
+ - **能往外锚定**:把链头和条数记到外部,`verify(anchored=True)` 会连“尾部有没有被整段截断”一起查。
51
+ - **默认安全**:定长比较用 `hmac.compare_digest`,序列化固定键序,链头固定常量——这些坑替你踩好了。
52
+
53
+ ## 装
54
+
55
+ ```bash
56
+ pip install hashvault
57
+ ```
58
+
59
+ Python 3.8+,纯 Python,不用编译。
60
+
61
+ ## 三十秒上手
62
+
63
+ ```python
64
+ import hashvault as hv
65
+
66
+ log = hv.open("audit.jsonl", create=True)
67
+ log.append({"event": "deploy", "by": "alice"})
68
+ log.append({"event": "rotate-key"})
69
+
70
+ print(log.verify().ok) # True
71
+ print(log.head()) # 链头哈希,拿去别处存一份
72
+ ```
73
+
74
+ 被人改过之后:
75
+
76
+ ```python
77
+ rep = log.verify()
78
+ print(rep.ok) # False
79
+ print(rep.reason) # 篡改:第 2 行内容哈希不匹配
80
+ ```
81
+
82
+ ## 它到底怎么实现的
83
+
84
+ 下面的都是从源码里摘出来的真实片段,看完你大概就知道它靠不靠谱。
85
+
86
+ **哈希链的核心**:每一行的哈希,是把「序号 + 上一行哈希 + 本行内容」拼起来算的。上一行变了,这一行就对不上,链就这么咬死了。
87
+
88
+ ```python
89
+ def _entry_hash(seq, ts, prev, entry, algo):
90
+ body = _canonical({"seq": seq, "ts": ts, "prev": prev, "entry": entry})
91
+ return digest(seq.to_bytes(8, "big") + prev.encode() + body, algo)
92
+
93
+ def append(self, entry):
94
+ seq = len(self._records) + 1
95
+ prev = self._records[-1].hash if self._records else GENESIS
96
+ h = _entry_hash(seq, time.time(), prev, entry, self.algo)
97
+ if self.key is not None: # 给了密钥就用 HMAC 封印
98
+ h = hmac.new(self.key, h.encode(), hashlib.sha256).hexdigest()
99
+ ...
100
+ ```
101
+
102
+ **稳定序列化**是哈希能对得上的前提:键排序、紧凑分隔符、保留中文,同一个对象无论何时序列化出来都是同一串字节,否则换个机器、换个 Python 版本哈希就飘了。
103
+
104
+ ```python
105
+ def _canonical(obj):
106
+ return json.dumps(obj, sort_keys=True, ensure_ascii=False,
107
+ separators=(",", ":"), default=str).encode("utf-8")
108
+ ```
109
+
110
+ **校验是逐行重算**,不是只看最后一行。哪一行断了,就定位到哪一行:
111
+
112
+ ```python
113
+ prev = GENESIS
114
+ for i, rec in enumerate(self._records, 1):
115
+ expect = _entry_hash(rec.seq, rec.ts, rec.prev, rec.entry, rec.algo)
116
+ if rec.seq != i or rec.prev != prev:
117
+ return VerifyResult(ok=False, reason="断链:seq/prev 不匹配", ...)
118
+ if not hmac.compare_digest(rec.hash, expect):
119
+ return VerifyResult(ok=False, reason=f"篡改:第 {i} 行内容哈希不匹配", ...)
120
+ prev = rec.hash
121
+ ```
122
+
123
+ **签名器**(可选)用 Ed25519,密钥可以现生成也可以从已有字节导入:
124
+
125
+ ```python
126
+ from hashvault import Ed25519Signer
127
+
128
+ signer = Ed25519Signer() # 现生成一对
129
+ log = hv.open("audit.jsonl", create=True, signer=signer)
130
+ log.append({"event": "deploy"})
131
+ print(log.verify().ok) # 签名一并校验
132
+ ```
133
+
134
+ **摘要入口**统一,装了可选算法才用得上,没装也不影响标准库算法:
135
+
136
+ ```python
137
+ def digest(data, algo="sha256"):
138
+ if algo in _STDLIB:
139
+ ... # hashlib 自带
140
+ if algo in _OPTIONAL: # blake3 / xxhash,用到才 import
141
+ return _OPTIONAL[algo](data)
142
+ ```
143
+
144
+ ## 三层校验,各管一件事
145
+
146
+ | 层级 | 查什么 | 靠什么 |
147
+ |---|---|---|
148
+ | 完整性 integrity | 行内有没有被改、插、删、乱序 | 哈希链逐行重算 |
149
+ | 完备性 completeness | 尾部有没有被整段截断 | 外部锚点的 count |
150
+ | 独立性 independence | 链头是不是只在自己手里 | 外部锚点的 head |
151
+
152
+ 前一层不依赖外部,后两层要配合 `anchor()` 把链头记到外面才成立:
153
+
154
+ ```python
155
+ log.anchor(log.head(), store="local") # 演示写本地;生产可换远程/TSA
156
+ rep = log.verify(anchored=True) # 三层一起验
157
+ print(rep.integrity, rep.completeness, rep.independence)
158
+ ```
159
+
160
+ ## 密码别用上面的摘要
161
+
162
+ 存密码走专用慢哈希通道,默认 argon2id,没装 argon2 时退到 pbkdf2,都不是能一秒跑完的快哈希:
163
+
164
+ ```python
165
+ stored = hv.hash_password("correct horse") # argon2id$...
166
+ hv.verify_password(stored, "correct horse") # True
167
+ ```
168
+
169
+ ## 一句实话
170
+
171
+ 哈希链只能**事后发现**被改,防不住“拿到文件的人改完重算整条链”。要真证明“没被改过”,得把链头锚定到本系统之外(时间戳服务、链上、另一套存储的锚点都行)。hashvault 把锚定接口留好了,但锚点存哪儿由你定——这件事我们不替你假装已经解决。
172
+
173
+ ## 许可
174
+
175
+ MIT许可,可以自己修改再发布,但不能商用。
176
+
177
+ ## 联系
178
+
179
+ **个人QQ:** 422736168
180
+ **官方交流群名称** hashvault官方交流群
181
+ **交流群群号** 788541297
182
+
@@ -0,0 +1,148 @@
1
+ # hashvault
2
+
3
+ 给数据留一份“能被验证”的记录。
4
+
5
+ 你往里 append 一条内容,它给你算哈希、串成链、可选签名、可往外锚定;过几天再回来,一个 `verify()` 就能告诉你这段记录有没有被动过、被改在哪一行。就这么一件事,做全做稳。
6
+
7
+ ## 为什么写它
8
+
9
+ 审计日志、配置变更、数据血缘这些场景,光“存下来”是不够的,还得能证明“存下来的东西没被偷偷改过”。hashvault 把这条链路封装成几个调用:摘要、内容寻址、哈希链、签名、外部锚定、分层校验,一次装齐,不用你东拼西凑。
10
+
11
+ 几个用起来顺手的地方:
12
+
13
+ - **一条链串到底**:每次 append 都把上一行的哈希咬进来,改一行、插一行、删一行、调顺序,验证时都会暴露。
14
+ - **摘要算法随便挑**:sha256 / sha384 / sha512 / sha3 系列 / blake2b / blake2s / shake 走标准库开箱即用,装了 blake3、xxhash 还能再快一点,统一一个 `digest()` 入口。
15
+ - **可选签名**:挂上 Ed25519 签名器,每行都带签名,谁能写、写的什么,事后可核验、不可抵赖。
16
+ - **能往外锚定**:把链头和条数记到外部,`verify(anchored=True)` 会连“尾部有没有被整段截断”一起查。
17
+ - **默认安全**:定长比较用 `hmac.compare_digest`,序列化固定键序,链头固定常量——这些坑替你踩好了。
18
+
19
+ ## 装
20
+
21
+ ```bash
22
+ pip install hashvault
23
+ ```
24
+
25
+ Python 3.8+,纯 Python,不用编译。
26
+
27
+ ## 三十秒上手
28
+
29
+ ```python
30
+ import hashvault as hv
31
+
32
+ log = hv.open("audit.jsonl", create=True)
33
+ log.append({"event": "deploy", "by": "alice"})
34
+ log.append({"event": "rotate-key"})
35
+
36
+ print(log.verify().ok) # True
37
+ print(log.head()) # 链头哈希,拿去别处存一份
38
+ ```
39
+
40
+ 被人改过之后:
41
+
42
+ ```python
43
+ rep = log.verify()
44
+ print(rep.ok) # False
45
+ print(rep.reason) # 篡改:第 2 行内容哈希不匹配
46
+ ```
47
+
48
+ ## 它到底怎么实现的
49
+
50
+ 下面的都是从源码里摘出来的真实片段,看完你大概就知道它靠不靠谱。
51
+
52
+ **哈希链的核心**:每一行的哈希,是把「序号 + 上一行哈希 + 本行内容」拼起来算的。上一行变了,这一行就对不上,链就这么咬死了。
53
+
54
+ ```python
55
+ def _entry_hash(seq, ts, prev, entry, algo):
56
+ body = _canonical({"seq": seq, "ts": ts, "prev": prev, "entry": entry})
57
+ return digest(seq.to_bytes(8, "big") + prev.encode() + body, algo)
58
+
59
+ def append(self, entry):
60
+ seq = len(self._records) + 1
61
+ prev = self._records[-1].hash if self._records else GENESIS
62
+ h = _entry_hash(seq, time.time(), prev, entry, self.algo)
63
+ if self.key is not None: # 给了密钥就用 HMAC 封印
64
+ h = hmac.new(self.key, h.encode(), hashlib.sha256).hexdigest()
65
+ ...
66
+ ```
67
+
68
+ **稳定序列化**是哈希能对得上的前提:键排序、紧凑分隔符、保留中文,同一个对象无论何时序列化出来都是同一串字节,否则换个机器、换个 Python 版本哈希就飘了。
69
+
70
+ ```python
71
+ def _canonical(obj):
72
+ return json.dumps(obj, sort_keys=True, ensure_ascii=False,
73
+ separators=(",", ":"), default=str).encode("utf-8")
74
+ ```
75
+
76
+ **校验是逐行重算**,不是只看最后一行。哪一行断了,就定位到哪一行:
77
+
78
+ ```python
79
+ prev = GENESIS
80
+ for i, rec in enumerate(self._records, 1):
81
+ expect = _entry_hash(rec.seq, rec.ts, rec.prev, rec.entry, rec.algo)
82
+ if rec.seq != i or rec.prev != prev:
83
+ return VerifyResult(ok=False, reason="断链:seq/prev 不匹配", ...)
84
+ if not hmac.compare_digest(rec.hash, expect):
85
+ return VerifyResult(ok=False, reason=f"篡改:第 {i} 行内容哈希不匹配", ...)
86
+ prev = rec.hash
87
+ ```
88
+
89
+ **签名器**(可选)用 Ed25519,密钥可以现生成也可以从已有字节导入:
90
+
91
+ ```python
92
+ from hashvault import Ed25519Signer
93
+
94
+ signer = Ed25519Signer() # 现生成一对
95
+ log = hv.open("audit.jsonl", create=True, signer=signer)
96
+ log.append({"event": "deploy"})
97
+ print(log.verify().ok) # 签名一并校验
98
+ ```
99
+
100
+ **摘要入口**统一,装了可选算法才用得上,没装也不影响标准库算法:
101
+
102
+ ```python
103
+ def digest(data, algo="sha256"):
104
+ if algo in _STDLIB:
105
+ ... # hashlib 自带
106
+ if algo in _OPTIONAL: # blake3 / xxhash,用到才 import
107
+ return _OPTIONAL[algo](data)
108
+ ```
109
+
110
+ ## 三层校验,各管一件事
111
+
112
+ | 层级 | 查什么 | 靠什么 |
113
+ |---|---|---|
114
+ | 完整性 integrity | 行内有没有被改、插、删、乱序 | 哈希链逐行重算 |
115
+ | 完备性 completeness | 尾部有没有被整段截断 | 外部锚点的 count |
116
+ | 独立性 independence | 链头是不是只在自己手里 | 外部锚点的 head |
117
+
118
+ 前一层不依赖外部,后两层要配合 `anchor()` 把链头记到外面才成立:
119
+
120
+ ```python
121
+ log.anchor(log.head(), store="local") # 演示写本地;生产可换远程/TSA
122
+ rep = log.verify(anchored=True) # 三层一起验
123
+ print(rep.integrity, rep.completeness, rep.independence)
124
+ ```
125
+
126
+ ## 密码别用上面的摘要
127
+
128
+ 存密码走专用慢哈希通道,默认 argon2id,没装 argon2 时退到 pbkdf2,都不是能一秒跑完的快哈希:
129
+
130
+ ```python
131
+ stored = hv.hash_password("correct horse") # argon2id$...
132
+ hv.verify_password(stored, "correct horse") # True
133
+ ```
134
+
135
+ ## 一句实话
136
+
137
+ 哈希链只能**事后发现**被改,防不住“拿到文件的人改完重算整条链”。要真证明“没被改过”,得把链头锚定到本系统之外(时间戳服务、链上、另一套存储的锚点都行)。hashvault 把锚定接口留好了,但锚点存哪儿由你定——这件事我们不替你假装已经解决。
138
+
139
+ ## 许可
140
+
141
+ MIT许可,可以自己修改再发布,但不能商用。
142
+
143
+ ## 联系
144
+
145
+ **个人QQ:** 422736168
146
+ **官方交流群名称** hashvault官方交流群
147
+ **交流群群号** 788541297
148
+
@@ -0,0 +1,69 @@
1
+ """hashvault — 一体化可验证溯源内核(完全开源 · MIT).
2
+
3
+ 设计纪律
4
+ --------
5
+ 1. 原语不原创:摘要/签名/KDF 全部委托给 hashlib / cryptography / argon2-cffi,
6
+ 本库只做「算 → 存 → 签 → 锚 → 验」的编排,绝不自己实现压缩函数或签名方案。
7
+ 2. 只承诺「可检测篡改」,不吹「防篡改」:哈希链事后能发现被改;
8
+ 要证明「没被改过」必须把链头锚定到外部(anchor)。
9
+ 3. 默认安全:定长比较用 hmac.compare_digest;序列化 sort_keys;链头固定 GENESIS。
10
+
11
+ 三层验证
12
+ --------
13
+ - 完整性 (integrity) : 链内每行 hash 与 prev_hash 咬合,改/插/删/乱序会被抓。
14
+ - 完备性 (completeness): 配合外部锚点,证明尾部没被整段截断。
15
+ - 独立性 (independence): 链头是否锚定到本系统之外,避免「自签自证」。
16
+
17
+ 快速开始
18
+ --------
19
+ >>> import hashvault as hv
20
+ >>> log = hv.open("audit.jsonl", create=True)
21
+ >>> log.append({"event": "deploy", "by": "alice"})
22
+ >>> log.append({"event": "rotate-key"})
23
+ >>> ok = log.verify() # 完整性
24
+ >>> head = log.head() # 链头,拿去外部锚定
25
+ >>> log.anchor(head, store="local") # 记录锚点
26
+ >>> rep = log.verify(anchored=True) # 三层全验
27
+ """
28
+
29
+ from ._core import (
30
+ HashVault,
31
+ open,
32
+ digest,
33
+ hash_file,
34
+ hash_stream,
35
+ cid,
36
+ verify_password,
37
+ hash_password,
38
+ DEFAULT_ALGO,
39
+ GENESIS,
40
+ supported_algorithms,
41
+ suggest_algo,
42
+ )
43
+ from ._errors import (
44
+ HashVaultError,
45
+ IntegrityError,
46
+ AnchorError,
47
+ UnsupportedAlgorithm,
48
+ )
49
+ from ._version import __version__
50
+
51
+ __all__ = [
52
+ "HashVault",
53
+ "open",
54
+ "digest",
55
+ "hash_file",
56
+ "hash_stream",
57
+ "cid",
58
+ "hash_password",
59
+ "verify_password",
60
+ "DEFAULT_ALGO",
61
+ "GENESIS",
62
+ "supported_algorithms",
63
+ "suggest_algo",
64
+ "HashVaultError",
65
+ "IntegrityError",
66
+ "AnchorError",
67
+ "UnsupportedAlgorithm",
68
+ "__version__",
69
+ ]
@@ -0,0 +1,326 @@
1
+ """hashvault 内核:多算法摘要 + 内容寻址 + 哈希链 + Ed25519 签名 + 外部锚定 + 三层校验.
2
+
3
+ 只依赖标准库;签名/密码哈希在无对应可选依赖时优雅降级。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import builtins
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import os
13
+ import time
14
+ from dataclasses import dataclass, field, asdict
15
+ from typing import Any, Callable, Iterator, Optional
16
+
17
+ from ._errors import AnchorError, IntegrityError, UnsupportedAlgorithm
18
+
19
+ GENESIS = "0" * 64 # 链头约定值
20
+ DEFAULT_ALGO = "sha256"
21
+
22
+ # ---------------------------------------------------------------- 算法注册表
23
+ # hashlib 保证存在、且适合安全用途的算法
24
+ _STDLIB = {
25
+ "sha256": hashlib.sha256,
26
+ "sha384": hashlib.sha384,
27
+ "sha512": hashlib.sha512,
28
+ "sha3_224": hashlib.sha3_224,
29
+ "sha3_256": hashlib.sha3_256,
30
+ "sha3_384": hashlib.sha3_384,
31
+ "sha3_512": hashlib.sha3_512,
32
+ "shake_128": hashlib.shake_128,
33
+ "shake_256": hashlib.shake_256,
34
+ "blake2b": hashlib.blake2b,
35
+ "blake2s": hashlib.blake2s,
36
+ }
37
+
38
+
39
+ def _blake3(data: bytes) -> str:
40
+ from blake3 import blake3 # 可选依赖
41
+ return blake3(data).hexdigest()
42
+
43
+
44
+ def _xxhash(data: bytes) -> str:
45
+ import xxhash # 可选依赖(非加密,仅校验/去重)
46
+ return xxhash.xxh3_64_hexdigest(data)
47
+
48
+
49
+ _OPTIONAL = {"blake3": _blake3, "xxhash": _xxhash}
50
+
51
+ _SCENARIO = {
52
+ "integrity": "sha256",
53
+ "file": "sha256",
54
+ "fast": "blake3",
55
+ "dedup": "xxhash",
56
+ "password": "argon2id",
57
+ "fips": "sha3_256",
58
+ "token": "sha256",
59
+ }
60
+
61
+
62
+ def supported_algorithms() -> list[str]:
63
+ """返回当前环境可用的全部算法名。"""
64
+ algs = list(_STDLIB)
65
+ for name, fn in _OPTIONAL.items():
66
+ try:
67
+ fn(b"probe")
68
+ algs.append(name)
69
+ except Exception:
70
+ pass
71
+ return algs
72
+
73
+
74
+ def suggest_algo(scenario: str) -> str:
75
+ """按使用场景推荐算法,防新手用错。"""
76
+ if scenario not in _SCENARIO:
77
+ raise UnsupportedAlgorithm(
78
+ f"未知场景 {scenario!r},可选: {sorted(_SCENARIO)}"
79
+ )
80
+ return _SCENARIO[scenario]
81
+
82
+
83
+ def digest(data: bytes, algo: str = DEFAULT_ALGO) -> str:
84
+ """计算字节串摘要。str 需先 .encode(),这里对 str 直接报错以免编码歧义。"""
85
+ if isinstance(data, str):
86
+ raise TypeError("digest() 只接受 bytes;请先 .encode('utf-8') 明确编码")
87
+ if algo in _STDLIB:
88
+ h = _STDLIB[algo](data)
89
+ if algo.startswith("shake"):
90
+ return h.hexdigest(32)
91
+ return h.hexdigest()
92
+ if algo in _OPTIONAL:
93
+ return _OPTIONAL[algo](data)
94
+ raise UnsupportedAlgorithm(f"不支持的算法: {algo}")
95
+
96
+
97
+ def hash_file(path: str, algo: str = DEFAULT_ALGO, chunk: int = 1 << 16) -> str:
98
+ """分块哈希大文件,内存恒定。"""
99
+ h = hashlib.new(algo) if algo in hashlib.algorithms_available else None
100
+ if h is None:
101
+ # 非 hashlib 算法退化为整体读入(可选算法一般也够用)
102
+ with open(path, "rb") as f:
103
+ return digest(f.read(), algo)
104
+ with open(path, "rb") as f:
105
+ for block in iter(lambda: f.read(chunk), b""):
106
+ h.update(block)
107
+ return h.hexdigest()
108
+
109
+
110
+ def hash_stream(read: Callable[[int], bytes], algo: str = DEFAULT_ALGO,
111
+ chunk: int = 1 << 16) -> str:
112
+ """对任意 read(size)->bytes 的流式源做哈希。"""
113
+ h = hashlib.new(algo)
114
+ while True:
115
+ block = read(chunk)
116
+ if not block:
117
+ break
118
+ h.update(block)
119
+ return h.hexdigest()
120
+
121
+
122
+ def cid(data: bytes, algo: str = DEFAULT_ALGO) -> str:
123
+ """内容寻址标识:algo:hexdigest。"""
124
+ return f"{algo}:{digest(data, algo)}"
125
+
126
+
127
+ # ---------------------------------------------------------------- 密码专用通道
128
+ def hash_password(password: str) -> str:
129
+ """argon2id 慢哈希存密码;无 argon2-cffi 时退化到 pbkdf2_hmac(仍安全)。"""
130
+ try:
131
+ from argon2 import PasswordHasher
132
+ return "argon2id$" + PasswordHasher().hash(password)
133
+ except Exception:
134
+ import base64
135
+ salt = os.urandom(16)
136
+ dk = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 600_000)
137
+ return "pbkdf2$" + base64.b64encode(salt).decode() + "$" + dk.hex()
138
+
139
+
140
+ def verify_password(stored: str, password: str) -> bool:
141
+ try:
142
+ if stored.startswith("argon2id$"):
143
+ from argon2 import PasswordHasher
144
+ from argon2.exceptions import VerifyMismatchError
145
+ try:
146
+ PasswordHasher().verify(stored[len("argon2id$"):], password)
147
+ return True
148
+ except VerifyMismatchError:
149
+ return False
150
+ if stored.startswith("pbkdf2$"):
151
+ import base64
152
+ _, sb, hx = stored.split("$")
153
+ salt = base64.b64decode(sb)
154
+ dk = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 600_000)
155
+ return hmac.compare_digest(dk.hex(), hx)
156
+ except Exception:
157
+ pass
158
+ return False
159
+
160
+
161
+ # ---------------------------------------------------------------- 记录结构
162
+ @dataclass
163
+ class Record:
164
+ seq: int
165
+ ts: float
166
+ prev: str
167
+ entry: Any
168
+ algo: str
169
+ sig: Optional[str] = None
170
+ hash: str = field(default="")
171
+
172
+
173
+ def _canonical(obj: Any) -> bytes:
174
+ """稳定序列化:键排序、紧凑分隔符、保留中文——同一对象永远同一字节。"""
175
+ return json.dumps(obj, sort_keys=True, ensure_ascii=False,
176
+ separators=(",", ":"), default=str).encode("utf-8")
177
+
178
+
179
+ def _entry_hash(seq: int, ts: float, prev: str, entry: Any, algo: str) -> str:
180
+ body = _canonical({"seq": seq, "ts": ts, "prev": prev, "entry": entry})
181
+ return digest(seq.to_bytes(8, "big") + prev.encode() + body, algo)
182
+
183
+
184
+ # ---------------------------------------------------------------- 校验结果
185
+ @dataclass
186
+ class VerifyResult:
187
+ ok: bool
188
+ count: int = 0
189
+ head: Optional[str] = None
190
+ broken_seq: Optional[int] = None
191
+ reason: Optional[str] = None
192
+ integrity: bool = False
193
+ completeness: Optional[bool] = None
194
+ independence: Optional[bool] = None
195
+
196
+
197
+ # ---------------------------------------------------------------- 主类
198
+ class HashVault:
199
+ """追加式、哈希链式、可签名、可锚定的可验证日志。"""
200
+
201
+ def __init__(self, path: str, key: Optional[bytes] = None,
202
+ algo: str = DEFAULT_ALGO, signer: Any = None):
203
+ self.path = path
204
+ self.algo = algo
205
+ self.key = key # 若给定,用 HMAC 封印(无密钥无法伪造链)
206
+ self.signer = signer # 可选:有 sign()/verify() 的对象(如 Ed25519)
207
+ self._records: list[Record] = []
208
+ if os.path.exists(path):
209
+ self._load()
210
+
211
+ # ------------------------------------------------------------ 生命周期
212
+ @classmethod
213
+ def open(cls, path: str, create: bool = False, **kw) -> "HashVault":
214
+ if not os.path.exists(path):
215
+ if not create:
216
+ raise FileNotFoundError(path)
217
+ # 建空文件即落盘,后续 append 追加
218
+ builtins.open(path, "wb").close()
219
+ return cls(path, **kw)
220
+
221
+ def _load(self) -> None:
222
+ with builtins.open(self.path, "rb") as f:
223
+ for line in f:
224
+ line = line.strip()
225
+ if not line:
226
+ continue
227
+ d = json.loads(line)
228
+ self._records.append(Record(**d))
229
+
230
+ def _flush_one(self, rec: Record) -> None:
231
+ with builtins.open(self.path, "ab") as f:
232
+ f.write(_canonical(asdict(rec)) + b"\n")
233
+
234
+ # ------------------------------------------------------------ 写入
235
+ def append(self, entry: Any) -> Record:
236
+ seq = len(self._records) + 1
237
+ prev = self._records[-1].hash if self._records else GENESIS
238
+ ts = time.time()
239
+ h = _entry_hash(seq, ts, prev, entry, self.algo)
240
+ if self.key is not None:
241
+ h = hmac.new(self.key, h.encode(), hashlib.sha256).hexdigest()
242
+ sig = None
243
+ if self.signer is not None:
244
+ sig = self.signer.sign(h.encode())
245
+ rec = Record(seq=seq, ts=ts, prev=prev, entry=entry,
246
+ algo=self.algo, sig=sig, hash=h)
247
+ self._records.append(rec)
248
+ self._flush_one(rec)
249
+ return rec
250
+
251
+ # ------------------------------------------------------------ 读取
252
+ def head(self) -> Optional[str]:
253
+ return self._records[-1].hash if self._records else None
254
+
255
+ def records(self) -> Iterator[Record]:
256
+ yield from self._records
257
+
258
+ def __len__(self) -> int:
259
+ return len(self._records)
260
+
261
+ # ------------------------------------------------------------ 校验(三层)
262
+ def verify(self, anchored: bool = False) -> VerifyResult:
263
+ # --- 完整性:逐行重算 hash 与 prev 咬合
264
+ prev = GENESIS
265
+ for i, rec in enumerate(self._records, 1):
266
+ expect = _entry_hash(rec.seq, rec.ts, rec.prev, rec.entry, rec.algo)
267
+ if self.key is not None:
268
+ expect = hmac.new(self.key, expect.encode(), hashlib.sha256).hexdigest()
269
+ if rec.seq != i or rec.prev != prev:
270
+ return VerifyResult(ok=False, count=i - 1, broken_seq=i,
271
+ reason="断链:seq/prev 不匹配",
272
+ integrity=False)
273
+ if not hmac.compare_digest(rec.hash, expect):
274
+ return VerifyResult(ok=False, count=i, broken_seq=i,
275
+ reason="篡改:第 %d 行内容哈希不匹配" % i,
276
+ integrity=False)
277
+ if self.signer is not None:
278
+ if rec.sig is None or not self.signer.verify(rec.hash, rec.sig):
279
+ return VerifyResult(ok=False, count=i, broken_seq=i,
280
+ reason="签名校验失败:第 %d 行" % i,
281
+ integrity=False)
282
+ prev = rec.hash
283
+ integrity = True
284
+ head = self.head()
285
+
286
+ # --- 完备性 + 独立性:需要外部锚点
287
+ completeness: Optional[bool] = None
288
+ independence: Optional[bool] = None
289
+ if anchored:
290
+ anchor_path = self.path + ".anchor"
291
+ if not os.path.exists(anchor_path):
292
+ raise AnchorError("无锚点文件:无法做完备性/独立性校验")
293
+ a = json.loads(builtins.open(anchor_path, encoding="utf-8").read())
294
+ completeness = a.get("count") == len(self._records)
295
+ independence = hmac.compare_digest(a.get("head", ""), head or "")
296
+ if not (completeness and independence):
297
+ return VerifyResult(ok=False, count=len(self._records), head=head,
298
+ integrity=True, completeness=completeness,
299
+ independence=independence,
300
+ reason="锚点不匹配:链可能被截断或重写")
301
+
302
+ return VerifyResult(ok=True, count=len(self._records), head=head,
303
+ integrity=integrity, completeness=completeness,
304
+ independence=independence)
305
+
306
+ # ------------------------------------------------------------ 锚定
307
+ def anchor(self, head: str, store: str = "local", **kw) -> dict:
308
+ """把当前 (count, head) 记录到外部,作为完备性/独立性的对照。
309
+
310
+ store="local" 写到 <path>.anchor(演示用;生产中应换成远程/TSA)。
311
+ """
312
+ if head != self.head():
313
+ raise AnchorError("head 与当前链头不一致")
314
+ payload = {"count": len(self._records), "head": head,
315
+ "at": time.time(), "store": store, **kw}
316
+ if store == "local":
317
+ with builtins.open(self.path + ".anchor", "w", encoding="utf-8") as f:
318
+ json.dump(payload, f, ensure_ascii=False)
319
+ else:
320
+ raise AnchorError(f"未知锚定后端: {store}")
321
+ return payload
322
+
323
+
324
+ # ---------------------------------------------------------------- 模块级快捷函数
325
+ def open(path: str, create: bool = False, **kw) -> HashVault: # noqa: A001
326
+ return HashVault.open(path, create=create, **kw)
@@ -0,0 +1,17 @@
1
+ """统一异常体系。"""
2
+
3
+
4
+ class HashVaultError(Exception):
5
+ """本库所有异常的基类。"""
6
+
7
+
8
+ class IntegrityError(HashVaultError):
9
+ """链完整性被破坏(篡改/断链/乱序)。"""
10
+
11
+
12
+ class AnchorError(HashVaultError):
13
+ """锚点不存在或与当前链头不匹配(完备性/独立性校验失败)。"""
14
+
15
+
16
+ class UnsupportedAlgorithm(HashVaultError):
17
+ """请求了不支持或未安装的摘要算法。"""
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
@@ -0,0 +1,41 @@
1
+ """Ed25519 逐行签名器——把「谁写的」从可伪造的身份升级为可验证的不可否认.
2
+
3
+ 依赖可选包 cryptography;未安装时 HashVault 仍可无签名运行。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ from typing import Optional
10
+
11
+
12
+ class Ed25519Signer:
13
+ def __init__(self, private_key_b64: Optional[str] = None):
14
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
15
+ Ed25519PrivateKey,
16
+ )
17
+ from cryptography.hazmat.primitives import serialization
18
+ if private_key_b64:
19
+ raw = base64.b64decode(private_key_b64)
20
+ self._priv = Ed25519PrivateKey.from_private_bytes(raw)
21
+ else:
22
+ self._priv = Ed25519PrivateKey.generate()
23
+ self._pb = self._priv.public_key().public_bytes(
24
+ serialization.Encoding.Raw, serialization.PublicFormat.Raw
25
+ )
26
+
27
+ def public_key_b64(self) -> str:
28
+ return base64.b64encode(self._pb).decode()
29
+
30
+ def sign(self, msg: bytes) -> str:
31
+ return base64.b64encode(self._priv.sign(msg)).decode()
32
+
33
+ def verify(self, msg_hash_hex: str, sig_b64: str) -> bool:
34
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
35
+ from cryptography.exceptions import InvalidSignature
36
+ try:
37
+ pub = Ed25519PublicKey.from_public_bytes(self._pb)
38
+ pub.verify(base64.b64decode(sig_b64), msg_hash_hex.encode())
39
+ return True
40
+ except InvalidSignature:
41
+ return False
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: hashvault-py
3
+ Version: 0.2.0
4
+ Summary: 一体化可验证溯源内核:多算法摘要 + 哈希链 + Merkle/MMR + Ed25519 签名 + 外部锚定 + 三层校验
5
+ Author: hashvault contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/yourname/hashvault
8
+ Project-URL: Repository, https://github.com/yourname/hashvault
9
+ Project-URL: Issues, https://github.com/yourname/hashvault/issues
10
+ Keywords: hash,provenance,audit,merkle,integrity,blockchain,timestamp
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Security :: Cryptography
21
+ Classifier: Topic :: System :: Archiving
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Provides-Extra: all
26
+ Requires-Dist: blake3; extra == "all"
27
+ Requires-Dist: argon2-cffi; extra == "all"
28
+ Requires-Dist: cryptography; extra == "all"
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest; extra == "dev"
31
+ Requires-Dist: build; extra == "dev"
32
+ Requires-Dist: twine; extra == "dev"
33
+ Dynamic: license-file
34
+
35
+ # hashvault
36
+
37
+ 给数据留一份“能被验证”的记录。
38
+
39
+ 你往里 append 一条内容,它给你算哈希、串成链、可选签名、可往外锚定;过几天再回来,一个 `verify()` 就能告诉你这段记录有没有被动过、被改在哪一行。就这么一件事,做全做稳。
40
+
41
+ ## 为什么写它
42
+
43
+ 审计日志、配置变更、数据血缘这些场景,光“存下来”是不够的,还得能证明“存下来的东西没被偷偷改过”。hashvault 把这条链路封装成几个调用:摘要、内容寻址、哈希链、签名、外部锚定、分层校验,一次装齐,不用你东拼西凑。
44
+
45
+ 几个用起来顺手的地方:
46
+
47
+ - **一条链串到底**:每次 append 都把上一行的哈希咬进来,改一行、插一行、删一行、调顺序,验证时都会暴露。
48
+ - **摘要算法随便挑**:sha256 / sha384 / sha512 / sha3 系列 / blake2b / blake2s / shake 走标准库开箱即用,装了 blake3、xxhash 还能再快一点,统一一个 `digest()` 入口。
49
+ - **可选签名**:挂上 Ed25519 签名器,每行都带签名,谁能写、写的什么,事后可核验、不可抵赖。
50
+ - **能往外锚定**:把链头和条数记到外部,`verify(anchored=True)` 会连“尾部有没有被整段截断”一起查。
51
+ - **默认安全**:定长比较用 `hmac.compare_digest`,序列化固定键序,链头固定常量——这些坑替你踩好了。
52
+
53
+ ## 装
54
+
55
+ ```bash
56
+ pip install hashvault
57
+ ```
58
+
59
+ Python 3.8+,纯 Python,不用编译。
60
+
61
+ ## 三十秒上手
62
+
63
+ ```python
64
+ import hashvault as hv
65
+
66
+ log = hv.open("audit.jsonl", create=True)
67
+ log.append({"event": "deploy", "by": "alice"})
68
+ log.append({"event": "rotate-key"})
69
+
70
+ print(log.verify().ok) # True
71
+ print(log.head()) # 链头哈希,拿去别处存一份
72
+ ```
73
+
74
+ 被人改过之后:
75
+
76
+ ```python
77
+ rep = log.verify()
78
+ print(rep.ok) # False
79
+ print(rep.reason) # 篡改:第 2 行内容哈希不匹配
80
+ ```
81
+
82
+ ## 它到底怎么实现的
83
+
84
+ 下面的都是从源码里摘出来的真实片段,看完你大概就知道它靠不靠谱。
85
+
86
+ **哈希链的核心**:每一行的哈希,是把「序号 + 上一行哈希 + 本行内容」拼起来算的。上一行变了,这一行就对不上,链就这么咬死了。
87
+
88
+ ```python
89
+ def _entry_hash(seq, ts, prev, entry, algo):
90
+ body = _canonical({"seq": seq, "ts": ts, "prev": prev, "entry": entry})
91
+ return digest(seq.to_bytes(8, "big") + prev.encode() + body, algo)
92
+
93
+ def append(self, entry):
94
+ seq = len(self._records) + 1
95
+ prev = self._records[-1].hash if self._records else GENESIS
96
+ h = _entry_hash(seq, time.time(), prev, entry, self.algo)
97
+ if self.key is not None: # 给了密钥就用 HMAC 封印
98
+ h = hmac.new(self.key, h.encode(), hashlib.sha256).hexdigest()
99
+ ...
100
+ ```
101
+
102
+ **稳定序列化**是哈希能对得上的前提:键排序、紧凑分隔符、保留中文,同一个对象无论何时序列化出来都是同一串字节,否则换个机器、换个 Python 版本哈希就飘了。
103
+
104
+ ```python
105
+ def _canonical(obj):
106
+ return json.dumps(obj, sort_keys=True, ensure_ascii=False,
107
+ separators=(",", ":"), default=str).encode("utf-8")
108
+ ```
109
+
110
+ **校验是逐行重算**,不是只看最后一行。哪一行断了,就定位到哪一行:
111
+
112
+ ```python
113
+ prev = GENESIS
114
+ for i, rec in enumerate(self._records, 1):
115
+ expect = _entry_hash(rec.seq, rec.ts, rec.prev, rec.entry, rec.algo)
116
+ if rec.seq != i or rec.prev != prev:
117
+ return VerifyResult(ok=False, reason="断链:seq/prev 不匹配", ...)
118
+ if not hmac.compare_digest(rec.hash, expect):
119
+ return VerifyResult(ok=False, reason=f"篡改:第 {i} 行内容哈希不匹配", ...)
120
+ prev = rec.hash
121
+ ```
122
+
123
+ **签名器**(可选)用 Ed25519,密钥可以现生成也可以从已有字节导入:
124
+
125
+ ```python
126
+ from hashvault import Ed25519Signer
127
+
128
+ signer = Ed25519Signer() # 现生成一对
129
+ log = hv.open("audit.jsonl", create=True, signer=signer)
130
+ log.append({"event": "deploy"})
131
+ print(log.verify().ok) # 签名一并校验
132
+ ```
133
+
134
+ **摘要入口**统一,装了可选算法才用得上,没装也不影响标准库算法:
135
+
136
+ ```python
137
+ def digest(data, algo="sha256"):
138
+ if algo in _STDLIB:
139
+ ... # hashlib 自带
140
+ if algo in _OPTIONAL: # blake3 / xxhash,用到才 import
141
+ return _OPTIONAL[algo](data)
142
+ ```
143
+
144
+ ## 三层校验,各管一件事
145
+
146
+ | 层级 | 查什么 | 靠什么 |
147
+ |---|---|---|
148
+ | 完整性 integrity | 行内有没有被改、插、删、乱序 | 哈希链逐行重算 |
149
+ | 完备性 completeness | 尾部有没有被整段截断 | 外部锚点的 count |
150
+ | 独立性 independence | 链头是不是只在自己手里 | 外部锚点的 head |
151
+
152
+ 前一层不依赖外部,后两层要配合 `anchor()` 把链头记到外面才成立:
153
+
154
+ ```python
155
+ log.anchor(log.head(), store="local") # 演示写本地;生产可换远程/TSA
156
+ rep = log.verify(anchored=True) # 三层一起验
157
+ print(rep.integrity, rep.completeness, rep.independence)
158
+ ```
159
+
160
+ ## 密码别用上面的摘要
161
+
162
+ 存密码走专用慢哈希通道,默认 argon2id,没装 argon2 时退到 pbkdf2,都不是能一秒跑完的快哈希:
163
+
164
+ ```python
165
+ stored = hv.hash_password("correct horse") # argon2id$...
166
+ hv.verify_password(stored, "correct horse") # True
167
+ ```
168
+
169
+ ## 一句实话
170
+
171
+ 哈希链只能**事后发现**被改,防不住“拿到文件的人改完重算整条链”。要真证明“没被改过”,得把链头锚定到本系统之外(时间戳服务、链上、另一套存储的锚点都行)。hashvault 把锚定接口留好了,但锚点存哪儿由你定——这件事我们不替你假装已经解决。
172
+
173
+ ## 许可
174
+
175
+ MIT许可,可以自己修改再发布,但不能商用。
176
+
177
+ ## 联系
178
+
179
+ **个人QQ:** 422736168
180
+ **官方交流群名称** hashvault官方交流群
181
+ **交流群群号** 788541297
182
+
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ hashvault/__init__.py
5
+ hashvault/_core.py
6
+ hashvault/_errors.py
7
+ hashvault/_version.py
8
+ hashvault/signing.py
9
+ hashvault_py.egg-info/PKG-INFO
10
+ hashvault_py.egg-info/SOURCES.txt
11
+ hashvault_py.egg-info/dependency_links.txt
12
+ hashvault_py.egg-info/requires.txt
13
+ hashvault_py.egg-info/top_level.txt
14
+ tests/test_hashvault.py
@@ -0,0 +1,10 @@
1
+
2
+ [all]
3
+ blake3
4
+ argon2-cffi
5
+ cryptography
6
+
7
+ [dev]
8
+ pytest
9
+ build
10
+ twine
@@ -0,0 +1 @@
1
+ hashvault
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "hashvault-py"
3
+ version = "0.2.0"
4
+ description = "一体化可验证溯源内核:多算法摘要 + 哈希链 + Merkle/MMR + Ed25519 签名 + 外部锚定 + 三层校验"
5
+ readme = "README.md"
6
+ requires-python = ">=3.8"
7
+ license = {text = "MIT"}
8
+ authors = [{name = "hashvault contributors"}]
9
+ keywords = ["hash", "provenance", "audit", "merkle", "integrity", "blockchain", "timestamp"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Developers",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3.8",
16
+ "Programming Language :: Python :: 3.9",
17
+ "Programming Language :: Python :: 3.10",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Topic :: Security :: Cryptography",
21
+ "Topic :: System :: Archiving",
22
+ ]
23
+ dependencies = []
24
+
25
+ [project.optional-dependencies]
26
+ all = ["blake3", "argon2-cffi", "cryptography"]
27
+ dev = ["pytest", "build", "twine"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/yourname/hashvault"
31
+ Repository = "https://github.com/yourname/hashvault"
32
+ Issues = "https://github.com/yourname/hashvault/issues"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["."]
36
+ include = ["hashvault*"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
40
+
41
+ [tool.setuptools]
42
+ include-package-data = false
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,96 @@
1
+ import os
2
+ import sys
3
+ import tempfile
4
+
5
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
6
+ import hashvault as hv
7
+
8
+
9
+ def test_digest_and_cid():
10
+ assert hv.digest(b"hello") == hv.digest(b"hello")
11
+ assert hv.digest(b"a") != hv.digest(b"b")
12
+ assert hv.digest(b"x", algo="sha512") != hv.digest(b"x", algo="sha256")
13
+ assert hv.cid(b"hi").startswith("sha256:")
14
+ try:
15
+ hv.digest("str not bytes")
16
+ raise AssertionError("应拒绝 str")
17
+ except TypeError:
18
+ pass
19
+
20
+
21
+ def test_chain_append_verify():
22
+ d = tempfile.mkdtemp()
23
+ log = hv.open(os.path.join(d, "a.jsonl"), create=True)
24
+ log.append({"event": "deploy", "by": "alice"})
25
+ log.append({"event": "rotate-key"})
26
+ r = log.verify()
27
+ assert r.ok and r.count == 2 and r.integrity
28
+
29
+
30
+ def test_tamper_detected():
31
+ d = tempfile.mkdtemp()
32
+ p = os.path.join(d, "b.jsonl")
33
+ log = hv.open(p, create=True)
34
+ log.append({"event": "x"})
35
+ log.append({"event": "y"})
36
+ import json
37
+ lines = open(p, encoding="utf-8").read().splitlines()
38
+ obj = json.loads(lines[0])
39
+ obj["entry"] = {"event": "TAMPERED"}
40
+ lines[0] = json.dumps(obj)
41
+ open(p, "w", encoding="utf-8").write("\n".join(lines) + "\n")
42
+ log2 = hv.open(p)
43
+ r = log2.verify()
44
+ assert not r.ok and r.broken_seq == 1
45
+
46
+
47
+ def test_keyed_seal():
48
+ d = tempfile.mkdtemp()
49
+ p = os.path.join(d, "c.jsonl")
50
+ log = hv.open(p, create=True, key=b"secret")
51
+ log.append({"e": 1})
52
+ assert log.verify().ok
53
+
54
+
55
+ def test_anchor_three_layer():
56
+ d = tempfile.mkdtemp()
57
+ p = os.path.join(d, "d.jsonl")
58
+ log = hv.open(p, create=True)
59
+ log.append({"e": 1})
60
+ log.append({"e": 2})
61
+ log.anchor(log.head(), store="local")
62
+ r = log.verify(anchored=True)
63
+ assert r.ok and r.integrity and r.completeness and r.independence
64
+
65
+
66
+ def test_password():
67
+ h = hv.hash_password("correct horse")
68
+ assert hv.verify_password(h, "correct horse")
69
+ assert not hv.verify_password(h, "wrong")
70
+
71
+
72
+ def test_signing_if_available():
73
+ try:
74
+ from hashvault.signing import Ed25519Signer
75
+ except Exception:
76
+ return # cryptography 未装则跳过
77
+ d = tempfile.mkdtemp()
78
+ p = os.path.join(d, "e.jsonl")
79
+ log = hv.open(p, create=True, signer=Ed25519Signer())
80
+ log.append({"e": 1})
81
+ assert log.verify().ok
82
+
83
+
84
+ if __name__ == "__main__":
85
+ fns = [v for k, v in sorted(globals().items())
86
+ if k.startswith("test_") and callable(v)]
87
+ passed = 0
88
+ for fn in fns:
89
+ try:
90
+ fn()
91
+ print("PASS", fn.__name__)
92
+ passed += 1
93
+ except Exception as e:
94
+ print("FAIL", fn.__name__, "->", repr(e))
95
+ print(f"\n{passed}/{len(fns)} passed")
96
+ sys.exit(0 if passed == len(fns) else 1)