mivia-verify 1.0.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: mivia-verify
3
+ Version: 1.0.0
4
+ Summary: Check a Mivia evidence pack without relying on Mivia.
5
+ Author: Mivia Software Ltd
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/MiviaCo/mivia-verify
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Multimedia :: Sound/Audio
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pynacl>=1.5
16
+ Requires-Dist: blake3>=0.4
17
+ Dynamic: license-file
18
+
19
+ # mivia-verify
20
+
21
+ Check a [Mivia](https://mivia.co) evidence pack yourself, without relying on Mivia.
22
+
23
+ Every recording registered with Mivia has a public Certificate of Registration. Its owner can download an **evidence pack**: a zip with the signed registration record, its Bitcoin timestamp and Mivia's signed, dated statement about the record. This tool checks every part of a pack and tells you, in plain language, what passed.
24
+
25
+ **What a pack proves:** what was registered, by which Mivia account, and that the record existed no later than a given Bitcoin block. **What it does not prove:** who wrote the music or who owns it. That is for contracts, registries and courts.
26
+
27
+ ## Install
28
+
29
+ Python 3.9 or later:
30
+
31
+ ```
32
+ pip install git+https://github.com/MiviaCo/mivia-verify
33
+ ```
34
+
35
+ To compare an audio file by its acoustic fingerprint, also install Chromaprint's `fpcalc` (`brew install chromaprint`, `apt install libchromaprint-tools`, or <https://acoustid.org/chromaprint>).
36
+
37
+ ## Use
38
+
39
+ ```
40
+ mivia-verify mivia-evidence-<id>-<date>.zip
41
+ mivia-verify mivia-evidence-<id>-<date>.zip --audio the-recording.wav
42
+ ```
43
+
44
+ | Option | What it does |
45
+ |---|---|
46
+ | `--audio FILE` | Check whether FILE is the exact registered file, and whether it matches the registered recording by fingerprint |
47
+ | `--offline` | No network at all: skips comparing keys with mivia.co and looking up the Bitcoin block |
48
+ | `--bitcoin-node` | Look the block up with your own Bitcoin node (`bitcoin-cli`) instead of a public block explorer |
49
+ | `--json` | Machine-readable output |
50
+
51
+ The exit code is 0 when every check that could run passed, and 1 otherwise.
52
+
53
+ ## What it checks
54
+
55
+ 1. **The record is intact.** BLAKE3 of `1-registration/manifest.json` gives the record id, the same id as in the certificate address `mivia.co/c/<id>`.
56
+ 2. **Signed by Mivia.** The Ed25519 signature in `manifest.sig` is valid for the record.
57
+ 3. **The keys are Mivia's.** The keys in the pack match the copy pinned in this repository (`src/mivia_verify/keys.py`) and the copy published at <https://mivia.co/.well-known/mivia-keys.json>.
58
+ 4. **The Bitcoin timestamp.** The OpenTimestamps proof starts from the record's BLAKE3 hash and leads to the merkle root of a Bitcoin block, confirmed with a public block explorer or your own node. Nobody, including Mivia, can backdate it.
59
+ 5. **The watermark payload** (web registrations) points to this record and to Mivia's key. Reading the payload from audio needs Mivia's decoder or the public scan on mivia.co; this tool checks that the payload in the pack belongs to the record.
60
+ 6. **Mivia's dated statement** is signed by Mivia's statement key and lists every other file in the pack with its SHA-256, so nothing can be added, removed or changed. It is Mivia's account on the date shown (assurance level, warnings, creation history, lineage, scan dates); a later pack may say more.
61
+ 7. **The audio** (with `--audio`):
62
+ - **exact file:** for records registered from October 2026, the record contains the SHA-256 of the file that was uploaded; a creator who kept that file can prove it is the one;
63
+ - **fingerprint:** compared with the registered Chromaprint fingerprint. A similarity measure: it also matches re-encoded or edited copies.
64
+
65
+ A check that could not run (offline, no proof yet, no fingerprint) is shown as `----`, not as a failure.
66
+
67
+ You do not have to trust this tool either: [SPEC.md](SPEC.md) describes the pack precisely enough to write your own checker.
68
+
69
+ ## Licence
70
+
71
+ Apache-2.0. This repository contains the pack format and the checks only; Mivia's watermarking engine is not part of it.
@@ -0,0 +1,53 @@
1
+ # mivia-verify
2
+
3
+ Check a [Mivia](https://mivia.co) evidence pack yourself, without relying on Mivia.
4
+
5
+ Every recording registered with Mivia has a public Certificate of Registration. Its owner can download an **evidence pack**: a zip with the signed registration record, its Bitcoin timestamp and Mivia's signed, dated statement about the record. This tool checks every part of a pack and tells you, in plain language, what passed.
6
+
7
+ **What a pack proves:** what was registered, by which Mivia account, and that the record existed no later than a given Bitcoin block. **What it does not prove:** who wrote the music or who owns it. That is for contracts, registries and courts.
8
+
9
+ ## Install
10
+
11
+ Python 3.9 or later:
12
+
13
+ ```
14
+ pip install git+https://github.com/MiviaCo/mivia-verify
15
+ ```
16
+
17
+ To compare an audio file by its acoustic fingerprint, also install Chromaprint's `fpcalc` (`brew install chromaprint`, `apt install libchromaprint-tools`, or <https://acoustid.org/chromaprint>).
18
+
19
+ ## Use
20
+
21
+ ```
22
+ mivia-verify mivia-evidence-<id>-<date>.zip
23
+ mivia-verify mivia-evidence-<id>-<date>.zip --audio the-recording.wav
24
+ ```
25
+
26
+ | Option | What it does |
27
+ |---|---|
28
+ | `--audio FILE` | Check whether FILE is the exact registered file, and whether it matches the registered recording by fingerprint |
29
+ | `--offline` | No network at all: skips comparing keys with mivia.co and looking up the Bitcoin block |
30
+ | `--bitcoin-node` | Look the block up with your own Bitcoin node (`bitcoin-cli`) instead of a public block explorer |
31
+ | `--json` | Machine-readable output |
32
+
33
+ The exit code is 0 when every check that could run passed, and 1 otherwise.
34
+
35
+ ## What it checks
36
+
37
+ 1. **The record is intact.** BLAKE3 of `1-registration/manifest.json` gives the record id, the same id as in the certificate address `mivia.co/c/<id>`.
38
+ 2. **Signed by Mivia.** The Ed25519 signature in `manifest.sig` is valid for the record.
39
+ 3. **The keys are Mivia's.** The keys in the pack match the copy pinned in this repository (`src/mivia_verify/keys.py`) and the copy published at <https://mivia.co/.well-known/mivia-keys.json>.
40
+ 4. **The Bitcoin timestamp.** The OpenTimestamps proof starts from the record's BLAKE3 hash and leads to the merkle root of a Bitcoin block, confirmed with a public block explorer or your own node. Nobody, including Mivia, can backdate it.
41
+ 5. **The watermark payload** (web registrations) points to this record and to Mivia's key. Reading the payload from audio needs Mivia's decoder or the public scan on mivia.co; this tool checks that the payload in the pack belongs to the record.
42
+ 6. **Mivia's dated statement** is signed by Mivia's statement key and lists every other file in the pack with its SHA-256, so nothing can be added, removed or changed. It is Mivia's account on the date shown (assurance level, warnings, creation history, lineage, scan dates); a later pack may say more.
43
+ 7. **The audio** (with `--audio`):
44
+ - **exact file:** for records registered from October 2026, the record contains the SHA-256 of the file that was uploaded; a creator who kept that file can prove it is the one;
45
+ - **fingerprint:** compared with the registered Chromaprint fingerprint. A similarity measure: it also matches re-encoded or edited copies.
46
+
47
+ A check that could not run (offline, no proof yet, no fingerprint) is shown as `----`, not as a failure.
48
+
49
+ You do not have to trust this tool either: [SPEC.md](SPEC.md) describes the pack precisely enough to write your own checker.
50
+
51
+ ## Licence
52
+
53
+ Apache-2.0. This repository contains the pack format and the checks only; Mivia's watermarking engine is not part of it.
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mivia-verify"
7
+ version = "1.0.0"
8
+ description = "Check a Mivia evidence pack without relying on Mivia."
9
+ readme = "README.md"
10
+ license = { text = "Apache-2.0" }
11
+ authors = [{ name = "Mivia Software Ltd" }]
12
+ requires-python = ">=3.9"
13
+ dependencies = ["pynacl>=1.5", "blake3>=0.4"]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Multimedia :: Sound/Audio",
18
+ "Topic :: Security :: Cryptography",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/MiviaCo/mivia-verify"
23
+
24
+ [project.scripts]
25
+ mivia-verify = "mivia_verify.cli:main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """Check a Mivia evidence pack without relying on Mivia."""
2
+
3
+ from .verify import Check, Keys, Verdict, verify_pack
4
+
5
+ __all__ = ["Check", "Keys", "Verdict", "verify_pack"]
6
+ __version__ = "1.0.0"
@@ -0,0 +1,91 @@
1
+ """mivia-verify: check a Mivia evidence pack from the command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import subprocess
8
+ import sys
9
+ import urllib.request
10
+ from typing import Optional, Tuple
11
+
12
+ from . import __version__, keys
13
+ from .verify import verify_pack
14
+
15
+ MARK = {True: "PASS", False: "FAIL", None: "----"}
16
+
17
+
18
+ def mempool_block(height: int) -> Optional[Tuple[str, int]]:
19
+ """Merkle root and time of a block, from a public block explorer."""
20
+ for base in ("https://mempool.space/api", "https://blockstream.info/api"):
21
+ try:
22
+ with urllib.request.urlopen(f"{base}/block-height/{height}", timeout=15) as r:
23
+ block_hash = r.read().decode().strip()
24
+ with urllib.request.urlopen(f"{base}/block/{block_hash}", timeout=15) as r:
25
+ b = json.load(r)
26
+ return b["merkle_root"], int(b["timestamp"])
27
+ except Exception:
28
+ continue
29
+ return None
30
+
31
+
32
+ def node_block(height: int) -> Optional[Tuple[str, int]]:
33
+ """Merkle root and time of a block, from your own Bitcoin node (bitcoin-cli)."""
34
+ try:
35
+ h = subprocess.run(["bitcoin-cli", "getblockhash", str(height)], capture_output=True, check=True, text=True)
36
+ b = subprocess.run(["bitcoin-cli", "getblockheader", h.stdout.strip()], capture_output=True, check=True, text=True)
37
+ j = json.loads(b.stdout)
38
+ return j["merkleroot"], int(j["time"])
39
+ except Exception:
40
+ return None
41
+
42
+
43
+ def main(argv=None) -> int:
44
+ ap = argparse.ArgumentParser(
45
+ prog="mivia-verify",
46
+ description="Check a Mivia evidence pack without relying on Mivia.",
47
+ )
48
+ ap.add_argument("pack", help="the evidence pack (.zip)")
49
+ ap.add_argument("--audio", help="an audio file to compare with the registered recording")
50
+ ap.add_argument("--offline", action="store_true", help="no network: skip the published-key and Bitcoin lookups")
51
+ ap.add_argument("--bitcoin-node", action="store_true", help="look blocks up with your own node (bitcoin-cli)")
52
+ ap.add_argument("--json", action="store_true", help="print the result as JSON")
53
+ ap.add_argument("--version", action="version", version=f"mivia-verify {__version__}")
54
+ a = ap.parse_args(argv)
55
+
56
+ with open(a.pack, "rb") as fh:
57
+ pack = fh.read()
58
+ lookup = None if a.offline else (node_block if a.bitcoin_node else mempool_block)
59
+ v = verify_pack(
60
+ pack,
61
+ audio_path=a.audio,
62
+ published=None if a.offline else keys.published(),
63
+ pinned=keys.pinned(),
64
+ block_lookup=lookup,
65
+ )
66
+
67
+ if a.json:
68
+ print(json.dumps({
69
+ "record_id": v.record_id,
70
+ "passed": not v.failed,
71
+ "checks": [c.__dict__ for c in v.checks],
72
+ }, indent=2))
73
+ return 1 if v.failed else 0
74
+
75
+ m = v.manifest
76
+ print(f"Mivia evidence pack, record {v.record_id}")
77
+ if m.get("title"):
78
+ print(f'"{m.get("title")}" registered by {m.get("creator")} on {str(m.get("created_utc", ""))[:10]}')
79
+ print()
80
+ for c in v.checks:
81
+ print(f"[{MARK[c.ok]}] {c.title}")
82
+ print(f" {c.detail}")
83
+ print()
84
+ print("Result:", "FAILED: do not rely on this pack." if v.failed else "every check that could run passed.")
85
+ print("A pack shows what was registered, by which account, and since when.")
86
+ print("It does not prove who wrote the music or who owns it.")
87
+ return 1 if v.failed else 0
88
+
89
+
90
+ if __name__ == "__main__":
91
+ sys.exit(main())
@@ -0,0 +1,43 @@
1
+ """Mivia's public keys, pinned in this repository.
2
+
3
+ The verifier compares the keys inside a pack with this copy and with the
4
+ one published at https://mivia.co/.well-known/mivia-keys.json. Two
5
+ independent copies: changing one is not enough to make a forged pack pass.
6
+
7
+ Production keys, published 2026-10-16. The platform key was read from
8
+ decode.mivia.co/healthz and matches the issuer id (447fb581) in every web
9
+ registration's watermark payload. A rotated key is added here, never
10
+ removed, so older packs keep verifying.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import json
17
+ import urllib.request
18
+ from typing import Optional
19
+
20
+ from .verify import Keys
21
+
22
+ PLATFORM_KEY_B64: Optional[str] = "1Z5ayax4CYcVDDVfmWaAaCwATMmBEH77gKVRB4kOEUc="
23
+ STATEMENT_KEY_B64: Optional[str] = "APm0sr6P9ctu6IkiFzq/IsFjZuG8/TJh+0zaAJfR4w0="
24
+
25
+ PUBLISHED_URL = "https://mivia.co/.well-known/mivia-keys.json"
26
+
27
+
28
+ def pinned() -> Optional[Keys]:
29
+ if not PLATFORM_KEY_B64 or not STATEMENT_KEY_B64:
30
+ return None
31
+ return Keys(base64.b64decode(PLATFORM_KEY_B64), base64.b64decode(STATEMENT_KEY_B64))
32
+
33
+
34
+ def published(url: str = PUBLISHED_URL, timeout: float = 10) -> Optional[Keys]:
35
+ try:
36
+ with urllib.request.urlopen(url, timeout=timeout) as r:
37
+ k = json.load(r)["keys"]
38
+ return Keys(
39
+ base64.b64decode(k["platform"]["public_key_b64"]),
40
+ base64.b64decode(k["statement"]["public_key_b64"]),
41
+ )
42
+ except Exception:
43
+ return None
@@ -0,0 +1,134 @@
1
+ """Minimal OpenTimestamps proof reader.
2
+
3
+ Walks a .ots proof from its starting digest and returns every attestation
4
+ reached, with the digest at that point. For a Bitcoin attestation that
5
+ digest is the merkle root of the block it names. Wire format:
6
+ https://github.com/opentimestamps/python-opentimestamps (core/serialize.py,
7
+ core/timestamp.py, core/op.py, core/notary.py).
8
+
9
+ Kept dependency-free on purpose so the whole check can be read in one
10
+ sitting. The standard client gives the same answer:
11
+ ots verify -d <BLAKE3 hex of manifest.json> timestamp.ots
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ from dataclasses import dataclass
18
+ from typing import List, Optional
19
+
20
+ HEADER_MAGIC = (
21
+ b"\x00OpenTimestamps\x00\x00Proof\x00\xbf\x89\xe2\xe8\x84\xe8\x92\x94"
22
+ )
23
+ VERSION = 1
24
+ OP_SHA256 = 0x08
25
+
26
+ BITCOIN = bytes.fromhex("0588960d73d71901")
27
+ PENDING = bytes.fromhex("83dfe30d2ef90c8e")
28
+
29
+
30
+ class OtsError(ValueError):
31
+ pass
32
+
33
+
34
+ @dataclass
35
+ class Attestation:
36
+ kind: str # "bitcoin", "pending" or "unknown"
37
+ digest: bytes
38
+ height: Optional[int] = None
39
+ url: Optional[str] = None
40
+
41
+
42
+ class _Reader:
43
+ def __init__(self, data: bytes):
44
+ self.data = data
45
+ self.pos = 0
46
+
47
+ def eof(self) -> bool:
48
+ return self.pos >= len(self.data)
49
+
50
+ def byte(self) -> int:
51
+ if self.eof():
52
+ raise OtsError("unexpected end of proof")
53
+ b = self.data[self.pos]
54
+ self.pos += 1
55
+ return b
56
+
57
+ def peek(self) -> int:
58
+ if self.eof():
59
+ raise OtsError("unexpected end of proof")
60
+ return self.data[self.pos]
61
+
62
+ def take(self, n: int) -> bytes:
63
+ if self.pos + n > len(self.data):
64
+ raise OtsError("unexpected end of proof")
65
+ out = self.data[self.pos : self.pos + n]
66
+ self.pos += n
67
+ return out
68
+
69
+ def varuint(self) -> int:
70
+ value, shift = 0, 0
71
+ while True:
72
+ b = self.byte()
73
+ value |= (b & 0x7F) << shift
74
+ if not b & 0x80:
75
+ return value
76
+ shift += 7
77
+ if shift > 63:
78
+ raise OtsError("varuint too long")
79
+
80
+ def varbytes(self) -> bytes:
81
+ return self.take(self.varuint())
82
+
83
+
84
+ def _apply(tag: int, r: _Reader, digest: bytes) -> bytes:
85
+ if tag == 0x08:
86
+ return hashlib.sha256(digest).digest()
87
+ if tag == 0x02:
88
+ return hashlib.sha1(digest).digest()
89
+ if tag == 0x03:
90
+ return hashlib.new("ripemd160", digest).digest()
91
+ if tag == 0xF0:
92
+ return digest + r.varbytes()
93
+ if tag == 0xF1:
94
+ return r.varbytes() + digest
95
+ if tag == 0xF2:
96
+ return digest[::-1]
97
+ if tag == 0xF3:
98
+ return digest.hex().encode()
99
+ raise OtsError(f"unsupported operation 0x{tag:02x}")
100
+
101
+
102
+ def _walk(r: _Reader, digest: bytes, out: List[Attestation]) -> None:
103
+ while True:
104
+ tag = r.byte()
105
+ if tag == 0x00:
106
+ magic = r.take(8)
107
+ payload = r.varbytes()
108
+ if magic == BITCOIN:
109
+ out.append(Attestation("bitcoin", digest, height=_Reader(payload).varuint()))
110
+ elif magic == PENDING:
111
+ p = _Reader(payload)
112
+ out.append(Attestation("pending", digest, url=p.varbytes().decode("utf-8", "replace")))
113
+ else:
114
+ out.append(Attestation("unknown", digest))
115
+ else:
116
+ _walk(r, _apply(tag, r, digest), out)
117
+ if r.eof() or r.peek() != 0xFF:
118
+ return
119
+ r.byte()
120
+
121
+
122
+ def read_file(ots_file: bytes) -> tuple[bytes, List[Attestation]]:
123
+ """Parse a complete .ots file. Returns (the digest it starts from, attestations)."""
124
+ r = _Reader(ots_file)
125
+ if r.take(len(HEADER_MAGIC)) != HEADER_MAGIC:
126
+ raise OtsError("not an OpenTimestamps file")
127
+ if r.varuint() != VERSION:
128
+ raise OtsError("unsupported OpenTimestamps version")
129
+ if r.byte() != OP_SHA256:
130
+ raise OtsError("unexpected file hash operation")
131
+ digest = r.take(32)
132
+ atts: List[Attestation] = []
133
+ _walk(r, digest, atts)
134
+ return digest, atts
@@ -0,0 +1,344 @@
1
+ """The checks. Same rules as the web checker on mivia.co; see SPEC.md."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import io
8
+ import json
9
+ import shutil
10
+ import subprocess
11
+ import zipfile
12
+ from dataclasses import dataclass, field
13
+ from datetime import datetime, timezone
14
+ from typing import Callable, Dict, List, Optional, Tuple
15
+
16
+ import blake3
17
+ from nacl.exceptions import BadSignatureError
18
+ from nacl.signing import VerifyKey
19
+
20
+ from . import ots
21
+
22
+ # Fingerprint matching, as on mivia.co (functions/_lib/chromaprint.ts).
23
+ FP_MATCH_THRESHOLD = 0.35
24
+ FP_MIN_OVERLAP_FRAMES = 80
25
+
26
+
27
+ @dataclass
28
+ class Check:
29
+ id: str
30
+ ok: Optional[bool] # True pass, False fail, None could not be checked
31
+ title: str
32
+ detail: str
33
+
34
+
35
+ @dataclass
36
+ class Keys:
37
+ platform: bytes
38
+ statement: bytes
39
+
40
+
41
+ @dataclass
42
+ class Verdict:
43
+ checks: List[Check] = field(default_factory=list)
44
+ record_id: Optional[str] = None
45
+ manifest: Dict = field(default_factory=dict)
46
+ statement: Optional[Dict] = None
47
+
48
+ @property
49
+ def failed(self) -> bool:
50
+ return any(c.ok is False for c in self.checks)
51
+
52
+
53
+ BlockLookup = Callable[[int], Optional[Tuple[str, int]]] # height -> (merkle root hex as explorers show it, unix time)
54
+
55
+
56
+ def _verify_sig(sig: Optional[bytes], msg: bytes, pub: Optional[bytes]) -> bool:
57
+ if not sig or not pub:
58
+ return False
59
+ try:
60
+ VerifyKey(pub).verify(msg, sig)
61
+ return True
62
+ except (BadSignatureError, ValueError):
63
+ return False
64
+
65
+
66
+ def _crc16(data: bytes) -> int:
67
+ crc = 0xFFFF
68
+ for byte in data:
69
+ crc ^= byte << 8
70
+ for _ in range(8):
71
+ crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
72
+ return crc
73
+
74
+
75
+ def _day(unix: int) -> str:
76
+ return datetime.fromtimestamp(unix, tz=timezone.utc).strftime("%-d %B %Y")
77
+
78
+
79
+ def _u32s(raw: bytes) -> List[int]:
80
+ return [int.from_bytes(raw[i : i + 4], "little") for i in range(0, len(raw) - len(raw) % 4, 4)]
81
+
82
+
83
+ def alignment_score(a: List[int], b: List[int]) -> float:
84
+ """Lowest bit-error rate over all alignments with at least 80 overlapping frames."""
85
+ best = 1.0
86
+ la, lb, m = len(a), len(b), FP_MIN_OVERLAP_FRAMES
87
+ for offset in range(-(lb - m), la - m + 1):
88
+ if offset >= 0:
89
+ ao, bo, n = offset, 0, min(la - offset, lb)
90
+ else:
91
+ ao, bo, n = 0, -offset, min(lb + offset, la)
92
+ diff = sum(bin(a[ao + i] ^ b[bo + i]).count("1") for i in range(n))
93
+ best = min(best, diff / (n * 32))
94
+ return best
95
+
96
+
97
+ def fpcalc_fingerprint(path: str) -> Optional[List[int]]:
98
+ """Chromaprint of an audio file, computed the way Mivia computes it at registration."""
99
+ exe = shutil.which("fpcalc")
100
+ if not exe:
101
+ return None
102
+ out = subprocess.run(
103
+ [exe, "-length", "120", "-raw", "-json", path], capture_output=True, check=False
104
+ )
105
+ if out.returncode != 0:
106
+ return None
107
+ return [v & 0xFFFFFFFF for v in json.loads(out.stdout)["fingerprint"]]
108
+
109
+
110
+ def verify_pack(
111
+ pack: bytes,
112
+ audio_path: Optional[str] = None,
113
+ published: Optional[Keys] = None,
114
+ pinned: Optional[Keys] = None,
115
+ block_lookup: Optional[BlockLookup] = None,
116
+ ) -> Verdict:
117
+ v = Verdict()
118
+ try:
119
+ with zipfile.ZipFile(io.BytesIO(pack)) as z:
120
+ files = {n: z.read(n) for n in z.namelist() if not n.endswith("/")}
121
+ except zipfile.BadZipFile:
122
+ v.checks.append(Check("record", False, "Not an evidence pack", "The file is not a readable zip."))
123
+ return v
124
+ manifest = files.get("1-registration/manifest.json")
125
+ if manifest is None:
126
+ v.checks.append(Check("record", False, "Not an evidence pack", "There is no 1-registration/manifest.json."))
127
+ return v
128
+
129
+ pack_keys: Optional[Keys] = None
130
+ try:
131
+ k = json.loads(files["3-keys/mivia-keys.json"])["keys"]
132
+ pack_keys = Keys(
133
+ base64.b64decode(k["platform"]["public_key_b64"]),
134
+ base64.b64decode(k["statement"]["public_key_b64"]),
135
+ )
136
+ except (KeyError, ValueError, TypeError):
137
+ pack_keys = None
138
+
139
+ # 1. Record integrity.
140
+ h = blake3.blake3(manifest).digest()
141
+ rid = h[:8].hex()
142
+ v.record_id = rid
143
+ try:
144
+ v.manifest = json.loads(manifest)
145
+ except ValueError:
146
+ v.manifest = {}
147
+ try:
148
+ v.statement = json.loads(files["2-statement/statement.json"])
149
+ except (KeyError, ValueError):
150
+ v.statement = None
151
+ rec = (v.statement or {}).get("record", {})
152
+ rec_ok = not rec.get("id") or (rec.get("id") == rid and rec.get("manifest_blake3") == h.hex())
153
+ v.checks.append(
154
+ Check(
155
+ "record",
156
+ rec_ok,
157
+ "The record is intact" if rec_ok else "The record does not match its id",
158
+ f"BLAKE3 of the record gives the id {rid}. Make sure this is the id in the certificate "
159
+ f"address you were given (mivia.co/c/{rid})."
160
+ if rec_ok
161
+ else f"The record's content gives the id {rid}, but the pack says {rec.get('id')}. "
162
+ "The record has been changed.",
163
+ )
164
+ )
165
+
166
+ # 2. Mivia's signature over the record.
167
+ sig_ok = _verify_sig(files.get("1-registration/manifest.sig"), manifest, pack_keys and pack_keys.platform)
168
+ v.checks.append(
169
+ Check(
170
+ "signature",
171
+ sig_ok,
172
+ "Signed by Mivia" if sig_ok else "The signature does not match",
173
+ "Mivia's Ed25519 signature on the record is valid, so it has not been changed since it was registered."
174
+ if sig_ok
175
+ else "The record was changed after signing, or was not signed by the key in this pack.",
176
+ )
177
+ )
178
+
179
+ # 3. The keys are Mivia's: compared with the copy pinned in this tool and the one on mivia.co.
180
+ if pack_keys is None:
181
+ v.checks.append(Check("keys", False, "Keys missing", "The pack has no readable 3-keys/mivia-keys.json."))
182
+ else:
183
+ refs = [(n, k) for n, k in (("this tool", pinned), ("mivia.co", published)) if k is not None]
184
+ if not refs:
185
+ v.checks.append(
186
+ Check("keys", None, "Keys not compared", "No reference copy of Mivia's keys was available.")
187
+ )
188
+ else:
189
+ bad = [n for n, k in refs if (k.platform, k.statement) != (pack_keys.platform, pack_keys.statement)]
190
+ names = " and ".join(n for n, _ in refs)
191
+ v.checks.append(
192
+ Check(
193
+ "keys",
194
+ not bad,
195
+ "The keys are Mivia's published keys" if not bad else "The keys are not Mivia's",
196
+ f"The keys in the pack match the copy held by {names}."
197
+ if not bad
198
+ else f"The keys in the pack differ from the copy held by {' and '.join(bad)}. Do not rely on it.",
199
+ )
200
+ )
201
+
202
+ # 4. Bitcoin timestamp for BLAKE3(manifest.json).
203
+ ots_file = files.get("1-registration/timestamp.ots")
204
+ if ots_file is None:
205
+ v.checks.append(Check("timestamp", None, "No timestamp yet", "The pack has no Bitcoin timestamp proof yet."))
206
+ else:
207
+ try:
208
+ start, atts = ots.read_file(ots_file)
209
+ except ots.OtsError as e:
210
+ v.checks.append(Check("timestamp", False, "The timestamp proof is damaged", str(e)))
211
+ atts, start = [], b""
212
+ if ots_file is not None and start and start != h:
213
+ v.checks.append(
214
+ Check("timestamp", False, "The timestamp is for another record",
215
+ "The proof does not start from this record's hash.")
216
+ )
217
+ elif start:
218
+ btc = [a for a in atts if a.kind == "bitcoin"]
219
+ if not btc:
220
+ v.checks.append(
221
+ Check("timestamp", None, "Timestamp waiting for Bitcoin",
222
+ "The proof is valid but not yet anchored in a Bitcoin block.")
223
+ )
224
+ elif block_lookup is None:
225
+ v.checks.append(
226
+ Check("timestamp", None, f"Claims Bitcoin block {btc[0].height}",
227
+ "Offline: the block was not looked up, so the claim was not confirmed.")
228
+ )
229
+ else:
230
+ confirmed = None
231
+ for a in btc:
232
+ found = block_lookup(a.height)
233
+ if found and a.digest[::-1].hex() == found[0].lower():
234
+ confirmed = (a.height, found[1])
235
+ break
236
+ v.checks.append(
237
+ Check("timestamp", True, f"Existed by {_day(confirmed[1])}",
238
+ f"The record is committed in Bitcoin block {confirmed[0]}, mined on {_day(confirmed[1])}. "
239
+ "Nobody, including Mivia, can backdate it.")
240
+ if confirmed
241
+ else Check("timestamp", False, "The Bitcoin block does not match",
242
+ f"The proof points to block {btc[0].height}, but that block does not contain it.")
243
+ )
244
+
245
+ # 5. The watermark payload belongs to this record.
246
+ payload_hex = files.get("1-registration/watermark-payload.hex")
247
+ if payload_hex is None:
248
+ v.checks.append(
249
+ Check("watermark", None, "No watermark payload",
250
+ "This record has no watermark payload in the pack (normal for DAW plug-in registrations).")
251
+ )
252
+ else:
253
+ try:
254
+ p = bytes.fromhex(payload_hex.decode().strip())
255
+ except ValueError:
256
+ p = b""
257
+ wm_ok = (
258
+ len(p) == 20
259
+ and p[0] == 0xFB
260
+ and _crc16(p[:18]) == int.from_bytes(p[18:20], "big")
261
+ and p[6:14] == h[:8]
262
+ and pack_keys is not None
263
+ and p[2:6] == blake3.blake3(pack_keys.platform).digest()[:4]
264
+ )
265
+ v.checks.append(
266
+ Check(
267
+ "watermark",
268
+ wm_ok,
269
+ "The watermark payload points to this record" if wm_ok else "The watermark payload does not match",
270
+ "The payload embedded in the audio carries this record's id and Mivia's issuer id. Reading it "
271
+ "from an audio file needs Mivia's decoder or the public scan on mivia.co."
272
+ if wm_ok
273
+ else "The payload in the pack does not point to this record.",
274
+ )
275
+ )
276
+
277
+ # 6. Mivia's dated statement.
278
+ st = files.get("2-statement/statement.json")
279
+ if st is None or v.statement is None:
280
+ v.checks.append(Check("statement", False, "Statement missing", "No readable 2-statement/statement.json."))
281
+ else:
282
+ s_ok = _verify_sig(files.get("2-statement/statement.sig"), st, pack_keys and pack_keys.statement)
283
+ listed = v.statement.get("files", [])
284
+ others = sorted(n for n in files if not n.startswith("2-statement/"))
285
+ list_ok = [f.get("path") for f in listed] == others and all(
286
+ hashlib.sha256(files[f["path"]]).hexdigest() == f.get("sha256") for f in listed
287
+ )
288
+ ok = s_ok and list_ok
289
+ v.checks.append(
290
+ Check(
291
+ "statement",
292
+ ok,
293
+ f"Mivia's statement of {str(v.statement.get('generated_utc', ''))[:10]} is genuine"
294
+ if ok
295
+ else "The statement does not match the pack",
296
+ "The statement is signed by Mivia and covers every other file in the pack. It is Mivia's "
297
+ "account of the record on that date; a later pack may say more (for example, a dispute)."
298
+ if ok
299
+ else ("The statement's signature is not valid." if not s_ok
300
+ else "Files were added, removed or changed after the statement was signed."),
301
+ )
302
+ )
303
+
304
+ # 7. The audio file: exact match where the record has the file's hash, fingerprint otherwise too.
305
+ if audio_path:
306
+ with open(audio_path, "rb") as fh:
307
+ got = hashlib.sha256(fh.read()).hexdigest()
308
+ want = ((v.manifest.get("extensions") or {}).get("audio") or {}).get("file_sha256")
309
+ if want:
310
+ v.checks.append(
311
+ Check("audio", True, "This is the exact file that was registered",
312
+ f"Its SHA-256 ({got}) is the one signed in the record.")
313
+ if want == got
314
+ else Check("audio", False, "Not the exact registered file",
315
+ "This file is not byte-for-byte the registered one. See the fingerprint check.")
316
+ )
317
+ registered = files.get("1-registration/fingerprint.chromaprint")
318
+ if registered is None:
319
+ v.checks.append(Check("fingerprint", None, "No registered fingerprint",
320
+ "This record has no fingerprint in the pack."))
321
+ else:
322
+ fp = fpcalc_fingerprint(audio_path)
323
+ if fp is None:
324
+ v.checks.append(
325
+ Check("fingerprint", None, "Fingerprint not compared",
326
+ "Install Chromaprint's fpcalc (https://acoustid.org/chromaprint) to compare the audio.")
327
+ )
328
+ elif len(fp) < FP_MIN_OVERLAP_FRAMES or len(_u32s(registered)) < FP_MIN_OVERLAP_FRAMES:
329
+ v.checks.append(Check("fingerprint", None, "Audio too short to compare",
330
+ "At least 10 seconds of overlap are needed."))
331
+ else:
332
+ score = alignment_score(fp, _u32s(registered))
333
+ match = score < FP_MATCH_THRESHOLD
334
+ v.checks.append(
335
+ Check(
336
+ "fingerprint",
337
+ match,
338
+ "The audio matches the registered recording" if match
339
+ else "The audio does not match the registered recording",
340
+ f"Chromaprint bit-error rate {score:.3f} (a match is below {FP_MATCH_THRESHOLD}). "
341
+ "This is a similarity measure: it also matches re-encoded or edited copies.",
342
+ )
343
+ )
344
+ return v
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: mivia-verify
3
+ Version: 1.0.0
4
+ Summary: Check a Mivia evidence pack without relying on Mivia.
5
+ Author: Mivia Software Ltd
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/MiviaCo/mivia-verify
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Multimedia :: Sound/Audio
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: pynacl>=1.5
16
+ Requires-Dist: blake3>=0.4
17
+ Dynamic: license-file
18
+
19
+ # mivia-verify
20
+
21
+ Check a [Mivia](https://mivia.co) evidence pack yourself, without relying on Mivia.
22
+
23
+ Every recording registered with Mivia has a public Certificate of Registration. Its owner can download an **evidence pack**: a zip with the signed registration record, its Bitcoin timestamp and Mivia's signed, dated statement about the record. This tool checks every part of a pack and tells you, in plain language, what passed.
24
+
25
+ **What a pack proves:** what was registered, by which Mivia account, and that the record existed no later than a given Bitcoin block. **What it does not prove:** who wrote the music or who owns it. That is for contracts, registries and courts.
26
+
27
+ ## Install
28
+
29
+ Python 3.9 or later:
30
+
31
+ ```
32
+ pip install git+https://github.com/MiviaCo/mivia-verify
33
+ ```
34
+
35
+ To compare an audio file by its acoustic fingerprint, also install Chromaprint's `fpcalc` (`brew install chromaprint`, `apt install libchromaprint-tools`, or <https://acoustid.org/chromaprint>).
36
+
37
+ ## Use
38
+
39
+ ```
40
+ mivia-verify mivia-evidence-<id>-<date>.zip
41
+ mivia-verify mivia-evidence-<id>-<date>.zip --audio the-recording.wav
42
+ ```
43
+
44
+ | Option | What it does |
45
+ |---|---|
46
+ | `--audio FILE` | Check whether FILE is the exact registered file, and whether it matches the registered recording by fingerprint |
47
+ | `--offline` | No network at all: skips comparing keys with mivia.co and looking up the Bitcoin block |
48
+ | `--bitcoin-node` | Look the block up with your own Bitcoin node (`bitcoin-cli`) instead of a public block explorer |
49
+ | `--json` | Machine-readable output |
50
+
51
+ The exit code is 0 when every check that could run passed, and 1 otherwise.
52
+
53
+ ## What it checks
54
+
55
+ 1. **The record is intact.** BLAKE3 of `1-registration/manifest.json` gives the record id, the same id as in the certificate address `mivia.co/c/<id>`.
56
+ 2. **Signed by Mivia.** The Ed25519 signature in `manifest.sig` is valid for the record.
57
+ 3. **The keys are Mivia's.** The keys in the pack match the copy pinned in this repository (`src/mivia_verify/keys.py`) and the copy published at <https://mivia.co/.well-known/mivia-keys.json>.
58
+ 4. **The Bitcoin timestamp.** The OpenTimestamps proof starts from the record's BLAKE3 hash and leads to the merkle root of a Bitcoin block, confirmed with a public block explorer or your own node. Nobody, including Mivia, can backdate it.
59
+ 5. **The watermark payload** (web registrations) points to this record and to Mivia's key. Reading the payload from audio needs Mivia's decoder or the public scan on mivia.co; this tool checks that the payload in the pack belongs to the record.
60
+ 6. **Mivia's dated statement** is signed by Mivia's statement key and lists every other file in the pack with its SHA-256, so nothing can be added, removed or changed. It is Mivia's account on the date shown (assurance level, warnings, creation history, lineage, scan dates); a later pack may say more.
61
+ 7. **The audio** (with `--audio`):
62
+ - **exact file:** for records registered from October 2026, the record contains the SHA-256 of the file that was uploaded; a creator who kept that file can prove it is the one;
63
+ - **fingerprint:** compared with the registered Chromaprint fingerprint. A similarity measure: it also matches re-encoded or edited copies.
64
+
65
+ A check that could not run (offline, no proof yet, no fingerprint) is shown as `----`, not as a failure.
66
+
67
+ You do not have to trust this tool either: [SPEC.md](SPEC.md) describes the pack precisely enough to write your own checker.
68
+
69
+ ## Licence
70
+
71
+ Apache-2.0. This repository contains the pack format and the checks only; Mivia's watermarking engine is not part of it.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/mivia_verify/__init__.py
5
+ src/mivia_verify/cli.py
6
+ src/mivia_verify/keys.py
7
+ src/mivia_verify/ots.py
8
+ src/mivia_verify/verify.py
9
+ src/mivia_verify.egg-info/PKG-INFO
10
+ src/mivia_verify.egg-info/SOURCES.txt
11
+ src/mivia_verify.egg-info/dependency_links.txt
12
+ src/mivia_verify.egg-info/entry_points.txt
13
+ src/mivia_verify.egg-info/requires.txt
14
+ src/mivia_verify.egg-info/top_level.txt
15
+ tests/test_verify.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mivia-verify = mivia_verify.cli:main
@@ -0,0 +1,2 @@
1
+ pynacl>=1.5
2
+ blake3>=0.4
@@ -0,0 +1 @@
1
+ mivia_verify
@@ -0,0 +1,173 @@
1
+ """Tests build packs the way mivia.co does (functions/_lib/evidence.ts) and tamper with them."""
2
+
3
+ import hashlib
4
+ import io
5
+ import json
6
+ import os
7
+ import zipfile
8
+ from pathlib import Path
9
+
10
+ import blake3
11
+ import pytest
12
+ from nacl.signing import SigningKey
13
+
14
+ from mivia_verify import Keys, verify_pack
15
+ from mivia_verify import ots as ots_mod
16
+
17
+ PLATFORM = SigningKey(bytes([7]) * 32)
18
+ STATEMENT = SigningKey(bytes([9]) * 32)
19
+ KEYS = Keys(bytes(PLATFORM.verify_key), bytes(STATEMENT.verify_key))
20
+ AUDIO = b"RIFF....fake wav bytes"
21
+
22
+
23
+ def canonical(d):
24
+ return json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
25
+
26
+
27
+ MANIFEST = canonical({
28
+ "created_utc": "2026-10-15T12:00:00Z",
29
+ "creator": "Artist",
30
+ "extensions": {"audio": {"file_sha256": hashlib.sha256(AUDIO).hexdigest()}},
31
+ "title": "Song",
32
+ })
33
+ H = blake3.blake3(MANIFEST).digest()
34
+ APPEND = bytes([3]) * 16
35
+ TREE = bytes([0xF0, 16]) + APPEND + bytes([0x08, 0x00]) + ots_mod.BITCOIN + bytes([3, 0xA0, 0xF7, 0x36])
36
+ MERKLE = hashlib.sha256(H + APPEND).digest()
37
+
38
+
39
+ def lookup(height):
40
+ return (MERKLE[::-1].hex(), 1760500000) if height == 900000 else None
41
+
42
+
43
+ def crc16(data):
44
+ crc = 0xFFFF
45
+ for b in data:
46
+ crc ^= b << 8
47
+ for _ in range(8):
48
+ crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
49
+ return crc
50
+
51
+
52
+ def payload():
53
+ p = bytes([0xFB, 5]) + blake3.blake3(KEYS.platform).digest()[:4] + H[:8] + bytes(4)
54
+ return p + crc16(p).to_bytes(2, "big")
55
+
56
+
57
+ def files():
58
+ import base64
59
+ keys = {"keys": {
60
+ "platform": {"public_key_b64": base64.b64encode(KEYS.platform).decode()},
61
+ "statement": {"public_key_b64": base64.b64encode(KEYS.statement).decode()},
62
+ }}
63
+ f = {
64
+ "1-registration/manifest.json": MANIFEST,
65
+ "1-registration/manifest.sig": PLATFORM.sign(MANIFEST).signature,
66
+ "1-registration/timestamp.ots": ots_mod.HEADER_MAGIC + b"\x01\x08" + H + TREE,
67
+ "1-registration/watermark-payload.hex": (payload().hex() + "\n").encode(),
68
+ "3-keys/mivia-keys.json": json.dumps(keys).encode(),
69
+ "README.txt": b"readme",
70
+ }
71
+ return f
72
+
73
+
74
+ def seal(f):
75
+ st = canonical({
76
+ "generated_utc": "2026-10-20T09:00:00.000Z",
77
+ "record": {"id": H[:8].hex(), "manifest_blake3": H.hex()},
78
+ "files": [{"path": p, "sha256": hashlib.sha256(f[p]).hexdigest()} for p in sorted(f)],
79
+ })
80
+ f["2-statement/statement.json"] = st
81
+ f["2-statement/statement.sig"] = STATEMENT.sign(st).signature
82
+ return f
83
+
84
+
85
+ def zipped(f):
86
+ buf = io.BytesIO()
87
+ with zipfile.ZipFile(buf, "w") as z:
88
+ for k, v in f.items():
89
+ z.writestr(k, v)
90
+ return buf.getvalue()
91
+
92
+
93
+ def results(v):
94
+ return {c.id: c.ok for c in v.checks}
95
+
96
+
97
+ @pytest.fixture
98
+ def audio(tmp_path):
99
+ p = tmp_path / "song.wav"
100
+ p.write_bytes(AUDIO)
101
+ return str(p)
102
+
103
+
104
+ def test_genuine_pack_passes(audio):
105
+ v = verify_pack(zipped(seal(files())), audio_path=audio, published=KEYS, pinned=KEYS, block_lookup=lookup)
106
+ assert results(v) == {
107
+ "record": True, "signature": True, "keys": True, "timestamp": True,
108
+ "watermark": True, "statement": True, "audio": True, "fingerprint": None,
109
+ }
110
+ assert v.record_id == H[:8].hex()
111
+ assert not v.failed
112
+
113
+
114
+ def test_one_changed_byte_in_the_record_fails():
115
+ f = files()
116
+ m = bytearray(f["1-registration/manifest.json"])
117
+ m[10] ^= 1
118
+ f["1-registration/manifest.json"] = bytes(m)
119
+ r = results(verify_pack(zipped(seal(files()) | {"1-registration/manifest.json": bytes(m)}), published=KEYS, block_lookup=lookup))
120
+ assert r["record"] is False and r["signature"] is False and r["timestamp"] is False and r["statement"] is False
121
+
122
+
123
+ def test_edited_statement_fails():
124
+ f = seal(files())
125
+ f["2-statement/statement.json"] = f["2-statement/statement.json"].replace(b"2026-10-20", b"2026-10-21")
126
+ assert results(verify_pack(zipped(f), published=KEYS))["statement"] is False
127
+
128
+
129
+ def test_added_file_fails():
130
+ f = seal(files())
131
+ f["extra.txt"] = b"hi"
132
+ assert results(verify_pack(zipped(f), published=KEYS))["statement"] is False
133
+
134
+
135
+ def test_keys_that_differ_from_either_reference_fail():
136
+ other = Keys(bytes(SigningKey(bytes([1]) * 32).verify_key), KEYS.statement)
137
+ v = verify_pack(zipped(seal(files())), published=KEYS, pinned=other)
138
+ assert results(v)["keys"] is False
139
+
140
+
141
+ def test_wrong_bitcoin_block_fails():
142
+ v = verify_pack(zipped(seal(files())), published=KEYS, block_lookup=lambda h: ("00" * 32, 1))
143
+ assert results(v)["timestamp"] is False
144
+
145
+
146
+ def test_a_different_audio_file_fails(tmp_path):
147
+ p = tmp_path / "other.wav"
148
+ p.write_bytes(b"other")
149
+ assert results(verify_pack(zipped(seal(files())), audio_path=str(p), published=KEYS))["audio"] is False
150
+
151
+
152
+ def test_offline_reports_unchecked_not_failed():
153
+ r = results(verify_pack(zipped(seal(files()))))
154
+ assert r["keys"] is None and r["timestamp"] is None
155
+
156
+
157
+ def test_not_a_pack():
158
+ assert verify_pack(b"not a zip").failed
159
+
160
+
161
+ def test_pack_built_by_the_website_verifies():
162
+ """A pack downloaded from a local run of mivia.co (local test keys)."""
163
+ pack = (Path(__file__).parent / "vectors" / "website-pack.zip").read_bytes()
164
+ r = results(verify_pack(pack))
165
+ assert r["record"] is True and r["signature"] is True and r["statement"] is True
166
+
167
+
168
+ def test_alignment_score_identical_and_unrelated():
169
+ from mivia_verify.verify import alignment_score
170
+ a = [int.from_bytes(os.urandom(4), "little") for _ in range(200)]
171
+ b = [int.from_bytes(os.urandom(4), "little") for _ in range(200)]
172
+ assert alignment_score(a, a) == 0
173
+ assert alignment_score(a, b) > 0.35