forked from Dshield-xyz/Dshield
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathposeidon2.ts
More file actions
140 lines (118 loc) · 3.91 KB
/
Copy pathposeidon2.ts
File metadata and controls
140 lines (118 loc) · 3.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import { Noir } from "@noir-lang/noir_js";
import hasherCircuit from "@/circuits/hasher.json";
let noirInstance: InstanceType<typeof Noir> | null = null;
async function getHasher(): Promise<InstanceType<typeof Noir>> {
if (!noirInstance) {
noirInstance = new Noir(hasherCircuit as never);
}
return noirInstance;
}
/**
* Left-pad a field element to a canonical 32-byte (64 hex char) 0x-prefixed
* string. The Noir hasher returns field values WITHOUT leading-zero padding
* (e.g. a root whose top byte is 0x00 comes back as "0x301b…" not "0x00301b…").
* On-chain the same value is always a full 32-byte BytesN<32>, so comparing the
* two as raw strings — or slicing them into a Buffer for an ScVal — silently
* breaks (~1/256 of values) unless both sides are normalized to 32 bytes.
*/
export function normalizeField(v: string): string {
const hex = v.replace(/^0x/, "").toLowerCase();
if (hex.length > 64) {
throw new Error(`field element exceeds 32 bytes: ${v}`);
}
return "0x" + hex.padStart(64, "0");
}
export async function poseidon2Hash(a: string, b: string): Promise<string> {
const noir = await getHasher();
const result = await noir.execute({ a, b });
return normalizeField(result.returnValue as string);
}
export async function computeCommitment(
nullifier: string,
secret: string,
): Promise<string> {
return poseidon2Hash(toField(nullifier), toField(secret));
}
export async function computeNullifierHash(
nullifier: string,
): Promise<string> {
return poseidon2Hash(toField(nullifier), "0");
}
function toField(hex: string): string {
if (hex.startsWith("0x")) return hex;
return "0x" + hex;
}
const TREE_DEPTH = 20;
let zeroHashesCache: string[] | null = null;
export async function getZeroHashes(): Promise<string[]> {
if (zeroHashesCache) return zeroHashesCache;
const zeroes: string[] = [];
let cur = "0x" + "00".repeat(32);
zeroes.push(cur);
for (let i = 0; i < TREE_DEPTH; i++) {
cur = await poseidon2Hash(cur, cur);
zeroes.push(cur);
}
zeroHashesCache = zeroes;
return zeroes;
}
export interface MerkleProof {
root: string;
pathSiblings: string[];
pathBits: number[];
}
export async function buildMerkleTree(
commitments: string[],
targetIndex: number,
): Promise<MerkleProof> {
const zeroes = await getZeroHashes();
const n = commitments.length;
const leaves: string[] = [];
for (let i = 0; i < Math.max(n, targetIndex + 1); i++) {
leaves.push(i < n ? ensureHex(commitments[i]) : zeroes[0]);
}
let currentLevel = leaves;
const pathSiblings: string[] = [];
const pathBits: number[] = [];
let targetIdx = targetIndex;
for (let depth = 0; depth < TREE_DEPTH; depth++) {
const bit = targetIdx & 1;
pathBits.push(bit);
const siblingIdx = targetIdx ^ 1;
if (siblingIdx < currentLevel.length) {
pathSiblings.push(currentLevel[siblingIdx]);
} else {
pathSiblings.push(zeroes[depth]);
}
const nextLevel: string[] = [];
for (let i = 0; i < currentLevel.length; i += 2) {
const left = currentLevel[i];
const right = i + 1 < currentLevel.length ? currentLevel[i + 1] : zeroes[depth];
nextLevel.push(await poseidon2Hash(left, right));
}
if (nextLevel.length === 0) {
nextLevel.push(zeroes[depth + 1]);
}
currentLevel = nextLevel;
targetIdx = targetIdx >> 1;
}
return {
root: currentLevel[0],
pathSiblings,
pathBits,
};
}
export async function computeRecipientHash(
stellarAddress: string,
): Promise<string> {
const StellarSdk = await import("@stellar/stellar-sdk");
const keypair = StellarSdk.Keypair.fromPublicKey(stellarAddress);
const rawKey = keypair.rawPublicKey();
const lo = "0x00" + Buffer.from(rawKey.slice(0, 15)).toString("hex");
const hi = "0x00" + Buffer.from(rawKey.slice(15)).toString("hex");
return poseidon2Hash(lo, hi);
}
function ensureHex(v: string): string {
if (v.startsWith("0x")) return v;
return "0x" + v;
}