eventsourcingdb-merkle 0.1.0

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.
Files changed (60) hide show
  1. package/.github/CODEOWNERS +1 -0
  2. package/.github/ISSUE_TEMPLATE/bug.md +22 -0
  3. package/.github/ISSUE_TEMPLATE/feature.md +18 -0
  4. package/.github/ISSUE_TEMPLATE/task.md +18 -0
  5. package/.github/dependabot.yml +29 -0
  6. package/.github/workflows/lint-pr-title.yml +28 -0
  7. package/.github/workflows/qa.yml +30 -0
  8. package/.github/workflows/release.yml +55 -0
  9. package/README.md +210 -0
  10. package/biome.json +62 -0
  11. package/dist/chunk-EKYNFDDV.js +1 -0
  12. package/dist/chunk-KGZNHB6W.js +1 -0
  13. package/dist/chunk-M4TKYTGU.js +3 -0
  14. package/dist/chunk-UVMEMIPC.js +1 -0
  15. package/dist/chunk-XN54AB4F.js +1 -0
  16. package/dist/commands/get-proof.js +1 -0
  17. package/dist/commands/get-proof.test.js +2 -0
  18. package/dist/commands/merkle-root.js +1 -0
  19. package/dist/commands/merkle-root.test.js +2 -0
  20. package/dist/commands/validate-chain.js +1 -0
  21. package/dist/commands/validate-chain.test.js +3 -0
  22. package/dist/commands/validate-event-hash.js +1 -0
  23. package/dist/commands/validate-event-hash.test.js +2 -0
  24. package/dist/commands/verify-proof.js +1 -0
  25. package/dist/commands/verify-proof.test.js +1 -0
  26. package/dist/index.js +2 -0
  27. package/dist/lib/BaseCommand.js +1 -0
  28. package/dist/lib/backupReader.js +1 -0
  29. package/dist/lib/backupReader.test.js +1 -0
  30. package/dist/lib/chainValidator.js +1 -0
  31. package/dist/lib/chainValidator.test.js +1 -0
  32. package/dist/lib/hash.js +1 -0
  33. package/dist/lib/hash.test.js +1 -0
  34. package/dist/lib/merkleTree.js +1 -0
  35. package/dist/lib/merkleTree.test.js +1 -0
  36. package/dist/lib/types.js +0 -0
  37. package/package.json +47 -0
  38. package/src/commands/get-proof.test.ts +107 -0
  39. package/src/commands/get-proof.ts +67 -0
  40. package/src/commands/merkle-root.test.ts +96 -0
  41. package/src/commands/merkle-root.ts +35 -0
  42. package/src/commands/validate-chain.test.ts +134 -0
  43. package/src/commands/validate-chain.ts +47 -0
  44. package/src/commands/validate-event-hash.test.ts +116 -0
  45. package/src/commands/validate-event-hash.ts +117 -0
  46. package/src/commands/verify-proof.test.ts +106 -0
  47. package/src/commands/verify-proof.ts +69 -0
  48. package/src/index.ts +5 -0
  49. package/src/lib/BaseCommand.ts +24 -0
  50. package/src/lib/backupReader.test.ts +56 -0
  51. package/src/lib/backupReader.ts +81 -0
  52. package/src/lib/chainValidator.test.ts +50 -0
  53. package/src/lib/chainValidator.ts +65 -0
  54. package/src/lib/hash.test.ts +51 -0
  55. package/src/lib/hash.ts +20 -0
  56. package/src/lib/merkleTree.test.ts +131 -0
  57. package/src/lib/merkleTree.ts +92 -0
  58. package/src/lib/types.ts +38 -0
  59. package/test-fixtures/test-backup.json +4 -0
  60. package/tsconfig.json +15 -0
