-
Notifications
You must be signed in to change notification settings - Fork 9
/
circom-utxo.ts
302 lines (251 loc) · 8.6 KB
/
circom-utxo.ts
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import type { Backend, Curve, JsUtxo } from '@webb-tools/wasm-utils';
import { poseidon } from 'circomlibjs';
import { BigNumber } from 'ethers';
import { hexToU8a, u8aToHex } from '@polkadot/util';
import { randomBN, toBuffer, toFixedHex } from '../big-number-utils.js';
import { Keypair } from '../keypair.js';
import { Utxo, UtxoGenInput } from '../utxo.js';
// The CircomUtxo class implements the Utxo interface so that
// the same 'Utxo' type may be used in serialization between worker contexts
export class CircomUtxo extends Utxo {
_curve: Curve = 'Bn254';
_backend: Backend = 'Circom';
_amount = '';
_chainId = '';
_index?: number;
_pubkey = '';
_secret_key = '';
_blinding = '';
_originChainId?: string;
private constructor (inner: JsUtxo) {
super(inner);
}
serialize (): string {
return [
this._curve,
this._backend,
this.amount,
this.chainId,
this.blinding,
this.getKeypair().getPubKey().slice(2),
this.getKeypair().getEncryptionKey()?.slice(2),
this.getKeypair().privkey?.slice(2),
this.index.toString()
].join('&');
}
/**
* @param utxoString - A string representation of the parts that make up a utxo.
* - All values are represented as BigEndian, hex-encoded strings unless indicated otherwise.
* - Optional values are represented as the empty string if not present,
* meaning the split call will always be an array of length "parts".
*
* parts[0] - Curve value, e.g. Bn254, Bls381, Ed25519, etc. value represented as string.
* parts[1] - Backend value, e.g. arkworks or circom. value represented as string.
* parts[2] - Amount of atomic units, e.g. ETH in wei amounts or DOT in 10^12 decimals. value represented as uint.
* parts[3] - TypedChainId, the hex value of the calculated typed chain id
* parts[4] - Blinding, secret random value
* parts[5] - PublicKey, the "publicKey = hash(privateKey)" value which indicates ownership for a utxo.
* parts[6] Optional - EncryptionKey, the public key of "publicKey = encryptionScheme(privateKey)" value used for messaging.
* parts[7] Optional - PrivateKey, the secret key component correlated to the above values.
* parts[8] Optional - Index, the leaf index if the utxo has been inserted in a merkle tree
* @returns The CircomUtxo object implementation of a Utxo.
*/
static async deserialize (utxoString: string): Promise<Utxo> {
const inner = new CircomJsUtxo();
const utxo = new CircomUtxo(inner);
const parts = utxoString.split('&');
utxo._curve = 'Bn254';
utxo._backend = 'Circom';
utxo._amount = parts[2];
utxo._chainId = parts[3];
utxo._blinding = parts[4];
utxo._pubkey = parts[5];
const maybeEncryptionKey = parts[6];
const maybeSecretKey = parts[7];
const maybeIndex = parts[8];
if (maybeSecretKey.length === 64) {
utxo.setKeypair(new Keypair('0x' + maybeSecretKey));
} else {
if (maybeEncryptionKey.length === 64) {
utxo.setKeypair(Keypair.fromString('0x' + utxo._pubkey + maybeEncryptionKey));
} else {
utxo.setKeypair(Keypair.fromString('0x' + utxo._pubkey));
}
}
if (maybeIndex.length > 0) {
utxo._index = Number(maybeIndex);
}
return utxo;
}
static async generateUtxo (input: UtxoGenInput): Promise<Utxo> {
const inner = new CircomJsUtxo();
const utxo = new CircomUtxo(inner);
// Required parameters
utxo._amount = input.amount;
utxo._chainId = input.chainId;
utxo._curve = input.curve;
utxo._backend = input.backend;
// Optional parameters
utxo._index = input.index ? Number(input.index) : 0;
if (input.keypair) {
utxo.setKeypair(input.keypair);
} else {
// Populate the _pubkey and _secret_key values with
// the random default keypair
utxo.setKeypair(utxo.keypair);
}
utxo._blinding = input.blinding ? u8aToHex(input.blinding).slice(2) : toFixedHex(randomBN(31)).slice(2);
utxo.setOriginChainId(input.originChainId);
return utxo;
}
/**
* Encrypt UTXO data using the current keypair.
* This is used in the externalDataHash calculations so the funds for this deposit
* can only be spent by the owner of `this.keypair`.
*
* @returns `0x`-prefixed hex string with data
*/
encrypt () {
if (!this.getKeypair().getEncryptionKey()) {
throw new Error('Must have a configured encryption key on the keypair to encrypt the utxo');
}
const bytes = Buffer.concat([
toBuffer(BigNumber.from(this._chainId), 8),
toBuffer(BigNumber.from(this._amount), 32),
toBuffer(BigNumber.from('0x' + this._blinding), 32)
]);
return this.getKeypair().encrypt(bytes);
}
/**
* Decrypt a UTXO
*
* @param keypair - keypair used to decrypt
* @param data - hex string with data
* @returns a UTXO object
*/
static async decrypt (keypair: Keypair, data: string) {
const buf = keypair.decrypt(data);
if (buf.length !== 72) {
throw new Error('malformed utxo encryption');
}
const utxo = await CircomUtxo.generateUtxo({
amount: BigNumber.from('0x' + buf.subarray(8, 8 + 32).toString('hex')).toString(),
backend: 'Circom',
blinding: hexToU8a(toFixedHex('0x' + buf.subarray(8 + 32, 8 + 64).toString('hex'))),
chainId: BigNumber.from('0x' + buf.subarray(0, 8).toString('hex')).toString(),
curve: 'Bn254',
keypair
});
return utxo;
}
get amount (): string {
return this._amount;
}
set amount (amount: string) {
this._amount = amount;
}
get blinding (): string {
return this._blinding;
}
set blinding (blinding: string) {
this._blinding = blinding;
}
get chainId (): string {
return this._chainId;
}
set chainId (chainId: string) {
this._chainId = chainId;
}
/**
* Returns commitment for this UTXO
*
* @returns the poseidon hash of [chainId, amount, pubKey, blinding]
*/
get commitment (): Uint8Array {
const hash = poseidon([this._chainId, this._amount, '0x' + this._pubkey, '0x' + this._blinding]);
return hexToU8a(BigNumber.from(hash).toHexString());
}
/**
* @returns the index configured on this UTXO. Output UTXOs generated
* before they have been inserted in a tree.
*
*/
get index (): number {
return this._index ?? 0;
}
set index (index: number) {
this._index = index;
}
/**
* @returns the nullifier: hash of [commitment, index, signature] as decimal string
* where signature = hash([secret key, commitment, index])
*/
get nullifier (): string {
// If the amount of the UTXO is zero, then the nullifier is not important.
// Return a 'dummy' value that will satisfy the circuit
// Enforce index on the UTXO if there is an amount greater than zero
if (!this.getKeypair() || !this.getKeypair().privkey) {
throw new Error('Cannot create nullifier, keypair with private key not configured');
}
const x = poseidon([
u8aToHex(this.commitment),
this.index > 0 ? this.index : 0,
// The following parameter is the 'ownership hash', a portion of the nullifier that enables
// compliance, and ties a utxo to a particular keypair.
poseidon([this.getKeypair().privkey, u8aToHex(this.commitment), this.index])
]);
return toFixedHex(x).slice(2);
}
get public_key (): string {
return this._pubkey;
}
/**
* @returns the secret_key AKA private_key used in the nullifier.
* this value is used to derive the public_key for the commitment.
*/
get secret_key (): string {
return this._secret_key;
}
set secret_key (secret: string) {
this._secret_key = secret;
}
getKeypair (): Keypair {
return this.keypair;
}
setKeypair (keypair: Keypair): void {
this._pubkey = keypair.getPubKey().slice(2);
if (keypair.privkey) {
this._secret_key = keypair.privkey.slice(2);
}
this.keypair = keypair;
}
setIndex (val: number): void {
this.index = val;
}
}
// Implemented to satisfy the Utxo interface, not meant to be used.
// TODO: Support leaf generation in wasm-utils for non-arkworks
class CircomJsUtxo implements JsUtxo {
free (): void {
throw new Error('Method not implemented.');
}
serialize (): string {
throw new Error('Method not implemented.');
}
setIndex (val: bigint): void {
this.index = val;
throw new Error('Method not implemented.');
}
calculate_nullifier (): string {
throw new Error('Method not implemented.');
}
amount = '';
blinding = '';
chainId = '';
chainIdRaw = BigInt(0);
commitment: Uint8Array = new Uint8Array();
index: any;
nullifier = '';
public_key = '';
secret_key = '';
}