@ocap/tx-pipeline 1.30.24 → 1.30.26

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.
Files changed (63) hide show
  1. package/esm/helpers/dedup-height.d.mts +16 -0
  2. package/esm/helpers/dedup-height.mjs +61 -0
  3. package/esm/index.d.mts +7 -4
  4. package/esm/index.mjs +6 -4
  5. package/esm/pipes/anti-land-attack.mjs +1 -1
  6. package/esm/pipes/decode-tx.d.mts +3 -2
  7. package/esm/pipes/decode-tx.mjs +175 -29
  8. package/esm/pipes/extract-signer.mjs +11 -2
  9. package/esm/pipes/extract-state.d.mts +4 -1
  10. package/esm/pipes/extract-state.mjs +14 -7
  11. package/esm/pipes/take-state-snapshot.mjs +8 -0
  12. package/esm/pipes/update-owner.d.mts +3 -1
  13. package/esm/pipes/update-owner.mjs +28 -2
  14. package/esm/pipes/verify-account-migration.mjs +2 -2
  15. package/esm/pipes/verify-blocked.mjs +1 -1
  16. package/esm/pipes/verify-delegation.d.mts +6 -3
  17. package/esm/pipes/verify-delegation.mjs +121 -47
  18. package/esm/pipes/verify-list-size.mjs +1 -1
  19. package/esm/pipes/verify-multisig-v2.mjs +39 -9
  20. package/esm/pipes/verify-multisig.mjs +20 -5
  21. package/esm/pipes/verify-sender.mjs +1 -1
  22. package/esm/pipes/verify-signature.mjs +14 -5
  23. package/esm/pipes/verify-signer.mjs +5 -3
  24. package/esm/pipes/verify-token-access.mjs +31 -2
  25. package/esm/pipes/verify-token-balance.mjs +4 -2
  26. package/esm/pipes/verify-transferrable.mjs +1 -1
  27. package/esm/pipes/verify-tx-input.mjs +3 -3
  28. package/esm/pipes/verify-tx-size.mjs +1 -1
  29. package/esm/pipes/verify-tx.d.mts +1 -1
  30. package/esm/pipes/verify-tx.mjs +12 -5
  31. package/esm/pipes/verify-updater.mjs +1 -1
  32. package/lib/helpers/dedup-height.cjs +72 -0
  33. package/lib/helpers/dedup-height.d.cts +16 -0
  34. package/lib/index.cjs +15 -0
  35. package/lib/index.d.cts +7 -4
  36. package/lib/pipes/anti-land-attack.cjs +2 -2
  37. package/lib/pipes/decode-tx.cjs +176 -26
  38. package/lib/pipes/decode-tx.d.cts +3 -2
  39. package/lib/pipes/extract-signer.cjs +11 -2
  40. package/lib/pipes/extract-state.cjs +14 -7
  41. package/lib/pipes/extract-state.d.cts +4 -1
  42. package/lib/pipes/take-state-snapshot.cjs +8 -0
  43. package/lib/pipes/update-owner.cjs +29 -2
  44. package/lib/pipes/update-owner.d.cts +3 -1
  45. package/lib/pipes/verify-account-migration.cjs +2 -2
  46. package/lib/pipes/verify-blocked.cjs +1 -1
  47. package/lib/pipes/verify-delegation.cjs +123 -48
  48. package/lib/pipes/verify-delegation.d.cts +6 -3
  49. package/lib/pipes/verify-list-size.cjs +1 -1
  50. package/lib/pipes/verify-multisig-v2.cjs +40 -9
  51. package/lib/pipes/verify-multisig.cjs +21 -5
  52. package/lib/pipes/verify-sender.cjs +1 -1
  53. package/lib/pipes/verify-signature.cjs +13 -4
  54. package/lib/pipes/verify-signer.cjs +5 -3
  55. package/lib/pipes/verify-token-access.cjs +32 -3
  56. package/lib/pipes/verify-token-balance.cjs +5 -3
  57. package/lib/pipes/verify-transferrable.cjs +1 -1
  58. package/lib/pipes/verify-tx-input.cjs +4 -4
  59. package/lib/pipes/verify-tx-size.cjs +1 -1
  60. package/lib/pipes/verify-tx.cjs +12 -4
  61. package/lib/pipes/verify-tx.d.cts +1 -1
  62. package/lib/pipes/verify-updater.cjs +1 -1
  63. package/package.json +10 -10
@@ -1,5 +1,5 @@
1
1
  import { PipeFunction } from "../runner.mjs";
2
- import { IDecodedContext } from "@ocap/types";
2
+ import { IAccountState, IDecodedContext, IMultiSigData } from "@ocap/types";
3
3
 
4
4
  //#region src/pipes/verify-delegation.d.ts
