/
bch-2023-tokens.ts
389 lines (363 loc) · 13.6 KB
/
bch-2023-tokens.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import { binToHex, flattenBinArray } from '../../../../format/format.js';
import type {
AuthenticationProgramStateError,
AuthenticationProgramStateStack,
AuthenticationProgramStateTransactionContext,
Input,
Output,
Transaction,
} from '../../../../lib.js';
import {
pushToStackChecked,
pushToStackVmNumber,
pushToStackVmNumberChecked,
useTransactionOutput,
useTransactionUtxo,
} from '../../common/common.js';
import { ConsensusBCH2023 } from './bch-2023-consensus.js';
/**
* Given a list of transaction inputs, extract a hex-encoded list of all
* {@link Input.outpointTransactionHash}es from inputs that spend output `0` of
* that transaction (i.e. where {@link Input.outpointIndex} is `0`).
* @param inputs - a list of transaction inputs
* @returns a hex-encoded list of {@link Input.outpointTransactionHash}es
*/
export const extractGenesisCategories = (inputs: Input[]) =>
inputs.reduce<string[]>(
(agg, input) =>
input.outpointIndex === 0
? [...agg, binToHex(input.outpointTransactionHash)]
: agg,
[],
);
type ImmutableToken = {
categoryHex: string;
commitmentHex: string;
};
type FungibleTokensByCategory = {
[categoryHex: string]: bigint;
};
type MutableTokensByCategory = {
[categoryHex: string]: number;
};
/**
* Given the resolved list of a transaction's source outputs – the Unspent
* Transaction Outputs (UTXOs) spent by the transaction, extract all token data
* for token-aware validation. See CHIP-2022-02-CashTokens for details.
* @param sourceOutputs - a list of resolved source outputs (UTXOs)
* @returns an object containing `availableImmutableTokens`,
* `availableMutableTokensByCategory`, `availableSumsByCategory`, and
* `inputMintingCategories`. See CHIP-2022-02-CashTokens for details.
*/
export const extractSourceOutputTokenData = (sourceOutputs: Output[]) =>
sourceOutputs.reduce(
// eslint-disable-next-line complexity
(agg, sourceOutput) => {
if (sourceOutput.token === undefined) return agg;
const categoryHex = binToHex(sourceOutput.token.category);
return {
availableImmutableTokens: [
...agg.availableImmutableTokens,
...(sourceOutput.token.nft?.capability === 'none'
? [
{
categoryHex: binToHex(sourceOutput.token.category),
commitmentHex: binToHex(sourceOutput.token.nft.commitment),
},
]
: []),
],
availableMutableTokensByCategory:
sourceOutput.token.nft?.capability === 'mutable'
? {
...agg.availableMutableTokensByCategory,
[categoryHex]:
(agg.availableMutableTokensByCategory[categoryHex] ?? 0) + 1,
}
: agg.availableMutableTokensByCategory,
availableSumsByCategory: {
...agg.availableSumsByCategory,
[categoryHex]:
(agg.availableSumsByCategory[categoryHex] ?? 0n) +
sourceOutput.token.amount,
},
inputMintingCategories: [
...agg.inputMintingCategories,
...(sourceOutput.token.nft?.capability === 'minting'
? [binToHex(sourceOutput.token.category)]
: []),
],
};
},
{
availableImmutableTokens: [] as ImmutableToken[],
availableMutableTokensByCategory: {} as MutableTokensByCategory,
availableSumsByCategory: {} as FungibleTokensByCategory,
inputMintingCategories: [] as string[],
},
);
/**
* Given a transaction's outputs, extract all token data for token-aware
* validation. See CHIP-2022-02-CashTokens for details.
* @param outputs - a list of transaction outputs
* @returns an object containing `outputImmutableTokens`,
* `outputMintingCategories`, `outputMutableTokensByCategory`, and
* `outputSumsByCategory`. See CHIP-2022-02-CashTokens for details.
*/
export const extractTransactionOutputTokenData = (
outputs: Transaction['outputs'],
) =>
outputs.reduce(
// eslint-disable-next-line complexity
(agg, output) => {
if (output.token === undefined) return agg;
const categoryHex = binToHex(output.token.category);
return {
outputImmutableTokens: [
...agg.outputImmutableTokens,
...(output.token.nft?.capability === 'none'
? [
{
categoryHex: binToHex(output.token.category),
commitmentHex: binToHex(output.token.nft.commitment),
},
]
: []),
],
outputMintingCategories: [
...agg.outputMintingCategories,
...(output.token.nft?.capability === 'minting'
? [binToHex(output.token.category)]
: []),
],
outputMutableTokensByCategory:
output.token.nft?.capability === 'mutable'
? {
...agg.outputMutableTokensByCategory,
[categoryHex]:
(agg.outputMutableTokensByCategory[categoryHex] ?? 0) + 1,
}
: agg.outputMutableTokensByCategory,
outputSumsByCategory: {
...agg.outputSumsByCategory,
[categoryHex]:
(agg.outputSumsByCategory[categoryHex] ?? 0n) + output.token.amount,
},
};
},
{
outputImmutableTokens: [] as ImmutableToken[],
outputMintingCategories: [] as string[],
outputMutableTokensByCategory: {} as MutableTokensByCategory,
outputSumsByCategory: {} as FungibleTokensByCategory,
},
);
/**
* Given a transaction and its resolved source outputs – the Unspent Transaction
* Outputs (UTXOs) it spends – verify that the transaction passes token-aware
* validation.
* @param transaction - the transaction to verify
* @param sourceOutputs - the resolved list of the transaction's source outputs
* @returns `true` on success, or an error message (string) on failure.
*/
// eslint-disable-next-line complexity
export const verifyTransactionTokens = (
transaction: Transaction,
sourceOutputs: Output[],
) => {
const excessiveCommitment = [...sourceOutputs, ...transaction.outputs].find(
(output) =>
output.token?.nft?.commitment !== undefined &&
output.token.nft.commitment.length >
ConsensusBCH2023.maximumCommitmentLength,
);
if (excessiveCommitment !== undefined) {
return `Transaction violates token validation: a token commitment exceeds the consensus limit of ${
ConsensusBCH2023.maximumCommitmentLength
} bytes. Excessive token commitment length: ${
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
excessiveCommitment.token!.nft!.commitment.length
}`;
}
const genesisCategories = extractGenesisCategories(transaction.inputs);
const {
availableSumsByCategory,
availableMutableTokensByCategory,
inputMintingCategories,
availableImmutableTokens,
} = extractSourceOutputTokenData(sourceOutputs);
const {
outputSumsByCategory,
outputMutableTokensByCategory,
outputMintingCategories,
outputImmutableTokens,
} = extractTransactionOutputTokenData(transaction.outputs);
const availableMintingCategories = [
...genesisCategories,
...inputMintingCategories,
];
const missingMintingCategory = outputMintingCategories.find(
(category) => !availableMintingCategories.includes(category),
);
if (missingMintingCategory !== undefined) {
return `Transaction violates token validation: the transaction outputs include a minting token that is not substantiated by the transaction's inputs. Invalid output minting token category: ${missingMintingCategory}`;
}
// eslint-disable-next-line functional/no-loop-statements
for (const [categoryHex, sum] of Object.entries(outputSumsByCategory)) {
if (sum > BigInt(ConsensusBCH2023.maxVmNumber)) {
return `Transaction violates token validation: the transaction outputs include a sum of fungible tokens for a category exceeding the maximum supply (${
ConsensusBCH2023.maxVmNumber
}). Category: ${categoryHex}, total amount: ${sum.toString()}.`;
}
const availableSum = availableSumsByCategory[categoryHex];
if (
availableSum === undefined &&
sum > 0 &&
!genesisCategories.includes(categoryHex)
) {
return `Transaction violates token validation: the transaction creates new fungible tokens for a category without a matching genesis input. Category: ${categoryHex}, tokens created: ${sum}`;
}
if (availableSum !== undefined && sum > availableSum) {
return `Transaction violates token validation: the sum of fungible tokens in the transaction's outputs exceed that of the transactions inputs for a category. Category: ${categoryHex}, input amount: ${availableSum}, output amount: ${sum}`;
}
}
const remainingMutableTokens = Object.entries(
outputMutableTokensByCategory,
).reduce<MutableTokensByCategory>((agg, [categoryHex, sum]) => {
if (availableMintingCategories.includes(categoryHex)) {
return agg;
}
return { ...agg, [categoryHex]: (agg[categoryHex] ?? 0) - sum };
}, availableMutableTokensByCategory);
// eslint-disable-next-line functional/no-loop-statements
for (const [categoryHex, sum] of Object.entries(remainingMutableTokens)) {
if (sum < 0) {
return `Transaction violates token validation: the transaction creates more mutable tokens than are available for a category without a matching minting token. Category: ${categoryHex}, excess mutable tokens: ${
0 - sum
}`;
}
}
const { unmatchedImmutableTokens } = outputImmutableTokens.reduce(
(agg, token) => {
const { categoryHex, commitmentHex } = token;
if (availableMintingCategories.includes(categoryHex)) {
return agg;
}
const firstMatch = availableImmutableTokens.findIndex(
(available) =>
available.categoryHex === categoryHex &&
available.commitmentHex === commitmentHex,
);
if (firstMatch === -1) {
return {
availableImmutableTokens: agg.availableImmutableTokens,
unmatchedImmutableTokens: [...agg.unmatchedImmutableTokens, token],
};
}
// eslint-disable-next-line functional/no-expression-statements, functional/immutable-data
agg.availableImmutableTokens.splice(firstMatch, 1);
return agg;
},
{
availableImmutableTokens,
unmatchedImmutableTokens: [] as ImmutableToken[],
},
);
const requiredMutableTokens =
unmatchedImmutableTokens.reduce<MutableTokensByCategory>(
(agg, token) => ({
...agg,
[token.categoryHex]: (agg[token.categoryHex] ?? 0) + 1,
}),
{},
);
// eslint-disable-next-line functional/no-loop-statements
for (const [categoryHex, required] of Object.entries(requiredMutableTokens)) {
const available = remainingMutableTokens[categoryHex] ?? 0;
if (available < required) {
return `Transaction violates token validation: the transaction creates an immutable token for a category without a matching minting token or sufficient mutable tokens. Category ${categoryHex}, available mutable tokens: ${available}, new immutable tokens: ${required}`;
}
}
return true;
};
const enum Constants {
mutableCapabilityByte = 0x01,
mintingCapabilityByte = 0x02,
}
export const pushTokenExtendedCategory = <
State extends AuthenticationProgramStateError &
AuthenticationProgramStateStack &
AuthenticationProgramStateTransactionContext,
>(
state: State,
utxo: Output,
) => {
const { token } = utxo;
if (token === undefined) {
return pushToStackVmNumber(state, 0n);
}
const capabilityByte =
token.nft?.capability === 'minting'
? [Constants.mintingCapabilityByte]
: token.nft?.capability === 'mutable'
? [Constants.mutableCapabilityByte]
: [];
const extendedCategory = flattenBinArray([
token.category.slice().reverse(),
Uint8Array.from(capabilityByte),
]);
return pushToStackChecked(state, extendedCategory);
};
type TokenOpState = AuthenticationProgramStateError &
AuthenticationProgramStateStack &
AuthenticationProgramStateTransactionContext;
export const pushTokenCommitment = <State extends TokenOpState>(
state: State,
utxo: Output,
) => {
const { token } = utxo;
if (token?.nft === undefined) {
return pushToStackVmNumber(state, 0n);
}
return pushToStackChecked(state, token.nft.commitment);
};
export const pushTokenAmount = <State extends TokenOpState>(
state: State,
utxo: Output,
) => {
const { token } = utxo;
if (token === undefined) {
return pushToStackVmNumber(state, 0n);
}
return pushToStackVmNumberChecked(state, token.amount);
};
export const opUtxoTokenCategory = <State extends TokenOpState>(state: State) =>
useTransactionUtxo(state, (nextState, [utxo]) =>
pushTokenExtendedCategory(nextState, utxo),
);
export const opUtxoTokenCommitment = <State extends TokenOpState>(
state: State,
) =>
useTransactionUtxo(state, (nextState, [utxo]) =>
pushTokenCommitment(nextState, utxo),
);
export const opUtxoTokenAmount = <State extends TokenOpState>(state: State) =>
useTransactionUtxo(state, (nextState, [utxo]) =>
pushTokenAmount(nextState, utxo),
);
export const opOutputTokenCategory = <State extends TokenOpState>(
state: State,
) =>
useTransactionOutput(state, (nextState, [output]) =>
pushTokenExtendedCategory(nextState, output),
);
export const opOutputTokenCommitment = <State extends TokenOpState>(
state: State,
) =>
useTransactionOutput(state, (nextState, [output]) =>
pushTokenCommitment(nextState, output),
);
export const opOutputTokenAmount = <State extends TokenOpState>(state: State) =>
useTransactionOutput(state, (nextState, [output]) =>
pushTokenAmount(nextState, output),
);