@@ -0,0 +1 @@
1
+ * @thenativeweb/internal_dev
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: Bug
3
+ about: Submit a bug to report erroneous behavior that needs to be fixed.
4
+ ---
5
+
6
+ ### What happened incorrectly?
7
+
8
+ …
9
+
10
+ ### What should have happened instead?
11
+
12
+ …
13
+
14
+ ### What steps are needed to reproduce the bug?
15
+
16
+ - …
17
+ - …
18
+ - …
19
+
20
+ ### What else should we know?
21
+
22
+ …
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: Feature
3
+ about: Submit a feature to request or describe new functionality to be added.
4
+ ---
5
+
6
+ ### What is this feature about?
7
+
8
+ …
9
+
10
+ ### What needs to be done to implement this feature?
11
+
12
+ - [ ] …
13
+ - [ ] …
14
+ - [ ] …
15
+
16
+ ### What else should we know?
17
+
18
+ …
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: Task
3
+ about: Submit a task to describe something that needs to get done.
4
+ ---
5
+
6
+ ### What is this task about?
7
+
8
+ …
9
+
10
+ ### What needs to be done to complete this task?
11
+
12
+ - [ ] …
13
+ - [ ] …
14
+ - [ ] …
15
+
16
+ ### What else should we know?
17
+
18
+ …
@@ -0,0 +1,29 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: npm
4
+ directory: "/"
5
+ schedule:
6
+ interval: weekly
7
+ open-pull-requests-limit: 10
8
+ assignees:
9
+ - thenativeweb/internal_dev
10
+ labels:
11
+ - Dependencies
12
+ versioning-strategy: increase
13
+ allow:
14
+ - dependency-type: direct
15
+ commit-message:
16
+ prefix: chore
17
+ prefix-development: chore
18
+
19
+ - package-ecosystem: "github-actions"
20
+ directory: "/"
21
+ schedule:
22
+ interval: "weekly"
23
+ open-pull-requests-limit: 10
24
+ assignees:
25
+ - thenativeweb/internal_dev
26
+ labels:
27
+ - Dependencies
28
+ commit-message:
29
+ prefix: chore
@@ -0,0 +1,28 @@
1
+ name: Lint PR title
2
+
3
+ on:
4
+ pull_request:
5
+ types:
6
+ - opened
7
+ - edited
8
+ - synchronize
9
+
10
+ concurrency:
11
+ group: lint-pr-title-pr-${{ github.event.pull_request.number }}
12
+ cancel-in-progress: true
13
+
14
+ jobs:
15
+ lint-pr-title:
16
+ name: Lint PR title
17
+ runs-on: ubuntu-latest
18
+ timeout-minutes: 1
19
+
20
+ steps:
21
+ - uses: amannn/action-semantic-pull-request@v6
22
+ env:
23
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
24
+ with:
25
+ types: |
26
+ chore
27
+ feat
28
+ fix
@@ -0,0 +1,30 @@
1
+ name: QA
2
+
3
+ on: pull_request
4
+
5
+ concurrency:
6
+ group: qa-pr-${{ github.event.pull_request.number }}
7
+ cancel-in-progress: true
8
+
9
+ jobs:
10
+ qa:
11
+ name: QA
12
+ runs-on: ubuntu-latest
13
+ timeout-minutes: 15
14
+
15
+ steps:
16
+ - name: Clone repository
17
+ uses: actions/checkout@v5
18
+ - name: Use Node.js
19
+ uses: actions/setup-node@v6
20
+ with:
21
+ node-version: '24.x'
22
+ - name: Install dependencies
23
+ run: |
24
+ npm ci
25
+ - name: Run QA
26
+ run: |
27
+ npm run qa
28
+ - name: Run build
29
+ run: |
30
+ npm run build
@@ -0,0 +1,55 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - "main"
7
+
8
+ permissions:
9
+ contents: write
10
+
11
+ jobs:
12
+ release:
13
+ name: Release
14
+ runs-on: ubuntu-latest
15
+ timeout-minutes: 15
16
+
17
+ steps:
18
+ - name: Clone repository
19
+ uses: actions/checkout@v5
20
+ with:
21
+ fetch-depth: "0"
22
+ token: ${{ secrets.TOKEN_GITHUB_TO_GITHUB_REPOSITORIES_RW }}
23
+ - name: Use Node.js
24
+ uses: actions/setup-node@v6
25
+ with:
26
+ node-version: 24.x
27
+ - name: Install dependencies
28
+ run: |
29
+ npm ci
30
+ - name: Run QA
31
+ run: |
32
+ npm run qa
33
+ - name: Get next version
34
+ id: get_next_version
35
+ uses: thenativeweb/get-next-version@2.7.1
36
+ - name: Create new version
37
+ if: ${{ steps.get_next_version.outputs.hasNextVersion == 'true' }}
38
+ run: |
39
+ npm version --no-git-tag-version ${{ steps.get_next_version.outputs.version }}
40
+ git config --global user.email "hello@thenativeweb.io"
41
+ git config --global user.name "${{ github.actor }}"
42
+ git add .
43
+ git commit -m 'chore: Bump version to ${{ steps.get_next_version.outputs.version }}. [skip ci]'
44
+ git push
45
+ git tag ${{ steps.get_next_version.outputs.version }}
46
+ git push origin ${{ steps.get_next_version.outputs.version }}
47
+ - name: Build artifacts
48
+ if: ${{ steps.get_next_version.outputs.hasNextVersion == 'true' }}
49
+ run: |
50
+ npm run build
51
+ - name: Publish new version
52
+ if: ${{ steps.get_next_version.outputs.hasNextVersion == 'true' }}
53
+ run: |
54
+ echo "//registry.npmjs.org/:_authToken=${{ secrets.TOKEN_GITHUB_TO_NPM_RW }}" >> .npmrc
55
+ npm publish
package/README.md ADDED
@@ -0,0 +1,210 @@
1
+ # eventsourcingdb-merkle
2
+
3
+ Merkle tree utilities for [EventSourcingDB](https://www.eventsourcingdb.io) backups.
4
+
5
+ This CLI tool provides utilities to validate, verify, and generate Merkle proofs for EventSourcingDB backup files. It enables you to ensure the integrity of event chains and create cryptographic proofs for individual events without requiring access to the entire backup.
6
+
7
+ For more information on EventSourcingDB, see its [official documentation](https://docs.eventsourcingdb.io/).
8
+
9
+ ## Getting Started
10
+
11
+ Install the CLI tool globally:
12
+
13
+ ```shell
14
+ npm install -g eventsourcingdb-merkle
15
+ ```
16
+
17
+ Or use it directly with `npx` without installing:
18
+
19
+ ```shell
20
+ npx eventsourcingdb-merkle [COMMAND]
21
+ ```
22
+
23
+ ### Validating Event Chains
24
+
25
+ To ensure that a backup file has not been tampered with or corrupted, call the `validate-chain` command and provide the path to your backup file. The command verifies that each event's hash is correctly calculated, that the predecessor hash of each event matches the hash of the previous event, and that the first event has a null predecessor hash as expected:
26
+
27
+ ```shell
28
+ eventsourcingdb-merkle validate-chain backup.json
29
+ ```
30
+
31
+ If the chain is valid, you will see a confirmation message with the total number of events:
32
+
33
+ ```
34
+ ✓ Chain is valid (8220 events)
35
+ ```
36
+
37
+ If the chain is invalid, the command lists all errors found:
38
+
39
+ ```
40
+ ✗ Chain validation failed
41
+ Total events: 8220
42
+ Errors found: 2
43
+
44
+ Event 42: Hash mismatch: expected abc..., got def...
45
+ Event 43: Predecessor hash mismatch: expected def..., got ghi...
46
+ ```
47
+
48
+ *Note that the command will exit with a non-zero exit code if the chain is invalid, which makes it suitable for use in CI/CD pipelines.*
49
+
50
+ ### Calculating the Merkle Root
51
+
52
+ To calculate the Merkle root for all events in a backup file, call the `merkle-root` command and provide the path to your backup file. The Merkle root is a single hash that represents the entire event chain and can be used to verify the integrity of the backup:
53
+
54
+ ```shell
55
+ eventsourcingdb-merkle merkle-root backup.json
56
+ ```
57
+
58
+ The command outputs the Merkle root and the total number of events:
59
+
60
+ ```
61
+ Merkle Root: d1f6713af7ba3896ff238bb51f3986b2bad53b09bda7f23370e0a8b6eb97eeab
62
+ Total events: 4
63
+ ```
64
+
65
+ ### Validating Individual Events
66
+
67
+ Sometimes you want to verify the integrity of a single event without processing the entire backup. The `validate-event-hash` command provides two ways to do this.
68
+
69
+ #### Validating an Event from a Backup File
70
+
71
+ To validate an event by its ID from a backup file, call the `validate-event-hash` command with the `--file` and `--event-id` flags:
72
+
73
+ ```shell
74
+ eventsourcingdb-merkle validate-event-hash --file=backup.json --event-id=42
75
+ ```
76
+
77
+ If the hash is valid, you will see a confirmation message:
78
+
79
+ ```
80
+ ✓ Hash is valid
81
+ Event ID: 42
82
+ Hash: abc123...
83
+ ```
84
+
85
+ If the hash does not match, the command shows both the stored and calculated hashes:
86
+
87
+ ```
88
+ ✗ Hash mismatch
89
+ Event ID: 42
90
+ Stored hash: abc123...
91
+ Calculated hash: def456...
92
+ ```
93
+
94
+ #### Validating an Event from JSON
95
+
96
+ You can also validate an event provided as a JSON string. This is useful when you receive an event from an external source and want to verify its hash without having access to the backup file:
97
+
98
+ ```shell
99
+ eventsourcingdb-merkle validate-event-hash --event='{"specversion":"1.0","id":"0",...}'
100
+ ```
101
+
102
+ If you provide a CloudEvent without a stored hash, the command simply calculates and displays the hash:
103
+
104
+ ```
105
+ Calculated hash: abc123...
106
+ ```
107
+
108
+ ### Generating Merkle Proofs
109
+
110
+ A Merkle proof allows you to prove that a specific event is part of a backup without revealing the entire backup. To generate a proof for an event, call the `get-proof` command with the path to your backup file and the event ID:
111
+
112
+ ```shell
113
+ eventsourcingdb-merkle get-proof backup.json 42
114
+ ```
115
+
116
+ The command outputs the proof in a human-readable format:
117
+
118
+ ```
119
+ Merkle Proof for Event 42
120
+
121
+ Event Hash: abc123...
122
+ Merkle Root: d1f6713af7ba3896ff238bb51f3986b2bad53b09bda7f23370e0a8b6eb97eeab
123
+
124
+ Sibling Hashes (3):
125
+ 1. def456... (left)
126
+ 2. ghi789... (right)
127
+ 3. jkl012... (left)
128
+ ```
129
+
130
+ #### Outputting JSON
131
+
132
+ To get the proof as JSON for programmatic use, add the `--json` flag:
133
+
134
+ ```shell
135
+ eventsourcingdb-merkle get-proof backup.json 42 --json
136
+ ```
137
+
138
+ The output can then be saved to a file and shared with others:
139
+
140
+ ```json
141
+ {
142
+ "eventId": "42",
143
+ "eventHash": "abc123...",
144
+ "siblingHashes": [
145
+ {
146
+ "hash": "def456...",
147
+ "position": "left"
148
+ },
149
+ {
150
+ "hash": "ghi789...",
151
+ "position": "right"
152
+ },
153
+ {
154
+ "hash": "jkl012...",
155
+ "position": "left"
156
+ }
157
+ ],
158
+ "merkleRoot": "d1f6713af7ba3896ff238bb51f3986b2bad53b09bda7f23370e0a8b6eb97eeab"
159
+ }
160
+ ```
161
+
162
+ ### Verifying Merkle Proofs
163
+
164
+ Once you have a Merkle proof, you can verify it without needing the original backup file. This is particularly useful when you receive a proof from someone else and want to verify that the event is indeed part of the backup with the claimed Merkle root.
165
+
166
+ To verify a proof, call the `verify-proof` command and provide either a path to a JSON file containing the proof, or the proof as a JSON string:
167
+
168
+ ```shell
169
+ eventsourcingdb-merkle verify-proof proof.json
170
+ ```
171
+
172
+ Or with a JSON string:
173
+
174
+ ```shell
175
+ eventsourcingdb-merkle verify-proof '{"eventId":"42","eventHash":"...","siblingHashes":[],"merkleRoot":"..."}'
176
+ ```
177
+
178
+ If the proof is valid, the command confirms this and displays the event details:
179
+
180
+ ```
181
+ ✓ Merkle proof is valid
182
+ Event ID: 42
183
+ Event Hash: abc123...
184
+ Merkle Root: d1f6713af7ba3896ff238bb51f3986b2bad53b09bda7f23370e0a8b6eb97eeab
185
+ ```
186
+
187
+ If the proof is invalid, the command indicates this with a non-zero exit code:
188
+
189
+ ```
190
+ ✗ Merkle proof is invalid
191
+ Event ID: 42
192
+ Event Hash: abc123...
193
+ Merkle Root: d1f6713af7ba3896ff238bb51f3986b2bad53b09bda7f23370e0a8b6eb97eeab
194
+ ```
195
+
196
+ ## Understanding the Technical Details
197
+
198
+ The tool implements Merkle trees using SHA-256 hashing, following the EventSourcingDB specification for event hash calculation. Event hashes are computed by first creating a metadata string from the CloudEvents fields, then hashing the metadata and the JSON-stringified data separately, and finally hashing the concatenation of both hashes.
199
+
200
+ The Merkle tree is constructed by treating event hashes as leaf nodes. Internal nodes are created by hashing the concatenation of their child hashes. If the number of nodes at any level is odd, the last node is duplicated to create a complete binary tree. This process continues until a single root hash remains.
201
+
202
+ Backup files are expected to be in NDJSON format, where each line contains a JSON object with a `type` field set to `"event"` and a `payload` field containing both the CloudEvents-compliant event and its hash. This format ensures that the tool can efficiently process large backup files without loading the entire file into memory.
203
+
204
+ ## Running Quality Assurance
205
+
206
+ To verify that the tool is working correctly during development, run the quality assurance checks:
207
+
208
+ ```shell
209
+ npm run qa
210
+ ```
package/biome.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
+ "files": {
4
+ "includes": ["src/**", "!dist", "!node_modules"]
5
+ },
6
+ "formatter": {
7
+ "enabled": true,
8
+ "formatWithErrors": false,
9
+ "indentStyle": "tab",
10
+ "indentWidth": 2,
11
+ "lineEnding": "lf",
12
+ "lineWidth": 100
13
+ },
14
+ "javascript": {
15
+ "formatter": {
16
+ "arrowParentheses": "asNeeded",
17
+ "bracketSameLine": true,
18
+ "bracketSpacing": true,
19
+ "jsxQuoteStyle": "single",
20
+ "quoteProperties": "asNeeded",
21
+ "quoteStyle": "single",
22
+ "semicolons": "always",
23
+ "trailingCommas": "all"
24
+ }
25
+ },
26
+ "json": {
27
+ "formatter": {
28
+ "enabled": true,
29
+ "indentStyle": "tab",
30
+ "indentWidth": 2,
31
+ "lineEnding": "lf",
32
+ "lineWidth": 100
33
+ }
34
+ },
35
+ "linter": {
36
+ "domains": {
37
+ "test": "all"
38
+ },
39
+ "enabled": true,
40
+ "rules": {
41
+ "complexity": {
42
+ "noExcessiveCognitiveComplexity": "off"
43
+ },
44
+ "correctness": {
45
+ "noPrivateImports": "off"
46
+ },
47
+ "performance": "on",
48
+ "security": "on",
49
+ "suspicious": "on",
50
+ "style": {
51
+ "useFilenamingConvention": "off"
52
+ }
53
+ }
54
+ },
55
+ "assist": {
56
+ "actions": {
57
+ "source": {
58
+ "organizeImports": "on"
59
+ }
60
+ }
61
+ }
62
+ }
@@ -0,0 +1 @@
1
+ import{createReadStream as p}from"fs";import{access as l}from"fs/promises";import{createInterface as y}from"readline";var S=async e=>{try{await l(e)}catch{throw new Error(`File not found: ${e}`)}let i=[],s=p(e),u=y({input:s,crlfDelay:Number.POSITIVE_INFINITY});for await(let t of u)if(t.trim()!=="")try{let n=JSON.parse(t);if(t.includes('"data":')){let o=t.indexOf('"data":')+7,c=0,a=o,f=!1;for(let r=o;r<t.length;r++){if(t[r]==="{"&&!f){f=!0,c=1,a=r+1;continue}if(f){if(t[r]==="\\"){r++,a=r+1;continue}if(t[r]==="{"&&c++,t[r]==="}"&&(c--,c===0)){a=r+1;break}a=r+1}}let d=o+t.substring(o).indexOf("{");n.payload.originalDataString=t.substring(d,a)}i.push(n)}catch(n){throw new Error(`Failed to parse JSON line: ${n instanceof Error?n.message:String(n)}`)}return i},k=(e,i)=>e.find(s=>s.payload.event.id===i);export{S as a,k as b};
@@ -0,0 +1 @@
1
+ import a from"crypto";var d=(t,s)=>{let e=`${t.specversion}|${t.id}|${t.predecessorhash}|${t.time}|${t.source}|${t.subject}|${t.type}|${t.datacontenttype}`,r=a.createHash("sha256").update(e).digest("hex"),h=s??JSON.stringify(t.data),i=a.createHash("sha256").update(h).digest("hex");return a.createHash("sha256").update(`${r}${i}`).digest("hex")},n=(t,s)=>a.createHash("sha256").update(`${t}${s}`).digest("hex");export{d as a,n as b};
@@ -0,0 +1,3 @@
1
+ import{Command as i}from"@oclif/core";var r=class extends i{catch(e){let t=e.constructor.name;if(t==="RequiredArgsError"||t==="NonExistentFlagsError"){let s=e.message.split(`
2
+ `).filter(o=>!o.includes("See more help")).join(`
3
+ `).trim();return this.log(`\u2717 ${s}`),this.log("See more help with --help"),process.exitCode=2,Promise.resolve()}return super.catch(e)}};export{r as a};
@@ -0,0 +1 @@
1
+ import{b as s}from"./chunk-KGZNHB6W.js";var p=r=>{if(r.length===0)throw new Error("Cannot build Merkle root from empty list");if(r.length===1)return r[0];let e=[...r];for(;e.length>1;){let i=[];for(let t=0;t<e.length;t+=2){let n=e[t],l=t+1<e.length?e[t+1]:e[t];i.push(s(n,l))}e=i}return e[0]},a=(r,e)=>{let i=r.indexOf(e);if(i===-1)throw new Error("Target hash not found in the list");let t=[],n=[...r],l=i;for(;n.length>1;){let h=[],f=0;for(let o=0;o<n.length;o+=2){let g=n[o],c=o+1<n.length?n[o+1]:n[o];(o===l||o+1===l)&&(l%2===0?o+1<n.length&&t.push({hash:c,position:"right"}):t.push({hash:g,position:"left"}),f=Math.floor(l/2)),h.push(s(g,c))}n=h,l=f}return{eventHash:e,siblingHashes:t,merkleRoot:n[0]}},m=r=>{let e=r.eventHash;for(let{hash:i,position:t}of r.siblingHashes)t==="left"?e=s(i,e):e=s(e,i);return e===r.merkleRoot};export{p as a,a as b,m as c};
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-KGZNHB6W.js";var d=r=>{let t=[];for(let a=0;a<r.length;a++){let o=r[a],e=o.payload.event,n=o.payload.hash;try{let s=i(e,o.payload.originalDataString);s!==n&&t.push({eventId:e.id,message:`Hash mismatch: expected ${n}, got ${s}`})}catch(s){t.push({eventId:e.id,message:`Failed to calculate hash: ${s instanceof Error?s.message:String(s)}`})}if(a>0){let h=r[a-1].payload.hash;e.predecessorhash!==h&&t.push({eventId:e.id,message:`Predecessor hash mismatch: expected ${h}, got ${e.predecessorhash}`})}else{let s="0".repeat(64);e.predecessorhash!==s&&t.push({eventId:e.id,message:`First event should have null predecessor hash, got ${e.predecessorhash}`})}}return{isValid:t.length===0,totalEvents:r.length,errors:t}};export{d as a};
@@ -0,0 +1 @@
1
+ import{b as p}from"../chunk-UVMEMIPC.js";import{a}from"../chunk-M4TKYTGU.js";import{a as l,b as d}from"../chunk-EKYNFDDV.js";import"../chunk-KGZNHB6W.js";import{Args as f,Flags as v}from"@oclif/core";var s=class c extends a{static description="Generate a Merkle proof for a specific event";static examples=["<%= config.bin %> <%= command.id %> backup.json 42","<%= config.bin %> <%= command.id %> /path/to/backup.json 0 --json"];static args={file:f.string({description:"Path to the backup file",required:!0}),"event-id":f.string({description:"Event ID to generate proof for",required:!0})};static flags={json:v.boolean({description:"Output proof as JSON"})};async run(){let{args:t,flags:g}=await this.parse(c);try{let e=await l(t.file),i=d(e,t["event-id"]);if(!i){this.log(`\u2717 Event with ID ${t["event-id"]} not found`),process.exitCode=1;return}let h=e.map(r=>r.payload.hash),m=p(h,i.payload.hash),o={eventId:i.payload.event.id,...m};if(g.json){this.log(JSON.stringify(o,null,2));return}this.log(`Merkle Proof for Event ${o.eventId}`),this.log(""),this.log(`Event Hash: ${o.eventHash}`),this.log(`Merkle Root: ${o.merkleRoot}`),this.log(""),this.log(`Sibling Hashes (${o.siblingHashes.length}):`);for(let[r,n]of o.siblingHashes.entries())this.log(` ${r+1}. ${n.hash} (${n.position})`)}catch(e){this.log(`\u2717 Failed to generate Merkle proof: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}};export{s as default};
@@ -0,0 +1,2 @@
1
+ import e from"assert";import{execSync as r}from"child_process";import{mkdirSync as c,writeFileSync as p}from"fs";import{tmpdir as d}from"os";import{join as u}from"path";import{before as m,describe as f,it as n}from"test";f("get-proof",()=>{let i=u(d(),"esdb-test"),s=`${i}/proof-test.json`;m(()=>{c(i,{recursive:!0});let t=[{type:"event",payload:{event:{specversion:"1.0",id:"0",time:"2024-01-01T00:00:00Z",source:"test",subject:"/test/0",type:"test.event",datacontenttype:"application/json",predecessorhash:"0".repeat(64),data:{value:"test"}},hash:"abc123"}},{type:"event",payload:{event:{specversion:"1.0",id:"1",time:"2024-01-01T00:01:00Z",source:"test",subject:"/test/1",type:"test.event",datacontenttype:"application/json",predecessorhash:"abc123",data:{value:"test2"}},hash:"def456"}}];p(s,t.map(o=>JSON.stringify(o)).join(`
2
+ `))}),n("generates proof for event",()=>{let t=r(`npx tsx ./src/index.ts get-proof ${s} 0`,{encoding:"utf-8"});e.match(t,/Merkle Proof for Event 0/),e.match(t,/Event Hash:/),e.match(t,/Merkle Root:/)}),n("outputs proof as JSON",()=>{let t=r(`npx tsx ./src/index.ts get-proof ${s} 0 --json`,{encoding:"utf-8"}),o=JSON.parse(t.trim());e.strictEqual(o.eventId,"0"),e.ok(o.eventHash),e.ok(o.merkleRoot),e.ok(Array.isArray(o.siblingHashes))}),n("handles non-existent event ID",()=>{e.throws(()=>{r(`npx tsx ./src/index.ts get-proof ${s} 999`,{encoding:"utf-8"})},t=>{let o=t.stdout||"";return e.match(o,/✗ Event with ID 999 not found/),!0})}),n("shows error when arguments are missing",()=>{try{r("npx tsx ./src/index.ts get-proof",{encoding:"utf-8"}),e.fail("Expected command to fail")}catch(t){let a=t.stdout||"";e.match(a,/Missing 2 required args/)}})});
@@ -0,0 +1 @@
1
+ import{a as i}from"../chunk-UVMEMIPC.js";import{a as t}from"../chunk-M4TKYTGU.js";import{a as r}from"../chunk-EKYNFDDV.js";import"../chunk-KGZNHB6W.js";import{Args as d}from"@oclif/core";var o=class a extends t{static description="Calculate the Merkle root for an EventSourcingDB backup file";static examples=["<%= config.bin %> <%= command.id %> backup.json","<%= config.bin %> <%= command.id %> /path/to/backup.json"];static args={file:d.string({description:"Path to the backup file",required:!0})};async run(){let{args:s}=await this.parse(a);try{let e=await r(s.file),c=e.map(l=>l.payload.hash),n=i(c);this.log(`Merkle Root: ${n}`),this.log(`Total events: ${e.length}`)}catch(e){this.log(`\u2717 Failed to calculate Merkle root: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}};export{o as default};
@@ -0,0 +1,2 @@
1
+ import e from"assert";import{execSync as s}from"child_process";import{mkdirSync as c,writeFileSync as d}from"fs";import{tmpdir as p}from"os";import{join as m}from"path";import{before as l,describe as u,it as o}from"test";u("merkle-root",()=>{let n=m(p(),"esdb-test"),i=`${n}/merkle-test.json`;l(()=>{c(n,{recursive:!0});let t=[{type:"event",payload:{event:{specversion:"1.0",id:"0",time:"2024-01-01T00:00:00Z",source:"test",subject:"/test/0",type:"test.event",datacontenttype:"application/json",predecessorhash:"0".repeat(64),data:{value:"test"}},hash:"abc123"}},{type:"event",payload:{event:{specversion:"1.0",id:"1",time:"2024-01-01T00:01:00Z",source:"test",subject:"/test/1",type:"test.event",datacontenttype:"application/json",predecessorhash:"abc123",data:{value:"test2"}},hash:"def456"}}];d(i,t.map(r=>JSON.stringify(r)).join(`
2
+ `))}),o("calculates and displays merkle root",()=>{let t=s(`npx tsx ./src/index.ts merkle-root ${i}`,{encoding:"utf-8"});e.match(t,/Merkle Root:/),e.match(t,/Total events: 2/)}),o("handles missing file gracefully",()=>{e.throws(()=>{s("npx tsx ./src/index.ts merkle-root /nonexistent/file.json",{encoding:"utf-8"})},t=>{let r=t.stdout||"";return e.match(r,/✗ Failed to calculate Merkle root/),e.match(r,/File not found/),!0})}),o("shows error when file argument is missing",()=>{try{s("npx tsx ./src/index.ts merkle-root",{encoding:"utf-8"}),e.fail("Expected command to fail")}catch(t){let a=t.stdout||"";e.match(a,/Missing 1 required arg/)}})});
@@ -0,0 +1 @@
1
+ import{a}from"../chunk-XN54AB4F.js";import{a as r}from"../chunk-M4TKYTGU.js";import{a as s}from"../chunk-EKYNFDDV.js";import"../chunk-KGZNHB6W.js";import{Args as l}from"@oclif/core";var i=class n extends r{static description="Validate the hash chain in an EventSourcingDB backup file";static examples=["<%= config.bin %> <%= command.id %> backup.json","<%= config.bin %> <%= command.id %> /path/to/backup.json"];static args={file:l.string({description:"Path to the backup file",required:!0})};async run(){let{args:c}=await this.parse(n);try{let t=await s(c.file),e=a(t);if(!e.isValid){this.log("\u2717 Chain validation failed"),this.log(`Total events: ${e.totalEvents}`),this.log(`Errors found: ${e.errors.length}`),this.log("");for(let o of e.errors)this.log(`Event ${o.eventId}: ${o.message}`);process.exitCode=1;return}this.log(`\u2713 Chain is valid (${e.totalEvents} events)`)}catch(t){this.log(`\u2717 Failed to validate chain: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1}}};export{i as default};
@@ -0,0 +1,3 @@
1
+ import e from"assert";import{execSync as n}from"child_process";import{mkdirSync as p,writeFileSync as d}from"fs";import{tmpdir as h}from"os";import{join as u}from"path";import{before as f,describe as l,it as i}from"test";l("validate-chain",()=>{let r=u(h(),"esdb-test"),c=`${r}/valid-backup.json`,o=`${r}/invalid-backup.json`;f(()=>{p(r,{recursive:!0});let t=[{type:"event",payload:{event:{specversion:"1.0",id:"0",time:"2024-01-01T00:00:00Z",source:"test",subject:"/test/0",type:"test.event",datacontenttype:"application/json",predecessorhash:"0".repeat(64),data:{value:"first"}},hash:"72fe2f580855648230cc39bca73c91e35ba611fc497573abea105ff0c70484c8"}},{type:"event",payload:{event:{specversion:"1.0",id:"1",time:"2024-01-01T00:01:00Z",source:"test",subject:"/test/1",type:"test.event",datacontenttype:"application/json",predecessorhash:"72fe2f580855648230cc39bca73c91e35ba611fc497573abea105ff0c70484c8",data:{value:"second"}},hash:"db91d105b5b53da450cf569f06e26173084b5c14f3dc61a216f36a718a83b66f"}}];d(c,t.map(s=>JSON.stringify(s)).join(`
2
+ `));let a=[t[0],{type:"event",payload:{event:{...t[1].payload.event,predecessorhash:"wrong_hash"},hash:t[1].payload.hash}}];d(o,a.map(s=>JSON.stringify(s)).join(`
3
+ `))}),i("validates a correct chain",()=>{let t=n(`npx tsx ./src/index.ts validate-chain ${c}`,{encoding:"utf-8"});e.match(t,/✓ Chain is valid \(2 events\)/)}),i("detects chain validation errors",()=>{e.throws(()=>{n(`npx tsx ./src/index.ts validate-chain ${o}`,{encoding:"utf-8"})},t=>{let a=t.stdout||"";return e.match(a,/✗ Chain validation failed/),e.match(a,/Predecessor hash mismatch/),!0})}),i("handles missing file gracefully",()=>{e.throws(()=>{n("npx tsx ./src/index.ts validate-chain /nonexistent/file.json",{encoding:"utf-8"})},t=>{let a=t.stdout||"";return e.match(a,/✗ Failed to validate chain/),e.match(a,/File not found/),!0})}),i("shows error when file argument is missing",()=>{try{n("npx tsx ./src/index.ts validate-chain",{encoding:"utf-8"}),e.fail("Expected command to fail")}catch(t){let s=t.stdout||"";e.match(s,/Missing 1 required arg/)}})});
@@ -0,0 +1 @@
1
+ import{a as p}from"../chunk-M4TKYTGU.js";import{a as v,b as u}from"../chunk-EKYNFDDV.js";import{a as r}from"../chunk-KGZNHB6W.js";import{Flags as l}from"@oclif/core";var d=class f extends p{static description="Validate the hash of a specific event (with or without backup file)";static examples=["<%= config.bin %> <%= command.id %> --file=backup.json --event-id=42",`<%= config.bin %> <%= command.id %> --event='{"specversion":"1.0",...}'`];static flags={file:l.string({description:"Path to the backup file",exclusive:["event"]}),"event-id":l.string({description:"Event ID to validate (requires --file)",exclusive:["event"]}),event:l.string({description:"JSON string of the event to validate",exclusive:["file","event-id"]})};static args={};async run(){let{flags:t}=await this.parse(f);if(!t.file&&!t.event){this.log("\u2717 Either --file and --event-id, or --event must be provided"),this.log("See more help with --help"),process.exitCode=2;return}if(t.file&&!t["event-id"]){this.log("\u2717 --event-id is required when using --file"),this.log("See more help with --help"),process.exitCode=2;return}let h=t.file,n=t["event-id"];try{let e,i,a,o;if(t.event){let s=JSON.parse(t.event);if("type"in s&&s.type==="event"&&"payload"in s)e=s,i=e.payload.event,a=e.payload.hash,o=e.payload.originalDataString;else{i=s;let g=r(i);this.log(`Calculated hash: ${g}`);return}}else{if(!h||!n){this.log("\u2717 File path and event ID are required"),process.exitCode=2;return}let s=await v(h);if(e=u(s,n),!e){this.log(`\u2717 Event with ID ${n} not found`),process.exitCode=1;return}i=e.payload.event,a=e.payload.hash,o=e.payload.originalDataString}let c=r(i,o);if(c!==a){this.log("\u2717 Hash mismatch"),this.log(`Event ID: ${i.id}`),this.log(`Stored hash: ${a}`),this.log(`Calculated hash: ${c}`),process.exitCode=1;return}this.log("\u2713 Hash is valid"),this.log(`Event ID: ${i.id}`),this.log(`Hash: ${a}`)}catch(e){this.log(`\u2717 Failed to validate event hash: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}};export{d as default};
@@ -0,0 +1,2 @@
1
+ import s from"assert";import{execSync as n}from"child_process";import{mkdirSync as a,writeFileSync as d}from"fs";import{tmpdir as c}from"os";import{join as h}from"path";import{before as u,describe as v,it as r}from"test";v("validate-event-hash",()=>{let o=h(c(),"esdb-test"),i=`${o}/event-hash-test.json`;u(()=>{a(o,{recursive:!0});let t=[{type:"event",payload:{event:{specversion:"1.0",id:"0",time:"2024-01-01T00:00:00Z",source:"test",subject:"/test/0",type:"test.event",datacontenttype:"application/json",predecessorhash:"0".repeat(64),data:{value:"test"}},hash:"4e09d3d2e20b15145060dadbbc8597c47508937819ec272b1d3b33f6e7d9d10b"}}];d(i,t.map(e=>JSON.stringify(e)).join(`
2
+ `))}),r("validates event hash from file",()=>{let t=n(`npx tsx ./src/index.ts validate-event-hash --file ${i} --event-id 0`,{encoding:"utf-8"});s.match(t,/✓ Hash is valid/),s.match(t,/Event ID: 0/)}),r("handles non-existent event ID",()=>{s.throws(()=>{n(`npx tsx ./src/index.ts validate-event-hash --file ${i} --event-id 999`,{encoding:"utf-8"})},t=>{let e=t.stdout||"";return s.match(e,/✗ Event with ID 999 not found/),!0})}),r("calculates hash for CloudEvent without stored hash",()=>{let t=JSON.stringify({specversion:"1.0",id:"0",time:"2024-01-01T00:00:00Z",source:"test",subject:"/test",type:"test.event",datacontenttype:"application/json",predecessorhash:"0".repeat(64),data:{value:"test"}}),e=n(`npx tsx ./src/index.ts validate-event-hash --event '${t}'`,{encoding:"utf-8"});s.match(e,/Calculated hash:/)}),r("shows error when event-id is missing with file",()=>{s.throws(()=>{n(`npx tsx ./src/index.ts validate-event-hash --file ${i}`,{encoding:"utf-8"})},t=>{let e=t.stdout||"";return s.match(e,/✗ --event-id is required when using --file/),!0})}),r("shows error when no arguments provided",()=>{s.throws(()=>{n("npx tsx ./src/index.ts validate-event-hash",{encoding:"utf-8"})},t=>{let e=t.stdout||"";return s.match(e,/✗ Either --file and --event-id, or --event must be provided/),!0})})});
@@ -0,0 +1 @@
1
+ import{c as s}from"../chunk-UVMEMIPC.js";import{a as t}from"../chunk-M4TKYTGU.js";import"../chunk-KGZNHB6W.js";import{Args as l}from"@oclif/core";var o=class i extends t{static description="Verify a Merkle proof";static examples=[`<%= config.bin %> <%= command.id %> '{"eventId":"42","eventHash":"...","siblingHashes":[],"merkleRoot":"..."}'`,"<%= config.bin %> <%= command.id %> proof.json"];static args={proof:l.string({description:"Merkle proof as JSON string or path to JSON file",required:!0})};async run(){let{args:r}=await this.parse(i);try{let e;try{e=JSON.parse(r.proof)}catch{let{readFileSync:a}=await import("fs"),n=a(r.proof,"utf-8");e=JSON.parse(n)}if(!e.eventHash||!e.merkleRoot||!e.siblingHashes){this.log("\u2717 Invalid proof structure"),this.log("Must contain eventHash, merkleRoot, and siblingHashes"),process.exitCode=1;return}if(!s(e)){this.log("\u2717 Merkle proof is invalid"),this.log(`Event ID: ${e.eventId}`),this.log(`Event Hash: ${e.eventHash}`),this.log(`Merkle Root: ${e.merkleRoot}`),process.exitCode=1;return}this.log("\u2713 Merkle proof is valid"),this.log(`Event ID: ${e.eventId}`),this.log(`Event Hash: ${e.eventHash}`),this.log(`Merkle Root: ${e.merkleRoot}`)}catch(e){this.log(`\u2717 Failed to verify Merkle proof: ${e instanceof Error?e.message:String(e)}`),process.exitCode=1}}};export{o as default};
@@ -0,0 +1 @@
1
+ import t from"assert";import{execSync as i}from"child_process";import{mkdirSync as a,writeFileSync as d}from"fs";import{tmpdir as u}from"os";import{join as p}from"path";import{before as v,describe as l,it as e}from"test";l("verify-proof",()=>{let s=p(u(),"esdb-test"),f=`${s}/valid-proof.json`,c=`${s}/invalid-proof.json`;v(()=>{a(s,{recursive:!0});let r={eventId:"0",eventHash:"abc123",siblingHashes:[],merkleRoot:"abc123"},o={eventId:"0",eventHash:"abc123",siblingHashes:[],merkleRoot:"wrong_root"};d(f,JSON.stringify(r)),d(c,JSON.stringify(o))}),e("verifies valid proof from file",()=>{let r=i(`npx tsx ./src/index.ts verify-proof ${f}`,{encoding:"utf-8"});t.match(r,/✓ Merkle proof is valid/),t.match(r,/Event ID: 0/)}),e("verifies valid proof from JSON string",()=>{let r=JSON.stringify({eventId:"0",eventHash:"test123",siblingHashes:[],merkleRoot:"test123"}),o=i(`npx tsx ./src/index.ts verify-proof '${r}'`,{encoding:"utf-8"});t.match(o,/✓ Merkle proof is valid/)}),e("detects invalid proof",()=>{t.throws(()=>{i(`npx tsx ./src/index.ts verify-proof ${c}`,{encoding:"utf-8"})},r=>{let o=r.stdout||"";return t.match(o,/✗ Merkle proof is invalid/),!0})}),e("rejects proof with invalid structure",()=>{let r=JSON.stringify({invalid:"structure"});t.throws(()=>{i(`npx tsx ./src/index.ts verify-proof '${r}'`,{encoding:"utf-8"})},o=>{let n=o.stdout||"";return t.match(n,/✗ Invalid proof structure/),!0})}),e("shows error when proof argument is missing",()=>{try{i("npx tsx ./src/index.ts verify-proof",{encoding:"utf-8"}),t.fail("Expected command to fail")}catch(r){let n=r.stdout||"";t.match(n,/Missing 1 required arg/)}})});
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{run as r}from"@oclif/core";await r(process.argv.slice(2),import.meta.url);
@@ -0,0 +1 @@
1
+ import{a}from"../chunk-M4TKYTGU.js";export{a as default};
@@ -0,0 +1 @@
1
+ import{a,b}from"../chunk-EKYNFDDV.js";export{b as findEventById,a as readBackupFile};
@@ -0,0 +1 @@
1
+ import{a as s,b as n}from"../chunk-EKYNFDDV.js";import t from"assert";import{describe as c,it as i}from"test";c("readBackupFile",()=>{i("reads a backup file with multiple events",async()=>{let e=await s("test-fixtures/test-backup.json");t.strictEqual(e.length,4),t.strictEqual(e[0].type,"event"),t.strictEqual(e[0].payload.event.id,"0"),t.strictEqual(e[1].payload.event.id,"1"),t.strictEqual(e[2].payload.event.id,"2"),t.strictEqual(e[3].payload.event.id,"3")}),i("parses event data correctly",async()=>{let a=(await s("test-fixtures/test-backup.json"))[0].payload.event;t.strictEqual(a.specversion,"1.0"),t.strictEqual(a.type,"com.example.item.created"),t.strictEqual(a.datacontenttype,"application/json"),t.deepStrictEqual(a.data,{title:"Lorem ipsum",description:"Dolor sit amet"})}),i("reads hash from payload",async()=>{let e=await s("test-fixtures/test-backup.json");t.strictEqual(e[0].payload.hash,"a5137d458a5639ee5d1f1248559058b2dfc25c98c8731aefc3efbf9decb5dbeb")})});c("findEventById",()=>{i("finds an event by its ID",async()=>{let e=await s("test-fixtures/test-backup.json"),a=n(e,"2");t.ok(a),t.strictEqual(a.payload.event.id,"2")}),i("returns undefined for non-existent ID",async()=>{let e=await s("test-fixtures/test-backup.json"),a=n(e,"999");t.strictEqual(a,void 0)})});
@@ -0,0 +1 @@
1
+ import{a}from"../chunk-XN54AB4F.js";import"../chunk-KGZNHB6W.js";export{a as validateChain};
@@ -0,0 +1 @@
1
+ import{a as i}from"../chunk-XN54AB4F.js";import{a as r}from"../chunk-EKYNFDDV.js";import"../chunk-KGZNHB6W.js";import t from"assert";import{describe as o,it as c}from"test";o("validateChain",()=>{c("validates a correct chain",async()=>{let e=await r("test-fixtures/test-backup.json"),s=i(e);t.strictEqual(s.isValid,!0),t.strictEqual(s.totalEvents,4),t.strictEqual(s.errors.length,0)}),c("detects hash mismatch",async()=>{let e=await r("test-fixtures/test-backup.json");e[1].payload.hash="tampered";let s=i(e);t.strictEqual(s.isValid,!1),t.strictEqual(s.errors.length,2),t.ok(s.errors.some(a=>a.message.includes("Hash mismatch")))}),c("detects predecessor hash mismatch",async()=>{let e=await r("test-fixtures/test-backup.json");e[2].payload.event.predecessorhash="tampered";let s=i(e);t.strictEqual(s.isValid,!1),t.ok(s.errors.some(a=>a.message.includes("Predecessor hash mismatch")))}),c("validates first event has null predecessor",async()=>{let e=await r("test-fixtures/test-backup.json");e[0].payload.event.predecessorhash="invalid";let s=i(e);t.strictEqual(s.isValid,!1),t.ok(s.errors.some(a=>a.message.includes("null predecessor hash")))})});
@@ -0,0 +1 @@
1
+ import{a,b}from"../chunk-KGZNHB6W.js";export{a as calculateEventHash,b as hashPair};
@@ -0,0 +1 @@
1
+ import{a as r,b as a}from"../chunk-KGZNHB6W.js";import c from"assert";import{describe as h,it as o}from"test";h("calculateEventHash",()=>{o("calculates the correct hash for an event",()=>{let t=r({specversion:"1.0",id:"0",time:"2024-01-01T12:00:00.000000000Z",source:"tag:example.com,2024:test:app",subject:"/test-subject/items/00000000-0000-0000-0000-000000000001",type:"com.example.item.created",datacontenttype:"application/json",predecessorhash:"0000000000000000000000000000000000000000000000000000000000000000",data:{title:"Lorem ipsum",description:"Dolor sit amet"}});c.strictEqual(t,"a5137d458a5639ee5d1f1248559058b2dfc25c98c8731aefc3efbf9decb5dbeb")})});h("hashPair",()=>{o("hashes two strings together",()=>{let s=a("abc123","def456");c.strictEqual(typeof s,"string"),c.strictEqual(s.length,64)}),o("produces different results for different order",()=>{let e="abc123",t="def456",s=a(e,t),n=a(t,e);c.notStrictEqual(s,n)})});
@@ -0,0 +1 @@
1
+ import{a,b,c}from"../chunk-UVMEMIPC.js";import"../chunk-KGZNHB6W.js";export{a as buildMerkleRoot,b as generateMerkleProof,c as verifyMerkleProof};
@@ -0,0 +1 @@
1
+ import{a as o,b as a,c as r}from"../chunk-UVMEMIPC.js";import"../chunk-KGZNHB6W.js";import h from"assert";import{describe as i,it as t}from"test";i("buildMerkleRoot",()=>{t("throws error for empty list",()=>{h.throws(()=>o([]),{message:"Cannot build Merkle root from empty list"})}),t("returns the single hash for a list with one element",()=>{let e="abc123",s=o([e]);h.strictEqual(s,e)}),t("builds correct Merkle root for two hashes",()=>{let s=o(["hash1","hash2"]);h.strictEqual(typeof s,"string"),h.strictEqual(s.length,64)}),t("builds correct Merkle root for four hashes",()=>{let s=o(["hash1","hash2","hash3","hash4"]);h.strictEqual(typeof s,"string"),h.strictEqual(s.length,64)}),t("handles odd number of hashes by duplicating the last one",()=>{let s=o(["hash1","hash2","hash3"]);h.strictEqual(typeof s,"string"),h.strictEqual(s.length,64)})});i("generateMerkleProof",()=>{t("throws error if target hash not found",()=>{let e=["hash1","hash2","hash3"];h.throws(()=>a(e,"notfound"),{message:"Target hash not found in the list"})}),t("generates proof for single element",()=>{let s=a(["hash1"],"hash1");h.strictEqual(s.eventHash,"hash1"),h.strictEqual(s.siblingHashes.length,0),h.strictEqual(s.merkleRoot,"hash1")}),t("generates proof for first element in pair",()=>{let s=a(["hash1","hash2"],"hash1");h.strictEqual(s.eventHash,"hash1"),h.strictEqual(s.siblingHashes.length,1),h.strictEqual(s.siblingHashes[0].hash,"hash2"),h.strictEqual(s.siblingHashes[0].position,"right")}),t("generates proof for second element in pair",()=>{let s=a(["hash1","hash2"],"hash2");h.strictEqual(s.eventHash,"hash2"),h.strictEqual(s.siblingHashes.length,1),h.strictEqual(s.siblingHashes[0].hash,"hash1"),h.strictEqual(s.siblingHashes[0].position,"left")}),t("generates proof for element in larger tree",()=>{let s=a(["hash1","hash2","hash3","hash4"],"hash3");h.strictEqual(s.eventHash,"hash3"),h.strictEqual(s.siblingHashes.length,2)})});i("verifyMerkleProof",()=>{t("verifies valid proof for single element",()=>{let s=a(["hash1"],"hash1");h.strictEqual(r(s),!0)}),t("verifies valid proof for two elements",()=>{let s=a(["hash1","hash2"],"hash1");h.strictEqual(r(s),!0)}),t("verifies valid proof for four elements",()=>{let s=a(["hash1","hash2","hash3","hash4"],"hash3");h.strictEqual(r(s),!0)}),t("rejects invalid proof with wrong root",()=>{let s=a(["hash1","hash2"],"hash1");s.merkleRoot="wrongroot",h.strictEqual(r(s),!1)}),t("rejects invalid proof with tampered sibling",()=>{let s=a(["hash1","hash2","hash3","hash4"],"hash3");s.siblingHashes[0].hash="tampered",h.strictEqual(r(s),!1)})});
File without changes