eventsourcingdb-merkle 1.3.0 → 2.0.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.
- package/README.md +30 -12
- package/dist/commands/get-proof.js +42 -11
- package/dist/commands/merkle-root.js +26 -7
- package/dist/commands/validate-chain.js +12 -7
- package/dist/commands/validate-event-hash.js +16 -20
- package/dist/lib/BaseCommand.js +13 -6
- package/dist/lib/backupReader.js +10 -7
- package/dist/lib/eventId.js +8 -0
- package/dist/lib/hash.js +13 -2
- package/dist/lib/lastEventId.js +16 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -22,10 +22,10 @@ npx eventsourcingdb-merkle [COMMAND]
|
|
|
22
22
|
|
|
23
23
|
### Validating Event Chains
|
|
24
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
|
|
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 with `--backup`. 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
26
|
|
|
27
27
|
```shell
|
|
28
|
-
eventsourcingdb-merkle validate-chain backup.json
|
|
28
|
+
eventsourcingdb-merkle validate-chain --backup=backup.json
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
If the chain is valid, you will see a confirmation message with the total number of events:
|
|
@@ -57,29 +57,40 @@ Such an event cannot be verified, which is not the same as being tampered with,
|
|
|
57
57
|
|
|
58
58
|
### Calculating the Merkle Root
|
|
59
59
|
|
|
60
|
-
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
|
|
60
|
+
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 with `--backup`. The Merkle root is a single hash that represents the entire event chain and can be used to verify the integrity of the backup:
|
|
61
61
|
|
|
62
62
|
```shell
|
|
63
|
-
eventsourcingdb-merkle merkle-root backup.json
|
|
63
|
+
eventsourcingdb-merkle merkle-root --backup=backup.json
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
-
The command outputs the Merkle root
|
|
66
|
+
The command outputs the Merkle root, the total number of events, and the ID of the last event it covers:
|
|
67
67
|
|
|
68
68
|
```
|
|
69
69
|
Merkle Root: d1f6713af7ba3896ff238bb51f3986b2bad53b09bda7f23370e0a8b6eb97eeab
|
|
70
70
|
Total events: 4
|
|
71
|
+
Last event ID: 3
|
|
71
72
|
```
|
|
72
73
|
|
|
74
|
+
#### Calculating the Merkle Root of an Earlier State
|
|
75
|
+
|
|
76
|
+
A root that you published once has to be calculated again later, for instance to generate proofs against it. Since events are never changed, a newer backup holds the events of an older one, followed by those written since. Pass the last event ID that the root covered with `--last-event-id`, and the command calculates the root over the events up to it, which is the root of the older backup:
|
|
77
|
+
|
|
78
|
+
```shell
|
|
79
|
+
eventsourcingdb-merkle merkle-root --backup=backup-2025.json --last-event-id=3
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
So you do not have to keep the older backup to prove against its root. If the backup holds no event with that ID, the command refuses rather than calculating a root over other events.
|
|
83
|
+
|
|
73
84
|
### Validating Individual Events
|
|
74
85
|
|
|
75
86
|
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.
|
|
76
87
|
|
|
77
88
|
#### Validating an Event from a Backup File
|
|
78
89
|
|
|
79
|
-
To validate an event by its ID from a backup file, call the `validate-event-hash` command with the `--
|
|
90
|
+
To validate an event by its ID from a backup file, call the `validate-event-hash` command with the `--backup` and `--event-id` flags:
|
|
80
91
|
|
|
81
92
|
```shell
|
|
82
|
-
eventsourcingdb-merkle validate-event-hash --
|
|
93
|
+
eventsourcingdb-merkle validate-event-hash --backup=backup.json --event-id=42
|
|
83
94
|
```
|
|
84
95
|
|
|
85
96
|
If the hash is valid, you will see a confirmation message:
|
|
@@ -107,18 +118,19 @@ You can also validate an event provided as a JSON string. This is useful when yo
|
|
|
107
118
|
eventsourcingdb-merkle validate-event-hash --event='{"specversion":"1.0","id":"0",...,"hash":"esdb:hash:v2:..."}'
|
|
108
119
|
```
|
|
109
120
|
|
|
110
|
-
If you provide a CloudEvent without a stored hash, the command simply calculates and displays the hash
|
|
121
|
+
If you provide a CloudEvent without a stored hash, the command simply calculates and displays the hash in every version, since nothing tells which version is meant:
|
|
111
122
|
|
|
112
123
|
```
|
|
113
|
-
Calculated hash: abc123...
|
|
124
|
+
Calculated hash (version 1): abc123...
|
|
125
|
+
Calculated hash (version 2): esdb:hash:v2:def456...
|
|
114
126
|
```
|
|
115
127
|
|
|
116
128
|
### Generating Merkle Proofs
|
|
117
129
|
|
|
118
|
-
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
|
|
130
|
+
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 in `--backup` and the event ID in `--event-id`:
|
|
119
131
|
|
|
120
132
|
```shell
|
|
121
|
-
eventsourcingdb-merkle get-proof backup.json 42
|
|
133
|
+
eventsourcingdb-merkle get-proof --backup=backup.json --event-id=42
|
|
122
134
|
```
|
|
123
135
|
|
|
124
136
|
The command outputs the proof in a human-readable format:
|
|
@@ -135,12 +147,18 @@ Sibling Hashes (3):
|
|
|
135
147
|
3. jkl012... (left)
|
|
136
148
|
```
|
|
137
149
|
|
|
150
|
+
To prove an event against the root of an earlier state, pass its last event ID with `--last-event-id`, as for `merkle-root`. An event after it is not part of that tree, so the command refuses to prove it:
|
|
151
|
+
|
|
152
|
+
```shell
|
|
153
|
+
eventsourcingdb-merkle get-proof --backup=backup.json --event-id=42 --last-event-id=1234566
|
|
154
|
+
```
|
|
155
|
+
|
|
138
156
|
#### Outputting JSON
|
|
139
157
|
|
|
140
158
|
To get the proof as JSON for programmatic use, add the `--json` flag:
|
|
141
159
|
|
|
142
160
|
```shell
|
|
143
|
-
eventsourcingdb-merkle get-proof backup.json 42 --json
|
|
161
|
+
eventsourcingdb-merkle get-proof --backup=backup.json --event-id=42 --json
|
|
144
162
|
```
|
|
145
163
|
|
|
146
164
|
The output can then be saved to a file and shared with others:
|
|
@@ -1,27 +1,58 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Flags } from '@oclif/core';
|
|
2
2
|
import BaseCommand from '../lib/BaseCommand.js';
|
|
3
3
|
import { findEventById, readBackupFile } from '../lib/backupReader.js';
|
|
4
|
+
import { parseEventId } from '../lib/eventId.js';
|
|
5
|
+
import { takeEntriesUpTo } from '../lib/lastEventId.js';
|
|
4
6
|
import { generateMerkleProof } from '../lib/merkleTree.js';
|
|
5
7
|
export default class GetProof extends BaseCommand {
|
|
6
8
|
static description = 'Generate a Merkle proof for a specific event';
|
|
7
9
|
static examples = [
|
|
8
|
-
'<%= config.bin %> <%= command.id %> backup.json 42',
|
|
9
|
-
'<%= config.bin %> <%= command.id %>
|
|
10
|
+
'<%= config.bin %> <%= command.id %> --backup=backup.json --event-id=42',
|
|
11
|
+
'<%= config.bin %> <%= command.id %> --backup=/path/to/backup.json --event-id=0 --json',
|
|
12
|
+
'<%= config.bin %> <%= command.id %> --backup=backup.json --event-id=42 --last-event-id=1234566',
|
|
10
13
|
];
|
|
11
|
-
static args = {
|
|
12
|
-
file: Args.string({ description: 'Path to the backup file', required: true }),
|
|
13
|
-
'event-id': Args.string({ description: 'Event ID to generate proof for', required: true }),
|
|
14
|
-
};
|
|
15
14
|
static flags = {
|
|
15
|
+
backup: Flags.string({ description: 'Path to the backup file' }),
|
|
16
|
+
'event-id': Flags.string({ description: 'Event ID to generate proof for' }),
|
|
17
|
+
'last-event-id': Flags.string({
|
|
18
|
+
description: 'ID of the last event the root covers, to prove against the root of an earlier state',
|
|
19
|
+
}),
|
|
16
20
|
json: Flags.boolean({ description: 'Output proof as JSON' }),
|
|
17
21
|
};
|
|
22
|
+
static args = {};
|
|
18
23
|
async run() {
|
|
19
|
-
const {
|
|
24
|
+
const { flags } = await this.parse(GetProof);
|
|
25
|
+
if (!flags.backup) {
|
|
26
|
+
this.refuseCall('--backup must be provided');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const eventId = flags['event-id'];
|
|
30
|
+
if (!eventId) {
|
|
31
|
+
this.refuseCall('--event-id is required when using --backup');
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const lastEventId = flags['last-event-id'];
|
|
35
|
+
if (lastEventId !== undefined && parseEventId(lastEventId) === undefined) {
|
|
36
|
+
this.refuseCall(`--last-event-id has to be an event ID, but is '${lastEventId}'`);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
20
39
|
try {
|
|
21
|
-
const
|
|
22
|
-
const
|
|
40
|
+
const allEntries = await readBackupFile(flags.backup);
|
|
41
|
+
const entries = lastEventId === undefined ? allEntries : takeEntriesUpTo(allEntries, lastEventId);
|
|
42
|
+
// An event after the last one is not part of the tree, so it has no
|
|
43
|
+
// proof against its root, although the backup holds it.
|
|
44
|
+
const eventNumber = parseEventId(eventId);
|
|
45
|
+
const lastEventNumber = lastEventId === undefined ? undefined : parseEventId(lastEventId);
|
|
46
|
+
if (eventNumber !== undefined &&
|
|
47
|
+
lastEventNumber !== undefined &&
|
|
48
|
+
eventNumber > lastEventNumber) {
|
|
49
|
+
this.log(`✗ Event ${eventId} lies beyond the last event ID ${lastEventId}`);
|
|
50
|
+
process.exitCode = 1;
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
const entry = findEventById(entries, eventId);
|
|
23
54
|
if (!entry) {
|
|
24
|
-
this.log(`✗ Event with ID ${
|
|
55
|
+
this.log(`✗ Event with ID ${eventId} not found`);
|
|
25
56
|
process.exitCode = 1;
|
|
26
57
|
return;
|
|
27
58
|
}
|
|
@@ -1,24 +1,43 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Flags } from '@oclif/core';
|
|
2
2
|
import BaseCommand from '../lib/BaseCommand.js';
|
|
3
3
|
import { readBackupFile } from '../lib/backupReader.js';
|
|
4
|
+
import { parseEventId } from '../lib/eventId.js';
|
|
5
|
+
import { takeEntriesUpTo } from '../lib/lastEventId.js';
|
|
4
6
|
import { buildMerkleRoot } from '../lib/merkleTree.js';
|
|
5
7
|
export default class MerkleRoot extends BaseCommand {
|
|
6
8
|
static description = 'Calculate the Merkle root for an EventSourcingDB backup file';
|
|
7
9
|
static examples = [
|
|
8
|
-
'<%= config.bin %> <%= command.id %> backup.json',
|
|
9
|
-
'<%= config.bin %> <%= command.id %>
|
|
10
|
+
'<%= config.bin %> <%= command.id %> --backup=backup.json',
|
|
11
|
+
'<%= config.bin %> <%= command.id %> --backup=/path/to/backup.json --last-event-id=41',
|
|
10
12
|
];
|
|
11
|
-
static
|
|
12
|
-
|
|
13
|
+
static flags = {
|
|
14
|
+
backup: Flags.string({ description: 'Path to the backup file' }),
|
|
15
|
+
'last-event-id': Flags.string({
|
|
16
|
+
description: 'ID of the last event to cover, to calculate the root of an earlier state again',
|
|
17
|
+
}),
|
|
13
18
|
};
|
|
19
|
+
static args = {};
|
|
14
20
|
async run() {
|
|
15
|
-
const {
|
|
21
|
+
const { flags } = await this.parse(MerkleRoot);
|
|
22
|
+
if (!flags.backup) {
|
|
23
|
+
this.refuseCall('--backup must be provided');
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const lastEventId = flags['last-event-id'];
|
|
27
|
+
if (lastEventId !== undefined && parseEventId(lastEventId) === undefined) {
|
|
28
|
+
this.refuseCall(`--last-event-id has to be an event ID, but is '${lastEventId}'`);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
16
31
|
try {
|
|
17
|
-
const
|
|
32
|
+
const allEntries = await readBackupFile(flags.backup);
|
|
33
|
+
const entries = lastEventId === undefined ? allEntries : takeEntriesUpTo(allEntries, lastEventId);
|
|
18
34
|
const hashes = entries.map(entry => entry.payload.hash);
|
|
19
35
|
const merkleRoot = buildMerkleRoot(hashes);
|
|
36
|
+
// The ID of the last event is what calculates this root again later,
|
|
37
|
+
// from a backup that has grown since.
|
|
20
38
|
this.log(`Merkle Root: ${merkleRoot}`);
|
|
21
39
|
this.log(`Total events: ${entries.length}`);
|
|
40
|
+
this.log(`Last event ID: ${entries.at(-1)?.payload.event.id}`);
|
|
22
41
|
}
|
|
23
42
|
catch (error) {
|
|
24
43
|
this.log(`✗ Failed to calculate Merkle root: ${error instanceof Error ? error.message : String(error)}`);
|
|
@@ -1,20 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Flags } from '@oclif/core';
|
|
2
2
|
import BaseCommand from '../lib/BaseCommand.js';
|
|
3
3
|
import { readBackupFile } from '../lib/backupReader.js';
|
|
4
4
|
import { validateChain } from '../lib/chainValidator.js';
|
|
5
5
|
export default class ValidateChain extends BaseCommand {
|
|
6
6
|
static description = 'Validate the hash chain in an EventSourcingDB backup file';
|
|
7
7
|
static examples = [
|
|
8
|
-
'<%= config.bin %> <%= command.id %> backup.json',
|
|
9
|
-
'<%= config.bin %> <%= command.id %>
|
|
8
|
+
'<%= config.bin %> <%= command.id %> --backup=backup.json',
|
|
9
|
+
'<%= config.bin %> <%= command.id %> --backup=/path/to/backup.json',
|
|
10
10
|
];
|
|
11
|
-
static
|
|
12
|
-
|
|
11
|
+
static flags = {
|
|
12
|
+
backup: Flags.string({ description: 'Path to the backup file' }),
|
|
13
13
|
};
|
|
14
|
+
static args = {};
|
|
14
15
|
async run() {
|
|
15
|
-
const {
|
|
16
|
+
const { flags } = await this.parse(ValidateChain);
|
|
17
|
+
if (!flags.backup) {
|
|
18
|
+
this.refuseCall('--backup must be provided');
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
16
21
|
try {
|
|
17
|
-
const entries = await readBackupFile(
|
|
22
|
+
const entries = await readBackupFile(flags.backup);
|
|
18
23
|
const result = validateChain(entries);
|
|
19
24
|
if (!result.isValid) {
|
|
20
25
|
this.log(`✗ Chain validation failed`);
|
|
@@ -2,41 +2,37 @@ import { Flags } from '@oclif/core';
|
|
|
2
2
|
import BaseCommand from '../lib/BaseCommand.js';
|
|
3
3
|
import { findEventById, readBackupFile } from '../lib/backupReader.js';
|
|
4
4
|
import { readEventText } from '../lib/eventText.js';
|
|
5
|
-
import { calculateEventHash, UnsupportedHashVersionError } from '../lib/hash.js';
|
|
5
|
+
import { calculateEventHash, calculateEventHashInEveryVersion, UnsupportedHashVersionError, } from '../lib/hash.js';
|
|
6
6
|
export default class ValidateEventHash extends BaseCommand {
|
|
7
7
|
static description = 'Validate the hash of a specific event (with or without backup file)';
|
|
8
8
|
static examples = [
|
|
9
|
-
'<%= config.bin %> <%= command.id %> --
|
|
9
|
+
'<%= config.bin %> <%= command.id %> --backup=backup.json --event-id=42',
|
|
10
10
|
// biome-ignore lint/security/noSecrets: This is an example command, not a secret
|
|
11
11
|
'<%= config.bin %> <%= command.id %> --event=\'{"specversion":"1.0",...}\'',
|
|
12
12
|
];
|
|
13
13
|
static flags = {
|
|
14
|
-
|
|
14
|
+
backup: Flags.string({ description: 'Path to the backup file', exclusive: ['event'] }),
|
|
15
15
|
'event-id': Flags.string({
|
|
16
|
-
description: 'Event ID to validate (requires --
|
|
16
|
+
description: 'Event ID to validate (requires --backup)',
|
|
17
17
|
exclusive: ['event'],
|
|
18
18
|
}),
|
|
19
19
|
event: Flags.string({
|
|
20
20
|
description: 'JSON string of the event to validate',
|
|
21
|
-
exclusive: ['
|
|
21
|
+
exclusive: ['backup', 'event-id'],
|
|
22
22
|
}),
|
|
23
23
|
};
|
|
24
24
|
static args = {};
|
|
25
25
|
async run() {
|
|
26
26
|
const { flags } = await this.parse(ValidateEventHash);
|
|
27
|
-
if (!flags.
|
|
28
|
-
this.
|
|
29
|
-
this.log('See more help with --help');
|
|
30
|
-
process.exitCode = 2;
|
|
27
|
+
if (!flags.backup && !flags.event) {
|
|
28
|
+
this.refuseCall('Either --backup with --event-id, or --event must be provided');
|
|
31
29
|
return;
|
|
32
30
|
}
|
|
33
|
-
if (flags.
|
|
34
|
-
this.
|
|
35
|
-
this.log('See more help with --help');
|
|
36
|
-
process.exitCode = 2;
|
|
31
|
+
if (flags.backup && !flags['event-id']) {
|
|
32
|
+
this.refuseCall('--event-id is required when using --backup');
|
|
37
33
|
return;
|
|
38
34
|
}
|
|
39
|
-
const filePath = flags.
|
|
35
|
+
const filePath = flags.backup;
|
|
40
36
|
const eventId = flags['event-id'];
|
|
41
37
|
try {
|
|
42
38
|
let event;
|
|
@@ -45,15 +41,15 @@ export default class ValidateEventHash extends BaseCommand {
|
|
|
45
41
|
if (flags.event) {
|
|
46
42
|
const eventFromText = readEventText(flags.event);
|
|
47
43
|
if (eventFromText === undefined) {
|
|
48
|
-
this.
|
|
49
|
-
this.log('See more help with --help');
|
|
50
|
-
process.exitCode = 2;
|
|
44
|
+
this.refuseCall('--event is neither an event nor a line of a backup or of read-events');
|
|
51
45
|
return;
|
|
52
46
|
}
|
|
47
|
+
// Without a stored hash, nothing tells which version of the hash is
|
|
48
|
+
// meant, so it is calculated in every version.
|
|
53
49
|
if (eventFromText.storedHash === undefined) {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
50
|
+
for (const { version, hash } of calculateEventHashInEveryVersion(eventFromText.event, eventFromText.originalDataString)) {
|
|
51
|
+
this.log(`Calculated hash (version ${version}): ${hash}`);
|
|
52
|
+
}
|
|
57
53
|
return;
|
|
58
54
|
}
|
|
59
55
|
event = eventFromText.event;
|
package/dist/lib/BaseCommand.js
CHANGED
|
@@ -1,16 +1,23 @@
|
|
|
1
1
|
import { Command } from '@oclif/core';
|
|
2
2
|
export default class BaseCommand extends Command {
|
|
3
|
+
// refuseCall reports a call whose arguments or flags do not fit together, as
|
|
4
|
+
// oclif does for those it refuses itself, with the exit code 2.
|
|
5
|
+
refuseCall(message) {
|
|
6
|
+
this.log(`✗ ${message}`);
|
|
7
|
+
this.log('See more help with --help');
|
|
8
|
+
process.exitCode = 2;
|
|
9
|
+
}
|
|
3
10
|
catch(error) {
|
|
4
|
-
|
|
5
|
-
//
|
|
6
|
-
|
|
11
|
+
// oclif ends with the exit code 2 where it refuses the arguments and flags
|
|
12
|
+
// of a call, such as an argument that is missing or unexpected, a flag that
|
|
13
|
+
// does not exist, or two flags that cannot be used together. Such a call
|
|
14
|
+
// gets a message of its own rather than a stack trace.
|
|
15
|
+
if (error.oclif?.exit === 2) {
|
|
7
16
|
// Remove the "See more help with --help" line from oclif
|
|
8
17
|
const lines = error.message.split('\n');
|
|
9
18
|
const filteredLines = lines.filter(line => !line.includes('See more help'));
|
|
10
19
|
const message = filteredLines.join('\n').trim();
|
|
11
|
-
this.
|
|
12
|
-
this.log('See more help with --help');
|
|
13
|
-
process.exitCode = 2;
|
|
20
|
+
this.refuseCall(message);
|
|
14
21
|
return Promise.resolve();
|
|
15
22
|
}
|
|
16
23
|
// For other errors, use default oclif error handling
|
package/dist/lib/backupReader.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { createReadStream } from 'node:fs';
|
|
2
2
|
import { access } from 'node:fs/promises';
|
|
3
3
|
import { createInterface } from 'node:readline';
|
|
4
|
+
import { parseEventId } from './eventId.js';
|
|
4
5
|
import { isObject } from './isObject.js';
|
|
5
6
|
import { getCompactValue, getRawValue } from './rawJson.js';
|
|
6
7
|
// The version of the format in which the v2 API writes a backup. The backups
|
|
7
8
|
// of the v1 API carry no version of their own.
|
|
8
9
|
const backupFormatVersion = 2;
|
|
9
|
-
// An event ID is an integer, which EventSourcingDB reads with an optional sign.
|
|
10
|
-
const eventIdPattern = /^[+-]?\d+$/u;
|
|
11
10
|
export const readBackupFile = async (filePath) => {
|
|
12
11
|
// Check if file exists and is readable
|
|
13
12
|
try {
|
|
@@ -222,11 +221,15 @@ const isSameEvent = (anchor, endedAt) => {
|
|
|
222
221
|
if (typeof id !== 'string' || typeof hash !== 'string') {
|
|
223
222
|
return false;
|
|
224
223
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
}
|
|
228
|
-
return BigInt(id) === BigInt(endedAt.id) && hash === endedAt.hash;
|
|
224
|
+
const anchorId = parseEventId(id);
|
|
225
|
+
return anchorId !== undefined && anchorId === parseEventId(endedAt.id) && hash === endedAt.hash;
|
|
229
226
|
};
|
|
227
|
+
// findEventById compares IDs as numbers, as EventSourcingDB reads them, so that
|
|
228
|
+
// an ID in another notation of the same number finds the event.
|
|
230
229
|
export const findEventById = (entries, eventId) => {
|
|
231
|
-
|
|
230
|
+
const wanted = parseEventId(eventId);
|
|
231
|
+
if (wanted === undefined) {
|
|
232
|
+
return undefined;
|
|
233
|
+
}
|
|
234
|
+
return entries.find(entry => parseEventId(entry.payload.event.id) === wanted);
|
|
232
235
|
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// An event ID is an integer, which EventSourcingDB reads with an optional sign.
|
|
2
|
+
const eventIdPattern = /^[+-]?\d+$/u;
|
|
3
|
+
// parseEventId returns the number that an event ID names, so that IDs in other
|
|
4
|
+
// notations of the same number compare as equal, or undefined for text that
|
|
5
|
+
// names no number.
|
|
6
|
+
export const parseEventId = (id) => {
|
|
7
|
+
return eventIdPattern.test(id) ? BigInt(id) : undefined;
|
|
8
|
+
};
|
package/dist/lib/hash.js
CHANGED
|
@@ -41,13 +41,14 @@ const calculateEventHashOfVersion2 = (event, dataString) => {
|
|
|
41
41
|
};
|
|
42
42
|
// calculateEventHash computes the hash of an event in the version that its
|
|
43
43
|
// stored hash names, since an event keeps the version of the hash it was
|
|
44
|
-
// written with
|
|
44
|
+
// written with. An event without a stored hash names no version, which is what
|
|
45
|
+
// calculateEventHashInEveryVersion is for. A stored hash
|
|
45
46
|
// whose prefix names a version that the tool does not know cannot be verified,
|
|
46
47
|
// which is not the same as being tampered with, so it is refused rather than
|
|
47
48
|
// computed in another version that could only fail to match.
|
|
48
49
|
export const calculateEventHash = (event, originalDataString, storedHash) => {
|
|
49
50
|
const dataString = originalDataString ?? JSON.stringify(event.data);
|
|
50
|
-
if (
|
|
51
|
+
if (!storedHash.startsWith(hashPrefix)) {
|
|
51
52
|
return calculateEventHashOfVersion1(event, dataString);
|
|
52
53
|
}
|
|
53
54
|
if (storedHash.startsWith(hashVersion2Prefix)) {
|
|
@@ -56,6 +57,16 @@ export const calculateEventHash = (event, originalDataString, storedHash) => {
|
|
|
56
57
|
const [version = ''] = storedHash.slice(hashPrefix.length).split(':');
|
|
57
58
|
throw new UnsupportedHashVersionError(version);
|
|
58
59
|
};
|
|
60
|
+
// calculateEventHashInEveryVersion computes the hash of an event in every
|
|
61
|
+
// version the tool knows, for an event without a stored hash that would tell
|
|
62
|
+
// which version is meant.
|
|
63
|
+
export const calculateEventHashInEveryVersion = (event, originalDataString) => {
|
|
64
|
+
const dataString = originalDataString ?? JSON.stringify(event.data);
|
|
65
|
+
return [
|
|
66
|
+
{ version: 1, hash: calculateEventHashOfVersion1(event, dataString) },
|
|
67
|
+
{ version: 2, hash: calculateEventHashOfVersion2(event, dataString) },
|
|
68
|
+
];
|
|
69
|
+
};
|
|
59
70
|
export const hashPair = (left, right) => {
|
|
60
71
|
return crypto.createHash('sha256').update(`${left}${right}`).digest('hex');
|
|
61
72
|
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { parseEventId } from './eventId.js';
|
|
2
|
+
// takeEntriesUpTo returns the events of a backup up to the one with the given
|
|
3
|
+
// ID, which it includes, so that the Merkle root of an earlier state can be
|
|
4
|
+
// calculated again from a backup that has grown since. An ID that the backup
|
|
5
|
+
// does not hold is refused rather than taken as the end of the backup, since
|
|
6
|
+
// the root would then cover other events than the ones it was meant to.
|
|
7
|
+
export const takeEntriesUpTo = (entries, lastEventId) => {
|
|
8
|
+
const last = parseEventId(lastEventId);
|
|
9
|
+
const index = last === undefined
|
|
10
|
+
? -1
|
|
11
|
+
: entries.findIndex(entry => parseEventId(entry.payload.event.id) === last);
|
|
12
|
+
if (index === -1) {
|
|
13
|
+
throw new Error(`the backup holds no event with ID ${lastEventId}`);
|
|
14
|
+
}
|
|
15
|
+
return entries.slice(0, index + 1);
|
|
16
|
+
};
|