@txfence/provenance 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.
- package/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +64 -0
- package/dist/index.d.ts +94 -0
- package/dist/index.js +396 -0
- package/package.json +32 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# @txfence/provenance
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Initial public release — policy engine, intent execution, formal verification, adversarial stress testing, cryptographic provenance chains, temporal rules, and MEV protection across EVM, Solana, and Cosmos
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies
|
|
12
|
+
- @txfence/core@0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aditya Chauhan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# @txfence/provenance
|
|
2
|
+
|
|
3
|
+
Cryptographically linked provenance records for txfence transactions.
|
|
4
|
+
|
|
5
|
+
## What this is
|
|
6
|
+
|
|
7
|
+
Every transaction gets a provenance record capturing: which agent submitted it,
|
|
8
|
+
which policy version evaluated it, what the simulation returned, who approved it,
|
|
9
|
+
and the final on-chain receipt. Records form a hash chain and a Merkle tree.
|
|
10
|
+
|
|
11
|
+
At any point you can:
|
|
12
|
+
- Prove a specific transaction was authorized under a specific policy
|
|
13
|
+
- Verify the chain has not been tampered with
|
|
14
|
+
- Generate a compact Merkle proof for any record
|
|
15
|
+
|
|
16
|
+
## Use case
|
|
17
|
+
|
|
18
|
+
Hand a compliance officer cryptographic proof that every transaction
|
|
19
|
+
followed your policy:
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { createFileProvenanceChain } from '@txfence/provenance'
|
|
23
|
+
|
|
24
|
+
const chain = createFileProvenanceChain('./provenance.jsonl')
|
|
25
|
+
|
|
26
|
+
// Append a record after each pipeline execution
|
|
27
|
+
await chain.append({
|
|
28
|
+
agentId: '0xAGENT',
|
|
29
|
+
policyVersionId: getPolicyVersionId(policy),
|
|
30
|
+
action,
|
|
31
|
+
simulationResult,
|
|
32
|
+
approvalDecision: 'not_required',
|
|
33
|
+
outcome: { status: 'success', txHash: '0x...', confirmedAtBlock: 1000, gasUsed: '21000' },
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
// Verify the chain has not been tampered with
|
|
37
|
+
const result = await chain.verify()
|
|
38
|
+
console.log(result.valid) // true if unmodified
|
|
39
|
+
|
|
40
|
+
// Generate a proof for a specific transaction
|
|
41
|
+
const proof = await chain.generateProof(entryHash)
|
|
42
|
+
|
|
43
|
+
// Verify the proof
|
|
44
|
+
console.log(chain.verifyProof(proof)) // true
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Tamper evidence
|
|
48
|
+
|
|
49
|
+
Hash chaining: each record includes the hash of the previous record.
|
|
50
|
+
Modifying any record invalidates all subsequent records.
|
|
51
|
+
|
|
52
|
+
Merkle tree: the root hash commits to all records. A Merkle proof proves
|
|
53
|
+
a record exists without revealing all other records.
|
|
54
|
+
|
|
55
|
+
## Known limitation
|
|
56
|
+
|
|
57
|
+
The chain file must be stored on tamper-evident infrastructure (S3 with
|
|
58
|
+
object lock, WORM storage) for strict compliance requirements.
|
|
59
|
+
The hash chain detects tampering but does not prevent it on a writable filesystem.
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
Full project README: https://github.com/AdityaChauhanX07/txfence
|
|
64
|
+
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { Action, SimulationResult, PolicyRejectionReason, ExecutionFailureReason, SuccessReceipt, ChainId } from '@txfence/core';
|
|
2
|
+
|
|
3
|
+
type ProvenanceOutcome = {
|
|
4
|
+
status: 'success';
|
|
5
|
+
txHash: string;
|
|
6
|
+
confirmedAtBlock: number;
|
|
7
|
+
gasUsed: string;
|
|
8
|
+
} | {
|
|
9
|
+
status: 'policy_rejected';
|
|
10
|
+
reason: PolicyRejectionReason;
|
|
11
|
+
} | {
|
|
12
|
+
status: 'simulation_failed';
|
|
13
|
+
} | {
|
|
14
|
+
status: 'approval_timeout';
|
|
15
|
+
} | {
|
|
16
|
+
status: 'execution_failed';
|
|
17
|
+
reason: ExecutionFailureReason;
|
|
18
|
+
} | {
|
|
19
|
+
status: 'simulation_stale';
|
|
20
|
+
stalenessMs: number;
|
|
21
|
+
};
|
|
22
|
+
type ProvenanceRecord = {
|
|
23
|
+
id: string;
|
|
24
|
+
previousHash: string;
|
|
25
|
+
entryHash: string;
|
|
26
|
+
timestamp: number;
|
|
27
|
+
agentId: string;
|
|
28
|
+
policyVersionId: string;
|
|
29
|
+
action: Action;
|
|
30
|
+
simulationResult?: SimulationResult;
|
|
31
|
+
approvalDecision?: 'approved' | 'rejected' | 'not_required';
|
|
32
|
+
approver?: string;
|
|
33
|
+
submittedAtBlock?: number;
|
|
34
|
+
submittedAtBlockHash?: string;
|
|
35
|
+
outcome: ProvenanceOutcome;
|
|
36
|
+
receipt?: SuccessReceipt;
|
|
37
|
+
};
|
|
38
|
+
type ProvenanceRecordInput = Omit<ProvenanceRecord, 'id' | 'previousHash' | 'entryHash'>;
|
|
39
|
+
type MerkleProof = {
|
|
40
|
+
entryHash: string;
|
|
41
|
+
siblings: Array<{
|
|
42
|
+
hash: string;
|
|
43
|
+
position: 'left' | 'right';
|
|
44
|
+
}>;
|
|
45
|
+
root: string;
|
|
46
|
+
leafIndex: number;
|
|
47
|
+
};
|
|
48
|
+
type ProvenanceFilter = {
|
|
49
|
+
agentId?: string;
|
|
50
|
+
policyVersionId?: string;
|
|
51
|
+
status?: ProvenanceOutcome['status'];
|
|
52
|
+
from?: number;
|
|
53
|
+
to?: number;
|
|
54
|
+
chain?: ChainId;
|
|
55
|
+
};
|
|
56
|
+
type ChainViolation = {
|
|
57
|
+
entryId: string;
|
|
58
|
+
entryHash: string;
|
|
59
|
+
violation: 'hash_mismatch' | 'chain_broken' | 'invalid_hash';
|
|
60
|
+
details: string;
|
|
61
|
+
};
|
|
62
|
+
type ProvenanceVerificationResult = {
|
|
63
|
+
valid: boolean;
|
|
64
|
+
entryCount: number;
|
|
65
|
+
firstHash: string;
|
|
66
|
+
lastHash: string;
|
|
67
|
+
merkleRoot: string;
|
|
68
|
+
violations: ChainViolation[];
|
|
69
|
+
verifiedAt: number;
|
|
70
|
+
};
|
|
71
|
+
type ProvenanceChain = {
|
|
72
|
+
append: (record: ProvenanceRecordInput) => Promise<ProvenanceRecord>;
|
|
73
|
+
get: (entryHash: string) => Promise<ProvenanceRecord | null>;
|
|
74
|
+
list: (filter?: ProvenanceFilter) => Promise<ProvenanceRecord[]>;
|
|
75
|
+
head: () => Promise<ProvenanceRecord | null>;
|
|
76
|
+
verify: () => Promise<ProvenanceVerificationResult>;
|
|
77
|
+
generateProof: (entryHash: string) => Promise<MerkleProof | null>;
|
|
78
|
+
verifyProof: (proof: MerkleProof) => boolean;
|
|
79
|
+
getMerkleRoot: () => Promise<string>;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
declare function createMemoryProvenanceChain(): ProvenanceChain;
|
|
83
|
+
|
|
84
|
+
declare function createFileProvenanceChain(filePath: string): ProvenanceChain;
|
|
85
|
+
|
|
86
|
+
declare function computeEntryHash(previousHash: string, record: ProvenanceRecordInput): string;
|
|
87
|
+
declare const GENESIS_HASH: string;
|
|
88
|
+
|
|
89
|
+
declare function buildMerkleTree(leafHashes: string[]): string[][];
|
|
90
|
+
declare function getMerkleRoot(leafHashes: string[]): string;
|
|
91
|
+
declare function generateMerkleProof(leafHashes: string[], targetHash: string): MerkleProof | null;
|
|
92
|
+
declare function verifyMerkleProof(proof: MerkleProof): boolean;
|
|
93
|
+
|
|
94
|
+
export { type ChainViolation, GENESIS_HASH, type MerkleProof, type ProvenanceChain, type ProvenanceFilter, type ProvenanceOutcome, type ProvenanceRecord, type ProvenanceRecordInput, type ProvenanceVerificationResult, buildMerkleTree, computeEntryHash, createFileProvenanceChain, createMemoryProvenanceChain, generateMerkleProof, getMerkleRoot, verifyMerkleProof };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// src/memory.ts
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
|
|
4
|
+
// src/hash.ts
|
|
5
|
+
import { createHash } from "crypto";
|
|
6
|
+
function canonicalize(value) {
|
|
7
|
+
if (typeof value === "bigint") return value.toString();
|
|
8
|
+
if (Array.isArray(value)) return value.map(canonicalize);
|
|
9
|
+
if (value !== null && typeof value === "object") {
|
|
10
|
+
const sorted = {};
|
|
11
|
+
for (const key of Object.keys(value).sort()) {
|
|
12
|
+
sorted[key] = canonicalize(value[key]);
|
|
13
|
+
}
|
|
14
|
+
return sorted;
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function computeEntryHash(previousHash, record) {
|
|
19
|
+
const content = {
|
|
20
|
+
previousHash,
|
|
21
|
+
agentId: record.agentId,
|
|
22
|
+
policyVersionId: record.policyVersionId,
|
|
23
|
+
action: record.action,
|
|
24
|
+
simulationResult: record.simulationResult,
|
|
25
|
+
approvalDecision: record.approvalDecision,
|
|
26
|
+
approver: record.approver,
|
|
27
|
+
submittedAtBlock: record.submittedAtBlock,
|
|
28
|
+
submittedAtBlockHash: record.submittedAtBlockHash,
|
|
29
|
+
outcome: record.outcome,
|
|
30
|
+
timestamp: record.timestamp
|
|
31
|
+
};
|
|
32
|
+
const canonical = JSON.stringify(canonicalize(content));
|
|
33
|
+
return createHash("sha256").update(canonical).digest("hex");
|
|
34
|
+
}
|
|
35
|
+
var GENESIS_HASH = "0".repeat(64);
|
|
36
|
+
|
|
37
|
+
// src/merkle.ts
|
|
38
|
+
import { createHash as createHash2 } from "crypto";
|
|
39
|
+
function hashPair(left, right) {
|
|
40
|
+
return createHash2("sha256").update(left + right).digest("hex");
|
|
41
|
+
}
|
|
42
|
+
function buildMerkleTree(leafHashes) {
|
|
43
|
+
if (leafHashes.length === 0) return [[]];
|
|
44
|
+
const levels = [leafHashes];
|
|
45
|
+
let current = leafHashes;
|
|
46
|
+
while (current.length > 1) {
|
|
47
|
+
const next = [];
|
|
48
|
+
for (let i = 0; i < current.length; i += 2) {
|
|
49
|
+
const left = current[i];
|
|
50
|
+
const right = current[i + 1] ?? current[i];
|
|
51
|
+
next.push(hashPair(left, right));
|
|
52
|
+
}
|
|
53
|
+
levels.push(next);
|
|
54
|
+
current = next;
|
|
55
|
+
}
|
|
56
|
+
return levels;
|
|
57
|
+
}
|
|
58
|
+
function getMerkleRoot(leafHashes) {
|
|
59
|
+
if (leafHashes.length === 0) return "0".repeat(64);
|
|
60
|
+
const tree = buildMerkleTree(leafHashes);
|
|
61
|
+
return tree[tree.length - 1]?.[0] ?? "0".repeat(64);
|
|
62
|
+
}
|
|
63
|
+
function generateMerkleProof(leafHashes, targetHash) {
|
|
64
|
+
const leafIndex = leafHashes.indexOf(targetHash);
|
|
65
|
+
if (leafIndex === -1) return null;
|
|
66
|
+
const tree = buildMerkleTree(leafHashes);
|
|
67
|
+
const root = tree[tree.length - 1]?.[0] ?? "0".repeat(64);
|
|
68
|
+
const siblings = [];
|
|
69
|
+
let index = leafIndex;
|
|
70
|
+
for (let level = 0; level < tree.length - 1; level++) {
|
|
71
|
+
const levelNodes = tree[level];
|
|
72
|
+
const isLeftNode = index % 2 === 0;
|
|
73
|
+
const siblingIndex = isLeftNode ? index + 1 : index - 1;
|
|
74
|
+
const siblingHash = levelNodes[siblingIndex] ?? levelNodes[index];
|
|
75
|
+
siblings.push({
|
|
76
|
+
hash: siblingHash,
|
|
77
|
+
position: isLeftNode ? "right" : "left"
|
|
78
|
+
});
|
|
79
|
+
index = Math.floor(index / 2);
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
entryHash: targetHash,
|
|
83
|
+
siblings,
|
|
84
|
+
root,
|
|
85
|
+
leafIndex
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function verifyMerkleProof(proof) {
|
|
89
|
+
let current = proof.entryHash;
|
|
90
|
+
for (const sibling of proof.siblings) {
|
|
91
|
+
if (sibling.position === "right") {
|
|
92
|
+
current = hashPair(current, sibling.hash);
|
|
93
|
+
} else {
|
|
94
|
+
current = hashPair(sibling.hash, current);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return current === proof.root;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// src/memory.ts
|
|
101
|
+
function createMemoryProvenanceChain() {
|
|
102
|
+
const records = [];
|
|
103
|
+
async function append(input) {
|
|
104
|
+
const previousHash = records.length > 0 ? records[records.length - 1].entryHash : GENESIS_HASH;
|
|
105
|
+
const entryHash = computeEntryHash(previousHash, input);
|
|
106
|
+
const record = {
|
|
107
|
+
id: randomUUID(),
|
|
108
|
+
previousHash,
|
|
109
|
+
entryHash,
|
|
110
|
+
...input
|
|
111
|
+
};
|
|
112
|
+
records.push(record);
|
|
113
|
+
return record;
|
|
114
|
+
}
|
|
115
|
+
async function get(entryHash) {
|
|
116
|
+
return records.find((r) => r.entryHash === entryHash) ?? null;
|
|
117
|
+
}
|
|
118
|
+
async function list(filter) {
|
|
119
|
+
let result = [...records];
|
|
120
|
+
if (filter?.agentId !== void 0) {
|
|
121
|
+
const v = filter.agentId;
|
|
122
|
+
result = result.filter((r) => r.agentId === v);
|
|
123
|
+
}
|
|
124
|
+
if (filter?.policyVersionId !== void 0) {
|
|
125
|
+
const v = filter.policyVersionId;
|
|
126
|
+
result = result.filter((r) => r.policyVersionId === v);
|
|
127
|
+
}
|
|
128
|
+
if (filter?.status !== void 0) {
|
|
129
|
+
const v = filter.status;
|
|
130
|
+
result = result.filter((r) => r.outcome.status === v);
|
|
131
|
+
}
|
|
132
|
+
if (filter?.from !== void 0) {
|
|
133
|
+
const v = filter.from;
|
|
134
|
+
result = result.filter((r) => r.timestamp >= v);
|
|
135
|
+
}
|
|
136
|
+
if (filter?.to !== void 0) {
|
|
137
|
+
const v = filter.to;
|
|
138
|
+
result = result.filter((r) => r.timestamp <= v);
|
|
139
|
+
}
|
|
140
|
+
if (filter?.chain !== void 0) {
|
|
141
|
+
const v = filter.chain;
|
|
142
|
+
result = result.filter((r) => r.action.chain === v);
|
|
143
|
+
}
|
|
144
|
+
return result;
|
|
145
|
+
}
|
|
146
|
+
async function head() {
|
|
147
|
+
return records[records.length - 1] ?? null;
|
|
148
|
+
}
|
|
149
|
+
async function verify() {
|
|
150
|
+
const violations = [];
|
|
151
|
+
for (let i = 0; i < records.length; i++) {
|
|
152
|
+
const record = records[i];
|
|
153
|
+
const expectedPreviousHash = i === 0 ? GENESIS_HASH : records[i - 1].entryHash;
|
|
154
|
+
if (record.previousHash !== expectedPreviousHash) {
|
|
155
|
+
violations.push({
|
|
156
|
+
entryId: record.id,
|
|
157
|
+
entryHash: record.entryHash,
|
|
158
|
+
violation: "chain_broken",
|
|
159
|
+
details: `Entry ${i}: previousHash mismatch. Expected ${expectedPreviousHash.slice(0, 8)}... got ${record.previousHash.slice(0, 8)}...`
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
const { id: _id, previousHash, entryHash, ...input } = record;
|
|
163
|
+
void _id;
|
|
164
|
+
const recomputed = computeEntryHash(previousHash, input);
|
|
165
|
+
if (recomputed !== entryHash) {
|
|
166
|
+
violations.push({
|
|
167
|
+
entryId: record.id,
|
|
168
|
+
entryHash: record.entryHash,
|
|
169
|
+
violation: "hash_mismatch",
|
|
170
|
+
details: `Entry ${i}: hash mismatch. Stored ${entryHash.slice(0, 8)}... recomputed ${recomputed.slice(0, 8)}...`
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const leafHashes = records.map((r) => r.entryHash);
|
|
175
|
+
const merkleRoot = getMerkleRoot(leafHashes);
|
|
176
|
+
return {
|
|
177
|
+
valid: violations.length === 0,
|
|
178
|
+
entryCount: records.length,
|
|
179
|
+
firstHash: records[0]?.entryHash ?? GENESIS_HASH,
|
|
180
|
+
lastHash: records[records.length - 1]?.entryHash ?? GENESIS_HASH,
|
|
181
|
+
merkleRoot,
|
|
182
|
+
violations,
|
|
183
|
+
verifiedAt: Date.now()
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
async function generateProof(entryHash) {
|
|
187
|
+
const leafHashes = records.map((r) => r.entryHash);
|
|
188
|
+
return generateMerkleProof(leafHashes, entryHash);
|
|
189
|
+
}
|
|
190
|
+
function verifyProof(proof) {
|
|
191
|
+
return verifyMerkleProof(proof);
|
|
192
|
+
}
|
|
193
|
+
async function getMerkleRootFn() {
|
|
194
|
+
const leafHashes = records.map((r) => r.entryHash);
|
|
195
|
+
return getMerkleRoot(leafHashes);
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
append,
|
|
199
|
+
get,
|
|
200
|
+
list,
|
|
201
|
+
head,
|
|
202
|
+
verify,
|
|
203
|
+
generateProof,
|
|
204
|
+
verifyProof,
|
|
205
|
+
getMerkleRoot: getMerkleRootFn
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/file.ts
|
|
210
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
211
|
+
import {
|
|
212
|
+
readFileSync,
|
|
213
|
+
writeFileSync,
|
|
214
|
+
existsSync,
|
|
215
|
+
renameSync,
|
|
216
|
+
mkdirSync
|
|
217
|
+
} from "fs";
|
|
218
|
+
import { dirname } from "path";
|
|
219
|
+
import { bigintReplacer } from "@txfence/core";
|
|
220
|
+
function createFileProvenanceChain(filePath) {
|
|
221
|
+
function ensureDir() {
|
|
222
|
+
const dir = dirname(filePath);
|
|
223
|
+
if (!existsSync(dir)) {
|
|
224
|
+
mkdirSync(dir, { recursive: true });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function reviveRecord(raw) {
|
|
228
|
+
const action = raw["action"];
|
|
229
|
+
if (action["kind"] === "transfer") {
|
|
230
|
+
const token = action["token"];
|
|
231
|
+
if (typeof token["amount"] === "string") {
|
|
232
|
+
token["amount"] = BigInt(token["amount"]);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (action["kind"] === "swap") {
|
|
236
|
+
const from = action["from"];
|
|
237
|
+
if (typeof from["amount"] === "string") {
|
|
238
|
+
from["amount"] = BigInt(from["amount"]);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (action["kind"] === "contract_call" && action["value"] !== void 0) {
|
|
242
|
+
const value = action["value"];
|
|
243
|
+
if (typeof value["amount"] === "string") {
|
|
244
|
+
value["amount"] = BigInt(value["amount"]);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (raw["simulationResult"] !== void 0) {
|
|
248
|
+
const sim = raw["simulationResult"];
|
|
249
|
+
if (typeof sim["gasEstimate"] === "string") {
|
|
250
|
+
sim["gasEstimate"] = BigInt(sim["gasEstimate"]);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return raw;
|
|
254
|
+
}
|
|
255
|
+
function readAll() {
|
|
256
|
+
if (!existsSync(filePath)) return [];
|
|
257
|
+
const content = readFileSync(filePath, "utf-8").trim();
|
|
258
|
+
if (content.length === 0) return [];
|
|
259
|
+
return content.split("\n").map((line) => {
|
|
260
|
+
const parsed = JSON.parse(line);
|
|
261
|
+
return reviveRecord(parsed);
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
function appendRecord(record) {
|
|
265
|
+
ensureDir();
|
|
266
|
+
const line = JSON.stringify(record, bigintReplacer) + "\n";
|
|
267
|
+
const tmpPath = filePath + ".tmp";
|
|
268
|
+
const existing = existsSync(filePath) ? readFileSync(filePath, "utf-8") : "";
|
|
269
|
+
writeFileSync(tmpPath, existing + line, "utf-8");
|
|
270
|
+
try {
|
|
271
|
+
renameSync(tmpPath, filePath);
|
|
272
|
+
} catch {
|
|
273
|
+
writeFileSync(filePath, existing + line, "utf-8");
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
async function append(input) {
|
|
277
|
+
const records = readAll();
|
|
278
|
+
const previousHash = records.length > 0 ? records[records.length - 1].entryHash : GENESIS_HASH;
|
|
279
|
+
const entryHash = computeEntryHash(previousHash, input);
|
|
280
|
+
const record = {
|
|
281
|
+
id: randomUUID2(),
|
|
282
|
+
previousHash,
|
|
283
|
+
entryHash,
|
|
284
|
+
...input
|
|
285
|
+
};
|
|
286
|
+
appendRecord(record);
|
|
287
|
+
return record;
|
|
288
|
+
}
|
|
289
|
+
async function get(entryHash) {
|
|
290
|
+
const records = readAll();
|
|
291
|
+
return records.find((r) => r.entryHash === entryHash) ?? null;
|
|
292
|
+
}
|
|
293
|
+
async function list(filter) {
|
|
294
|
+
let records = readAll();
|
|
295
|
+
if (filter?.agentId !== void 0) {
|
|
296
|
+
const v = filter.agentId;
|
|
297
|
+
records = records.filter((r) => r.agentId === v);
|
|
298
|
+
}
|
|
299
|
+
if (filter?.policyVersionId !== void 0) {
|
|
300
|
+
const v = filter.policyVersionId;
|
|
301
|
+
records = records.filter((r) => r.policyVersionId === v);
|
|
302
|
+
}
|
|
303
|
+
if (filter?.status !== void 0) {
|
|
304
|
+
const v = filter.status;
|
|
305
|
+
records = records.filter((r) => r.outcome.status === v);
|
|
306
|
+
}
|
|
307
|
+
if (filter?.from !== void 0) {
|
|
308
|
+
const v = filter.from;
|
|
309
|
+
records = records.filter((r) => r.timestamp >= v);
|
|
310
|
+
}
|
|
311
|
+
if (filter?.to !== void 0) {
|
|
312
|
+
const v = filter.to;
|
|
313
|
+
records = records.filter((r) => r.timestamp <= v);
|
|
314
|
+
}
|
|
315
|
+
if (filter?.chain !== void 0) {
|
|
316
|
+
const v = filter.chain;
|
|
317
|
+
records = records.filter((r) => r.action.chain === v);
|
|
318
|
+
}
|
|
319
|
+
return records;
|
|
320
|
+
}
|
|
321
|
+
async function head() {
|
|
322
|
+
const records = readAll();
|
|
323
|
+
return records[records.length - 1] ?? null;
|
|
324
|
+
}
|
|
325
|
+
async function verify() {
|
|
326
|
+
const records = readAll();
|
|
327
|
+
const violations = [];
|
|
328
|
+
for (let i = 0; i < records.length; i++) {
|
|
329
|
+
const record = records[i];
|
|
330
|
+
const expectedPreviousHash = i === 0 ? GENESIS_HASH : records[i - 1].entryHash;
|
|
331
|
+
if (record.previousHash !== expectedPreviousHash) {
|
|
332
|
+
violations.push({
|
|
333
|
+
entryId: record.id,
|
|
334
|
+
entryHash: record.entryHash,
|
|
335
|
+
violation: "chain_broken",
|
|
336
|
+
details: `Entry ${i}: previousHash mismatch`
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
const { id: _id, previousHash, entryHash, ...input } = record;
|
|
340
|
+
void _id;
|
|
341
|
+
const recomputed = computeEntryHash(previousHash, input);
|
|
342
|
+
if (recomputed !== entryHash) {
|
|
343
|
+
violations.push({
|
|
344
|
+
entryId: record.id,
|
|
345
|
+
entryHash: record.entryHash,
|
|
346
|
+
violation: "hash_mismatch",
|
|
347
|
+
details: `Entry ${i}: hash mismatch. Record may have been tampered with.`
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const leafHashes = records.map((r) => r.entryHash);
|
|
352
|
+
const merkleRoot = getMerkleRoot(leafHashes);
|
|
353
|
+
return {
|
|
354
|
+
valid: violations.length === 0,
|
|
355
|
+
entryCount: records.length,
|
|
356
|
+
firstHash: records[0]?.entryHash ?? GENESIS_HASH,
|
|
357
|
+
lastHash: records[records.length - 1]?.entryHash ?? GENESIS_HASH,
|
|
358
|
+
merkleRoot,
|
|
359
|
+
violations,
|
|
360
|
+
verifiedAt: Date.now()
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
async function generateProof(entryHash) {
|
|
364
|
+
const records = readAll();
|
|
365
|
+
const leafHashes = records.map((r) => r.entryHash);
|
|
366
|
+
return generateMerkleProof(leafHashes, entryHash);
|
|
367
|
+
}
|
|
368
|
+
function verifyProof(proof) {
|
|
369
|
+
return verifyMerkleProof(proof);
|
|
370
|
+
}
|
|
371
|
+
async function getMerkleRootFn() {
|
|
372
|
+
const records = readAll();
|
|
373
|
+
const leafHashes = records.map((r) => r.entryHash);
|
|
374
|
+
return getMerkleRoot(leafHashes);
|
|
375
|
+
}
|
|
376
|
+
return {
|
|
377
|
+
append,
|
|
378
|
+
get,
|
|
379
|
+
list,
|
|
380
|
+
head,
|
|
381
|
+
verify,
|
|
382
|
+
generateProof,
|
|
383
|
+
verifyProof,
|
|
384
|
+
getMerkleRoot: getMerkleRootFn
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
export {
|
|
388
|
+
GENESIS_HASH,
|
|
389
|
+
buildMerkleTree,
|
|
390
|
+
computeEntryHash,
|
|
391
|
+
createFileProvenanceChain,
|
|
392
|
+
createMemoryProvenanceChain,
|
|
393
|
+
generateMerkleProof,
|
|
394
|
+
getMerkleRoot,
|
|
395
|
+
verifyMerkleProof
|
|
396
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@txfence/provenance",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"private": false,
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"types": "./dist/index.d.ts"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"CHANGELOG.md"
|
|
18
|
+
],
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@txfence/core": "0.1.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"vitest": "^4.1.5",
|
|
24
|
+
"tsup": "^8.0.0",
|
|
25
|
+
"@types/node": "^20.0.0"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "tsup",
|
|
29
|
+
"clean": "rm -rf dist",
|
|
30
|
+
"test": "vitest run"
|
|
31
|
+
}
|
|
32
|
+
}
|