5
5
  interface TokenLimit {
@@ -41,13 +41,16 @@ declare const isDelegationSufficient: (requirements: Requirement[], limitation:
41
41
  sufficient: boolean;
42
42
  reason?: string;
43
43
  };
44
+ declare const verifyImplicitAssetOwnership: (signerAddress: string, delegatorState: IAccountState | {
45
+ address: string;
46
+ } | null | undefined, context: IDecodedContext, delegatorAddress?: string) => Promise<boolean>;
44
47
  interface VerifyDelegationOptions {
45
48
  type?: 'signature' | 'multisig';
46
49
  delegationKey?: string;
47
50
  requirementsKey?: string;
48
51
  signerKey?: string;
49
52
  delegatorKey?: string;
50
- getRequirements?: (context: IDecodedContext) => Requirement[];
53
+ getRequirements?: (context: IDecodedContext, index?: number, signature?: IMultiSigData) => Requirement[];
51
54
  }
52
55
  declare function CreateVerifyDelegationPipe({
53
56
  type,
@@ -66,4 +69,4 @@ declare namespace CreateVerifyDelegationPipe {
66
69
  };
67
70
  }
68
71
  //#endregion
69
- export { CreateVerifyDelegationPipe as default, isDelegationSufficient };
72
+ export { CreateVerifyDelegationPipe as default, isDelegationSufficient, verifyImplicitAssetOwnership };
@@ -1,8 +1,10 @@
1
+ import get from "lodash/get.js";
1
2
  import { isSameDid, scopeMatch, scopeMatchAny, toBN } from "@ocap/util";
2
3
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
- import set from "lodash/set.js";
4
+ import { types } from "@ocap/mcrypto";
5
5
  import { getListField } from "@ocap/util/lib/get-list-field";
6
+ import set from "lodash/set.js";
7
+ import { toTypeInfo } from "@arcblock/did";
6
8
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
7
9
  import isEmpty from "lodash/isEmpty.js";
8
10
  import { toDelegateAddress } from "@arcblock/did-util";
@@ -12,6 +14,8 @@ const ZERO = toBN(0);
12
14
  const isDelegationSufficient = (requirements, limitation) => {
13
15
  if (!limitation || !limitation.tokens.length && !limitation.assets.length) return { sufficient: true };
14
16
  const now = Math.floor(Date.now() / 1e3);
17
+ const countedLimits = /* @__PURE__ */ new Set();
18
+ const txSpentByLimit = /* @__PURE__ */ new Map();
15
19
  for (const requirement of requirements) {
16
20
  if (requirement.type === "token") {
17
21
  const limit = limitation.tokens.find((token) => isSameDid(token.address, requirement.address));
@@ -22,25 +26,30 @@ const isDelegationSufficient = (requirements, limitation) => {
22
26
  sufficient: false,
23
27
  reason: "token receiver is not allowed"
24
28
  };
25
- if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
26
- sufficient: false,
27
- reason: "tx count exceeds threshold"
28
- };
29
- if (limit.validUntil > 0 && limit.validUntil < now) return {
30
- sufficient: false,
31
- reason: "delegation expired"
32
- };
33
- if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
34
- const { interval } = limit.rate;
35
- const { lastTx = 0 } = limit;
36
- if (lastTx + interval > now) return {
29
+ const isFirstMatchInTx = !countedLimits.has(limit);
30
+ if (isFirstMatchInTx) {
31
+ if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
32
+ sufficient: false,
33
+ reason: "tx count exceeds threshold"
34
+ };
35
+ if (limit.validUntil > 0 && limit.validUntil < now) return {
37
36
  sufficient: false,
38
- reason: "delegation rate limit exceeded"
37
+ reason: "delegation expired"
39
38
  };
39
+ if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
40
+ const { interval } = limit.rate;
41
+ const { lastTx = 0 } = limit;
42
+ if (lastTx + interval > now) return {
43
+ sufficient: false,
44
+ reason: "delegation rate limit exceeded"
45
+ };
46
+ }
40
47
  }
41
48
  const requirementValue = toBN(requirement.value || "0");
49
+ const currentTxSpent = (txSpentByLimit.get(limit) || ZERO).add(requirementValue);
50
+ txSpentByLimit.set(limit, currentTxSpent);
42
51
  const txAllowance = toBN(limit.txAllowance || "0");
43
- if (txAllowance.gt(ZERO) && requirementValue.gt(txAllowance)) return {
52
+ if (txAllowance.gt(ZERO) && currentTxSpent.gt(txAllowance)) return {
44
53
  sufficient: false,
45
54
  reason: "token amount exceeds tx allowance"
46
55
  };
@@ -50,9 +59,12 @@ const isDelegationSufficient = (requirements, limitation) => {
50
59
  sufficient: false,
51
60
  reason: "token amount exceeds total allowance"
52
61
  };
53
- limit.txSent = (limit.txSent || 0) + 1;
62
+ if (isFirstMatchInTx) {
63
+ countedLimits.add(limit);
64
+ limit.txSent = (limit.txSent || 0) + 1;
65
+ limit.lastTx = now;
66
+ }
54
67
  limit.spentAllowance = spentAllowance.add(requirementValue).toString();
55
- limit.lastTx = now;
56
68
  continue;
57
69
  }
58
70
  return {
@@ -69,24 +81,27 @@ const isDelegationSufficient = (requirements, limitation) => {
69
81
  sufficient: false,
70
82
  reason: "asset receiver is not allowed"
71
83
  };
72
- if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
73
- sufficient: false,
74
- reason: "tx count exceeds threshold"
75
- };
76
- if (limit.validUntil > 0 && limit.validUntil < now) return {
77
- sufficient: false,
78
- reason: "delegation expired"
79
- };
80
- if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
81
- const { interval } = limit.rate;
82
- const { lastTx = 0 } = limit;
83
- if (lastTx + interval > now) return {
84
+ if (!countedLimits.has(limit)) {
85
+ if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
86
+ sufficient: false,
87
+ reason: "tx count exceeds threshold"
88
+ };
89
+ if (limit.validUntil > 0 && limit.validUntil < now) return {
84
90
  sufficient: false,
85
- reason: "delegation rate limit exceeded"
91
+ reason: "delegation expired"
86
92
  };
93
+ if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
94
+ const { interval } = limit.rate;
95
+ const { lastTx = 0 } = limit;
96
+ if (lastTx + interval > now) return {
97
+ sufficient: false,
98
+ reason: "delegation rate limit exceeded"
99
+ };
100
+ }
101
+ countedLimits.add(limit);
102
+ limit.txSent = (limit.txSent || 0) + 1;
103
+ limit.lastTx = now;
87
104
  }
88
- limit.txSent = (limit.txSent || 0) + 1;
89
- limit.lastTx = now;
90
105
  continue;
91
106
  }
92
107
  return {
@@ -101,12 +116,38 @@ const isDelegationSufficient = (requirements, limitation) => {
101
116
  }
102
117
  return { sufficient: true };
103
118
  };
119
+ const verifyImplicitAssetOwnership = async (signerAddress, delegatorState, context, delegatorAddress) => {
120
+ if (!signerAddress || !delegatorState || !context.statedb?.asset?.get) return false;
121
+ if (toTypeInfo(signerAddress).role !== types.RoleType.ROLE_ASSET) return false;
122
+ const targetDelegator = delegatorAddress || delegatorState.address;
123
+ let resolvedDelegatorState = delegatorState;
124
+ if (targetDelegator && !("migratedFrom" in resolvedDelegatorState) && !("migratedTo" in resolvedDelegatorState) && context.statedb?.account?.get) {
125
+ const fetched = await context.statedb.account.get(targetDelegator, context);
126
+ if (fetched) resolvedDelegatorState = fetched;
127
+ }
128
+ if (targetDelegator && resolvedDelegatorState.address && !isSameDid(resolvedDelegatorState.address, targetDelegator) || Array.isArray(resolvedDelegatorState.migratedTo) && resolvedDelegatorState.migratedTo.length > 0) throw new CustomError("ACCOUNT_MIGRATED", `Delegator account ${targetDelegator} is migrated`, { persist: true });
129
+ const delegatorAddresses = getRelatedAddresses(resolvedDelegatorState);
130
+ if (!delegatorAddresses.length && resolvedDelegatorState.address) delegatorAddresses.push(resolvedDelegatorState.address);
131
+ const visited = /* @__PURE__ */ new Set();
132
+ let currentAddress = signerAddress;
133
+ while (currentAddress) {
134
+ if (visited.has(currentAddress)) return false;
135
+ visited.add(currentAddress);
136
+ const assetState = await context.statedb.asset.get(currentAddress, context);
137
+ if (!assetState || !assetState.owner) return false;
138
+ if (assetState.consumedTime) throw new CustomError("ASSET_ALREADY_CONSUMED", `Asset ${currentAddress} is already consumed`, { persist: true });
139
+ if (delegatorAddresses.some((addr) => isSameDid(addr, assetState.owner))) return true;
140
+ if (toTypeInfo(assetState.owner).role === types.RoleType.ROLE_ASSET) {
141
+ currentAddress = assetState.owner;
142
+ continue;
143
+ }
144
+ return false;
145
+ }
146
+ return false;
147
+ };
104
148
  function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "delegationState", requirementsKey = "delegationRequirements", signerKey = "signerState", delegatorKey = "delegatorState", getRequirements }) {
105
149
  return async function VerifyDelegation(context, next) {
106
150
  const { tx, txType, statedb } = context;
107
- let requirements = [];
108
- if (typeof getRequirements === "function") requirements = getRequirements(context) || [];
109
- set(context, requirementsKey, requirements);
110
151
  const getDelegationState = async (signerState, delegatorState) => {
111
152
  if (delegatorState) {
112
153
  const related = getRelatedAddresses(delegatorState);
@@ -118,7 +159,7 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
118
159
  }
119
160
  return null;
120
161
  };
121
- const checkDelegation = (delegationState) => {
162
+ const checkDelegation = (delegationState, requirements) => {
122
163
  const now = Math.floor(Date.now() / 1e3);
123
164
  const validUntil = delegationState.validUntil || 0;
124
165
  if (validUntil > 0 && validUntil < now) return {
@@ -152,11 +193,10 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
152
193
  tokens: [],
153
194
  assets: []
154
195
  };
155
- const limitation = {
196
+ const result = isDelegationSufficient(requirements, {
156
197
  tokens: rawLimit.tokens || [],
157
198
  assets: rawLimit.assets || []
158
- };
159
- const result = isDelegationSufficient(requirements, limitation);
199
+ });
160
200
  if (result.sufficient === false) return {
161
201
  valid: false,
162
202
  code: "INSUFFICIENT_DELEGATION",
@@ -165,9 +205,23 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
165
205
  return { valid: true };
166
206
  };
167
207
  if (type === "signature") {
208
+ const requirements = typeof getRequirements === "function" ? getRequirements(context) || [] : [];
209
+ set(context, requirementsKey, requirements);
168
210
  if (isEmpty(tx?.delegator)) return next();
169
211
  const signerState = get(context, signerKey);
170
212
  const delegatorState = get(context, delegatorKey);
213
+ const signerAddress = signerState?.address || tx?.from;
214
+ if (signerAddress && toTypeInfo(signerAddress).role === types.RoleType.ROLE_ASSET) {
215
+ try {
216
+ if (await verifyImplicitAssetOwnership(signerAddress, delegatorState || (tx?.delegator ? { address: tx.delegator } : null), context, tx?.delegator)) {
217
+ set(context, "isImplicitDelegation", true);
218
+ return next();
219
+ }
220
+ } catch (err) {
221
+ return next(err);
222
+ }
223
+ return next(new CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || tx?.delegator} is not the owner of asset ${signerAddress}`, { persist: true }));
224
+ }
171
225
  const delegationState = await getDelegationState(signerState, delegatorState ?? null);
172
226
  if (!delegationState) {
173
227
  console.error("invalid_delegation", {
@@ -176,22 +230,40 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
176
230
  });
177
231
  return next(new CustomError("INVALID_DELEGATION", "No delegation found between sender and delegator", { persist: true }));
178
232
  }
179
- const result = checkDelegation(delegationState);
233
+ const result = checkDelegation(delegationState, requirements);
180
234
  if (result.code) return next(new CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: true }));
181
235
  set(context, delegationKey, delegationState);
182
236
  set(context, "isDelegationChanged", true);
183
237
  return next();
184
238
  }
185
239
  if (type === "multisig") {
186
- const delegated = getListField(tx, "signatures").filter((x) => x.delegator);
187
- if (!delegated.length) return next();
240
+ const signatures = getListField(tx, "signatures");
241
+ if (!signatures.some((x) => x.delegator)) {
242
+ set(context, requirementsKey, []);
243
+ return next();
244
+ }
188
245
  const signerStates = get(context, signerKey);
189
246
  const delegatorStates = get(context, delegatorKey);
190
247
  const delegationStates = [];
191
- for (const signature of delegated) {
248
+ const allRequirements = [];
249
+ for (let index = 0; index < signatures.length; index++) {
250
+ const signature = signatures[index];
251
+ if (!signature.delegator) continue;
192
252
  const { signer, delegator } = signature;
253
+ const sigRequirements = typeof getRequirements === "function" ? getRequirements(context, index, signature) || [] : [];
254
+ allRequirements.push(...sigRequirements);
193
255
  const signerState = signerStates?.find((x) => signer && isSameDid(x.address, signer));
194
- const delegatorState = delegatorStates?.find((x) => delegator && isSameDid(x.address, delegator));
256
+ const delegatorState = delegatorStates?.find((x) => delegator && getRelatedAddresses(x).some((addr) => isSameDid(addr, delegator)));
257
+ if (delegatorState && (delegator && !isSameDid(delegatorState.address, delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegator} is migrated`, { persist: true }));
258
+ const signerAddress = signerState?.address || signer;
259
+ if (signerAddress && toTypeInfo(signerAddress).role === types.RoleType.ROLE_ASSET) {
260
+ try {
261
+ if (await verifyImplicitAssetOwnership(signerAddress, delegatorState || (delegator ? { address: delegator } : null), context, delegator)) continue;
262
+ } catch (err) {
263
+ return next(err);
264
+ }
265
+ return next(new CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || delegator} is not the owner of asset ${signerAddress}`, { persist: true }));
266
+ }
195
267
  const delegationState = await getDelegationState(signerState, delegatorState ?? null);
196
268
  if (!delegationState) {
197
269
  console.error("invalid_delegation", {
@@ -200,11 +272,13 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
200
272
  });
201
273
  return next(new CustomError("INVALID_DELEGATION", "No delegation found between signer and delegator", { persist: true }));
202
274
  }
203
- const result = checkDelegation(delegationState);
275
+ const result = checkDelegation(delegationState, sigRequirements);
204
276
  if (result.code) return next(new CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: true }));
205
277
  delegationStates.push(delegationState);
206
278
  }
279
+ set(context, requirementsKey, allRequirements);
207
280
  set(context, delegationKey, delegationStates);
281
+ if (delegationStates.length > 0) set(context, "isDelegationChanged", true);
208
282
  return next();
209
283
  }
210
284
  next();
@@ -213,4 +287,4 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
213
287
  CreateVerifyDelegationPipe.isDelegationSufficient = isDelegationSufficient;
214
288
 
215
289
  //#endregion
216
- export { CreateVerifyDelegationPipe as default, isDelegationSufficient };
290
+ export { CreateVerifyDelegationPipe as default, isDelegationSufficient, verifyImplicitAssetOwnership };
@@ -1,5 +1,5 @@
1
- import { CustomError } from "@ocap/util/lib/error";
2
1
  import get from "lodash/get.js";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
3
 
4
4
  //#region src/pipes/verify-list-size.ts
5
5
  function CreateVerifyListSizePipe({ listKey }) {
@@ -1,38 +1,68 @@
1
- import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
1
+ import { isCanonicalPasskeyExtra, isDedupHeightActive } from "../helpers/dedup-height.mjs";
2
+ import { name } from "../package.mjs";
2
3
  import { unwrapOpaqueAnyData } from "../helpers/unwrap-opaque-any.mjs";
3
- import { CustomError } from "@ocap/util/lib/error";
4
+ import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
4
5
  import get from "lodash/get.js";
6
+ import { CustomError } from "@ocap/util/lib/error";
5
7
  import { decodeAny } from "@ocap/message";
8
+ import { types } from "@ocap/mcrypto";
6
9
  import { getListField, setListField } from "@ocap/util/lib/get-list-field";
7
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
8
10
  import cloneDeep from "lodash/cloneDeep.js";
9
- import { fromPublicKey } from "@ocap/wallet";
10
11
  import omit from "lodash/omit.js";
12
+ import Debug from "debug";
13
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
14
+ import { fromPublicKey } from "@ocap/wallet";
11
15
 
12
16
  //#region src/pipes/verify-multisig-v2.ts
17
+ const debug = Debug(`${name}:pipe:verify-multisig-v2`);
13
18
  function CreateVerifyMultiSigV2Pipe({ signersKey }) {
14
19
  return async function VerifyMultiSigV2(context, next) {
15
20
  const signers = get(context, signersKey);
16
21
  if (!signers || signers.length === 0) return next();
22
+ if (new Set(signers).size !== signers.length) return next(new CustomError("INVALID_SIGNATURE", `Duplicate signers found in ${signersKey}`));
17
23
  const tx = cloneDeep(context.tx);
18
24
  const signatures = getListField(tx, "signatures");
19
25
  if (signatures.length !== signers.length) return next(new CustomError("INVALID_SIGNATURE", `Expect ${signers.length} signatures but found ${signatures.length}`));
20
- for (const signer of signers) if (!signatures.find((x) => [x.delegator, x.signer].includes(signer))) return next(new CustomError("INVALID_SIGNATURE", `Signature for ${signer} not found in tx.signatures`));
26
+ const sigToSigner = new Array(signatures.length).fill(-1);
27
+ const tryMatch = (signerIdx, visited) => {
28
+ const target = signers[signerIdx];
29
+ const candidateIndices = [];
30
+ for (let idx = 0; idx < signatures.length; idx++) if (signatures[idx].signer === target) candidateIndices.push(idx);
31
+ for (let idx = 0; idx < signatures.length; idx++) if (signatures[idx].signer !== target && signatures[idx].delegator === target) candidateIndices.push(idx);
32
+ for (const sigIdx of candidateIndices) {
33
+ if (visited.has(sigIdx)) continue;
34
+ visited.add(sigIdx);
35
+ if (sigToSigner[sigIdx] === -1 || tryMatch(sigToSigner[sigIdx], visited)) {
36
+ sigToSigner[sigIdx] = signerIdx;
37
+ return true;
38
+ }
39
+ }
40
+ return false;
41
+ };
42
+ for (let i = 0; i < signers.length; i++) if (!tryMatch(i, /* @__PURE__ */ new Set())) return next(new CustomError("INVALID_SIGNATURE", `Signature for ${signers[i]} not found in tx.signatures`));
21
43
  signatures.forEach((sig) => {
22
44
  sig.data = unwrapOpaqueAnyData(sig.data ? decodeAny(sig.data) : void 0);
23
45
  });
24
46
  tx.signature = void 0;
25
- setListField(tx, "signatures", signatures.map((x) => omit(x, "signature")));
47
+ setListField(tx, "signatures", signatures.map((x) => omit(x, ["signature", "extra"])));
48
+ let txBytes;
26
49
  for (let i = 0; i < signatures.length; i++) {
27
50
  const { signer, pk, delegator, signature, extra = "" } = signatures[i];
51
+ if (toTypeInfo(signer).role === types.RoleType.ROLE_ASSET && !delegator) return next(new CustomError("INVALID_SIGNATURE", `Asset signer ${signer} requires a delegator`));
52
+ if (delegator && toTypeInfo(delegator).role === types.RoleType.ROLE_ASSET) return next(new CustomError("INVALID_SIGNATURE", `Asset ${delegator} cannot act as a delegator signer`));
28
53
  const address = delegator || signer;
29
54
  if (isFromPublicKey(address, pk) === false) return next(new CustomError("INVALID_SIGNATURE", `signer ${address} and pk do not match`));
30
- const wallet = fromPublicKey(pk, toTypeInfo(address));
31
- const txBytes = encodeTxByEncoding(context.txEncoding, tx);
55
+ const type = toTypeInfo(address);
56
+ const isPasskey = type.role === types.RoleType.ROLE_PASSKEY || type.pk === types.KeyType.PASSKEY;
57
+ const dedupActive = await isDedupHeightActive(context);
58
+ if (!isPasskey && extra && dedupActive) return next(new CustomError("INVALID_SIGNATURE", `Unexpected extra data for non-passkey signer ${address}`));
59
+ if (isPasskey && extra && dedupActive && !isCanonicalPasskeyExtra(extra)) return next(new CustomError("INVALID_SIGNATURE", `Non-canonical extra data for passkey signer ${address}`));
60
+ const wallet = fromPublicKey(pk, type);
61
+ txBytes ??= encodeTxByEncoding(context.txEncoding, tx);
32
62
  try {
33
63
  if (await wallet.verify(txBytes, signature, true, extra) === false) return next(new CustomError("INVALID_SIGNATURE", `Signature for ${address} is not valid`));
34
64
  } catch (err) {
35
- console.error(err);
65
+ debug("verify failed", err);
36
66
  return next(new CustomError("INVALID_SIGNATURE", `Signature for ${address} verify failed: ${err.message}`));
37
67
  }
38
68
  }
@@ -1,10 +1,13 @@
1
- import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
1
+ import { isCanonicalPasskeyExtra, isDedupHeightActive } from "../helpers/dedup-height.mjs";
2
2
  import { unwrapOpaqueAnyData } from "../helpers/unwrap-opaque-any.mjs";
3
+ import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
4
+ import get from "lodash/get.js";
3
5
  import { CustomError } from "@ocap/util/lib/error";
4
6
  import { decodeAny } from "@ocap/message";
7
+ import { types } from "@ocap/mcrypto";
5
8
  import { deleteListField, getListField, setListField } from "@ocap/util/lib/get-list-field";
6
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
7
9
  import cloneDeep from "lodash/cloneDeep.js";
10
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
8
11
  import { fromPublicKey } from "@ocap/wallet";
9
12
 
10
13
  //#region src/pipes/verify-multisig.ts
@@ -16,10 +19,18 @@ function CreateVerifyMultiSigPipe(numSigs = 0) {
16
19
  if (numSigs === 0) return next();
17
20
  deleteListField(tx, "signatures");
18
21
  while (signatures.length > 0) {
19
- const { signer, pk, delegator, signature, data } = signatures.shift();
22
+ const { signer, pk, delegator, signature, data, extra: sigExtra } = signatures.shift();
23
+ if (toTypeInfo(signer).role === types.RoleType.ROLE_ASSET && !delegator) return next(new CustomError("INVALID_SIGNATURE", `Asset signer ${signer} requires a delegator`));
24
+ if (delegator && toTypeInfo(delegator).role === types.RoleType.ROLE_ASSET) return next(new CustomError("INVALID_SIGNATURE", `Asset ${delegator} cannot act as a delegator signer`));
20
25
  const address = delegator || signer;
21
26
  if (isFromPublicKey(address, pk) === false) return next(new CustomError("INVALID_SIGNATURE", `signer ${address} and pk do not match`));
22
- const wallet = fromPublicKey(pk, toTypeInfo(address));
27
+ const type = toTypeInfo(address);
28
+ const isPasskey = type.role === types.RoleType.ROLE_PASSKEY || type.pk === types.KeyType.PASSKEY;
29
+ const dedupActive = await isDedupHeightActive(context);
30
+ if (!isPasskey && sigExtra && dedupActive) return next(new CustomError("INVALID_SIGNATURE", `Unexpected extra data for non-passkey signer ${address}`));
31
+ if (isPasskey && sigExtra && dedupActive && !isCanonicalPasskeyExtra(sigExtra)) return next(new CustomError("INVALID_SIGNATURE", `Non-canonical extra data for passkey signer ${address}`));
32
+ const wallet = fromPublicKey(pk, type);
33
+ const extra = sigExtra || (isPasskey ? get(context, "extra.txExtra") || "" : "");
23
34
  setListField(tx, "signatures", [{
24
35
  signer,
25
36
  pk,
@@ -27,7 +38,11 @@ function CreateVerifyMultiSigPipe(numSigs = 0) {
27
38
  data: unwrapOpaqueAnyData(data ? decodeAny(data) : void 0)
28
39
  }].concat(signatures));
29
40
  const txBytes = encodeTxByEncoding(context.txEncoding, tx);
30
- if (await wallet.verify(txBytes, signature) === false) return next(new CustomError("INVALID_SIGNATURE", `Multi signature for ${address} is not valid`));
41
+ try {
42
+ if (await wallet.verify(txBytes, signature, true, extra) === false) return next(new CustomError("INVALID_SIGNATURE", `Multi signature for ${address} is not valid`));
43
+ } catch (err) {
44
+ return next(new CustomError("INVALID_SIGNATURE", `Multi signature for ${address} verify failed: ${err.message}`));
45
+ }
31
46
  }
32
47
  next();
33
48
  };
@@ -1,5 +1,5 @@
1
- import { CustomError } from "@ocap/util/lib/error";
2
1
  import get from "lodash/get.js";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
3
 
4
4
  //#region src/pipes/verify-sender.ts
5
5
  function CreateVerifySenderPipe({ state = "senderState" } = {}) {
@@ -1,27 +1,36 @@
1
+ import { isDedupHeightActive } from "../helpers/dedup-height.mjs";
1
2
  import { encodeTxByEncoding } from "../helpers/encode-tx-by-context.mjs";
2
- import { CustomError } from "@ocap/util/lib/error";
3
3
  import get from "lodash/get.js";
4
+ import { CustomError } from "@ocap/util/lib/error";
4
5
  import { types } from "@ocap/mcrypto";
5
- import { deleteListField } from "@ocap/util/lib/get-list-field";
6
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
6
+ import { deleteListField, getListField } from "@ocap/util/lib/get-list-field";
7
7
  import cloneDeep from "lodash/cloneDeep.js";
8
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
8
9
  import { fromPublicKey } from "@ocap/wallet";
9
10
 
10
11
  //#region src/pipes/verify-signature.ts
12
+ const V1_MULTISIG_TX_TYPES = new Set(["fg:t:exchange", "fg:t:exchange_v2"]);
11
13
  async function VerifySignature(context, next) {
12
14
  const tx = cloneDeep(context.tx);
13
15
  const { signature } = tx;
14
16
  tx.signature = void 0;
15
17
  const multiSignV2Txs = get(context, "config.transaction.multiSignV2Txs", []);
16
18
  const txType = context.txType;
17
- if (!txType || multiSignV2Txs.includes(txType) === false) deleteListField(tx, "signatures");
19
+ if (!txType || multiSignV2Txs.includes(txType) === false) {
20
+ const sigs = getListField(tx, "signatures");
21
+ if (txType && sigs.length > 0 && await isDedupHeightActive(context)) {
22
+ if (!V1_MULTISIG_TX_TYPES.has(txType)) return next(new CustomError("INVALID_SIGNATURE", `Expect 0 multi signatures but found ${sigs.length}`));
23
+ if (sigs.length > 1) return next(new CustomError("INVALID_SIGNATURE", `Expect 1 multi signatures but found ${sigs.length}`));
24
+ }
25
+ deleteListField(tx, "signatures");
26
+ }
18
27
  const { pk, delegator, from } = tx;
19
28
  const signer = delegator || from;
20
29
  if (isFromPublicKey(signer, pk) === false) return next(new CustomError("INVALID_SIGNATURE", "signer and pk does not match"));
21
30
  const txBytes = encodeTxByEncoding(context.txEncoding, tx);
22
31
  const type = toTypeInfo(signer);
23
32
  const wallet = fromPublicKey(pk, type);
24
- const extra = type.role === types.RoleType.ROLE_PASSKEY ? get(context, "extra.txExtra") : "";
33
+ const extra = type.role === types.RoleType.ROLE_PASSKEY || type.pk === types.KeyType.PASSKEY ? get(context, "extra.txExtra") : "";
25
34
  try {
26
35
  if (!signature || await wallet.verify(txBytes, signature, true, extra || "") === false) return next(new CustomError("INVALID_SIGNATURE", "tx.signature is invalid"));
27
36
  } catch (err) {
@@ -1,8 +1,10 @@
1
1
  import { name } from "../package.mjs";
2
- import { CustomError } from "@ocap/util/lib/error";
3
2
  import get from "lodash/get.js";
4
- import Debug from "debug";
3
+ import { CustomError } from "@ocap/util/lib/error";
4
+ import { types } from "@ocap/mcrypto";
5
5
  import { getListField } from "@ocap/util/lib/get-list-field";
6
+ import Debug from "debug";
7
+ import { toTypeInfo } from "@arcblock/did";
6
8
 
7
9
  //#region src/pipes/verify-signer.ts
8
10
  const debug = Debug(`${name}:pipe:verify-signer`);
@@ -13,7 +15,7 @@ function CreateVerifySignerPipe({ signer }) {
13
15
  const signatures = getListField(context, "tx.signatures");
14
16
  if (signatures.length === 0) return next(new CustomError("INVALID_TX", "Multisig can not be empty"));
15
17
  const [{ signer: signerDid, delegator }] = signatures;
16
- const actual = delegator || signerDid;
18
+ const actual = toTypeInfo(expected).role === types.RoleType.ROLE_ASSET ? signerDid : delegator || signerDid;
17
19
  debug("verify", {
18
20
  expected,
19
21
  actual
@@ -1,6 +1,7 @@
1
+ import get from "lodash/get.js";
1
2
  import { toAddress } from "@ocap/util";
2
3
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
+ import { getListField } from "@ocap/util/lib/get-list-field";
4
5
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
5
6
  import isEmpty from "lodash/isEmpty.js";
6
7
 
@@ -34,8 +35,36 @@ function CreateVerifyTokenAccessPipe({ statesKey = "tokenStates", listFieldKey =
34
35
  const list = state[listFieldKey];
35
36
  if (!list) continue;
36
37
  const listSet = new Set(list.map((addr) => toAddress(addr).toLowerCase()));
38
+ const rawInputs = context.inputs;
39
+ if (listFieldKey === "spenders" && Array.isArray(rawInputs) && rawInputs.length > 0) {
40
+ const senderAcct = context.senderState || get(context, "tx.from");
41
+ const senderRelated = senderAcct ? getCachedAddresses(senderAcct) : [];
42
+ if (state.type === "CreditToken" && Boolean(state.issuer) && senderRelated.some((addr) => toAddress(addr).toLowerCase() === toAddress(state.issuer).toLowerCase()) && senderAcct) {
43
+ if (!senderRelated.some((addr) => listSet.has(toAddress(addr).toLowerCase()))) {
44
+ const displayAddress = typeof senderAcct === "string" ? senderAcct : senderAcct.address;
45
+ return next(new CustomError("FORBIDDEN", `verify-token-access: ${defaultErrorMessage.replace("{address}", displayAddress).replace("{tokenAddress}", state.address)}`, { persist: true }));
46
+ }
47
+ continue;
48
+ }
49
+ const signerStates = Array.isArray(context.signerStates) ? context.signerStates : [];
50
+ const matchingOwners = [];
51
+ for (const input of rawInputs) {
52
+ if (!input || !input.owner) continue;
53
+ if ((getListField(input, "tokens") || []).some((t) => t && t.address === state.address)) {
54
+ const ownerState = signerStates.find((s) => s && s.address === input.owner);
55
+ matchingOwners.push(ownerState || input.owner);
56
+ }
57
+ }
58
+ if (matchingOwners.length > 0) {
59
+ for (const acct of matchingOwners) if (!getCachedAddresses(acct).some((addr) => listSet.has(toAddress(addr).toLowerCase()))) {
60
+ const displayAddress = typeof acct === "string" ? acct : acct.address;
61
+ return next(new CustomError("FORBIDDEN", `verify-token-access: ${defaultErrorMessage.replace("{address}", displayAddress).replace("{tokenAddress}", state.address)}`, { persist: true }));
62
+ }
63
+ continue;
64
+ }
65
+ }
37
66
  for (const accountKey of accountKeys) {
38
- const accountState = get(context, accountKey);
67
+ const accountState = get(context, accountKey) || (accountKey === "senderState" ? get(context, "tx.from") : void 0);
39
68
  if (!accountState) continue;
40
69
  const accountStates = Array.isArray(accountState) ? accountState : [accountState];
41
70
  for (const acct of accountStates) {
@@ -1,6 +1,6 @@
1
+ import get from "lodash/get.js";
1
2
  import { BN } from "@ocap/util";
2
3
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
4
  import { getListField } from "@ocap/util/lib/get-list-field";
5
5
  import isEmpty from "lodash/isEmpty.js";
6
6
 
@@ -18,12 +18,14 @@ function CreateVerifyTokenBalancePipe({ ownerKey, conditionKey, tokensKey = "tok
18
18
  if (!owner) return next(new CustomError("INVALID_TX", `Token owner ${condition.owner} not found`, { persist: true }));
19
19
  const { tokens: actual } = owner;
20
20
  const requirements = getListField(condition, tokensKey);
21
+ const aggregatedRequirements = /* @__PURE__ */ new Map();
21
22
  for (const requirement of requirements) {
22
23
  const { address, value } = requirement;
23
24
  if (!address || !value) return next(new CustomError("INTERNAL", "Invalid requirement params provided for VerifyTokenBalance pipe", { persist: true }));
24
25
  if (isEmpty(actual)) return next(new CustomError("INSUFFICIENT_FUND", `Account(${owner.address}) does not own any token`, { persist: true }));
25
26
  if (!actual[address]) return next(new CustomError("INSUFFICIENT_FUND", `Account(${owner.address}) does not own token(${address})`, { persist: true }));
26
- const expectedBalance = new BN(value);
27
+ const expectedBalance = (aggregatedRequirements.get(address) || new BN(0)).add(new BN(value));
28
+ aggregatedRequirements.set(address, expectedBalance);
27
29
  const actualBalance = new BN(actual[address]);
28
30
  if (actualBalance.lt(expectedBalance)) return next(new CustomError("INSUFFICIENT_FUND", `Account(${owner.address}) does not have enough token(${address}) to complete the transaction, expected (${expectedBalance}), actual (${actualBalance})`, { persist: true }));
29
31
  }
@@ -1,5 +1,5 @@
1
- import { CustomError } from "@ocap/util/lib/error";
2
1
  import get from "lodash/get.js";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
3
 
4
4
  //#region src/pipes/verify-transferrable.ts
5
5
  function CreateVerifyTransferrablePipe({ assets }) {
@@ -1,6 +1,6 @@
1
+ import get from "lodash/get.js";
1
2
  import { BN } from "@ocap/util";
2
3
  import { CustomError } from "@ocap/util/lib/error";
3
- import get from "lodash/get.js";
4
4
  import { getListField } from "@ocap/util/lib/get-list-field";
5
5
  import isEmpty from "lodash/isEmpty.js";
6
6
  import { createSortedList } from "@ocap/util/lib/create-sorted-list";
@@ -10,8 +10,8 @@ const ZERO = new BN(0);
10
10
  function CreateVerifyTxInputPipe({ fieldKey = "itx.inputs", inputsKey = "inputs", sendersKey = "senders", tokensKey = "tokens", assetsKey = "assets", allowEmpty = false }) {
11
11
  return function VerifyTxInput(context, next) {
12
12
  const inputs = getListField(context, fieldKey);
13
- const getTokens = (x) => x.tokensList || x.tokens || [];
14
- const getAssets = (x) => x.assetsList || x.assets || [];
13
+ const getTokens = (x) => getListField(x, "tokens");
14
+ const getAssets = (x) => getListField(x, "assets");
15
15
  const address = get(context, "config.token.address");
16
16
  inputs.forEach((x) => {
17
17
  getTokens(x).forEach((t) => {
@@ -1,5 +1,5 @@
1
- import { CustomError } from "@ocap/util/lib/error";
2
1
  import get from "lodash/get.js";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
3
  import { toTypeUrl } from "@ocap/message";
4
4
 
5
5
  //#region src/pipes/verify-tx-size.ts
@@ -2,6 +2,6 @@ import { CustomError } from "@ocap/util/lib/error";
2
2
  import { IDecodedContext } from "@ocap/types";
3
3
 
4
4
  //#region src/pipes/verify-tx.d.ts
5
- declare function VerifyTx(context: IDecodedContext, next: (err?: CustomError) => void): void;
5
+ declare function VerifyTx(context: IDecodedContext, next: (err?: CustomError) => void): Promise<void>;
6
6
  //#endregion
7
7
  export { VerifyTx as default };