@ocap/tx-pipeline 1.30.23 → 1.30.25

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,16 +1,40 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
3
  const require_package = require('../package.cjs');
4
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
5
4
  let lodash_get = require("lodash/get");
6
5
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
6
+ let _ocap_util = require("@ocap/util");
7
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
8
+ let _ocap_mcrypto = require("@ocap/mcrypto");
7
9
  let debug = require("debug");
8
10
  debug = require_rolldown_runtime.__toESM(debug);
9
11
  let lodash_set = require("lodash/set");
10
12
  lodash_set = require_rolldown_runtime.__toESM(lodash_set);
13
+ let _arcblock_did = require("@arcblock/did");
11
14
 
12
15
  //#region src/pipes/update-owner.ts
13
16
  const debug$1 = (0, debug.default)(`${require_package.name}:pipe:update-owner`);
17
+ async function verifyAssetHierarchy(assetAddresses, newOwnerAddress, context, pendingOwners, pendingConsumed) {
18
+ if (!newOwnerAddress || !assetAddresses || assetAddresses.length === 0) return null;
19
+ if ((0, _arcblock_did.toTypeInfo)(newOwnerAddress).role !== _ocap_mcrypto.types.RoleType.ROLE_ASSET) return null;
20
+ if (assetAddresses.some((addr) => (0, _ocap_util.isSameDid)(addr, newOwnerAddress))) return new _ocap_util_lib_error.CustomError("INVALID_OWNER", `Asset ${newOwnerAddress} cannot own itself`, { persist: true });
21
+ if (!context.statedb?.asset?.get) return new _ocap_util_lib_error.CustomError("INVALID_OWNER", `Target owner asset ${newOwnerAddress} does not exist`, { persist: true });
22
+ const visited = new Set(assetAddresses);
23
+ let current = newOwnerAddress;
24
+ while (current) {
25
+ if (visited.has(current)) return new _ocap_util_lib_error.CustomError("INVALID_OWNER", `Circular asset ownership detected for ${current}`, { persist: true });
26
+ visited.add(current);
27
+ const parentAsset = await context.statedb.asset.get(current, context);
28
+ if (!parentAsset) return new _ocap_util_lib_error.CustomError("INVALID_OWNER", `Target owner asset ${current} does not exist`, { persist: true });
29
+ if (parentAsset.consumedTime || pendingConsumed?.some((addr) => (0, _ocap_util.isSameDid)(addr, current))) return new _ocap_util_lib_error.CustomError("INVALID_OWNER", `Target owner asset ${current} is already consumed`, { persist: true });
30
+ const nextOwner = pendingOwners?.[current] ?? parentAsset.owner;
31
+ if (!nextOwner) return new _ocap_util_lib_error.CustomError("INVALID_OWNER", `Target owner asset ${current} has no owner`, { persist: true });
32
+ if (assetAddresses.some((addr) => (0, _ocap_util.isSameDid)(addr, nextOwner)) || visited.has(nextOwner)) return new _ocap_util_lib_error.CustomError("INVALID_OWNER", `Circular asset ownership detected for ${nextOwner}`, { persist: true });
33
+ if ((0, _arcblock_did.toTypeInfo)(nextOwner).role !== _ocap_mcrypto.types.RoleType.ROLE_ASSET) return null;
34
+ current = nextOwner;
35
+ }
36
+ return null;
37
+ }
14
38
  function CreateUpdateOwnerPipe({ assets, owner }) {
15
39
  return async function UpdateOwner(context, next) {
16
40
  const items = (0, lodash_get.default)(context, assets);
@@ -25,6 +49,8 @@ function CreateUpdateOwnerPipe({ assets, owner }) {
25
49
  ownerAddress,
26
50
  items: itemList
27
51
  });
52
+ const hierarchyError = await verifyAssetHierarchy(itemList.map((item) => item.address), ownerAddress, context);
53
+ if (hierarchyError) return next(hierarchyError);
28
54
  try {
29
55
  const updated = await Promise.all(itemList.map(async (item) => {
30
56
  const old = await statedb.asset.get(item.address, context);
@@ -40,4 +66,5 @@ function CreateUpdateOwnerPipe({ assets, owner }) {
40
66
  }
41
67
 
42
68
  //#endregion
43
- exports.default = CreateUpdateOwnerPipe;
69
+ exports.default = CreateUpdateOwnerPipe;
70
+ exports.verifyAssetHierarchy = verifyAssetHierarchy;
@@ -1,7 +1,9 @@
1
1
  import { PipeFunction } from "../runner.cjs";
2
2
  import { IBaseContext } from "@ocap/types";
3
+ import { CustomError } from "@ocap/util/lib/error";
3
4
 
4
5
  //#region src/pipes/update-owner.d.ts
6
+ declare function verifyAssetHierarchy(assetAddresses: string[], newOwnerAddress: string | undefined, context: IBaseContext, pendingOwners?: Record<string, string>, pendingConsumed?: string[]): Promise<CustomError | null>;
5
7
  interface UpdateOwnerOptions {
6
8
  assets: string;
7
9
  owner: string;
@@ -11,4 +13,4 @@ declare function CreateUpdateOwnerPipe({
11
13
  owner
12
14
  }: UpdateOwnerOptions): PipeFunction<IBaseContext>;
13
15
  //#endregion
14
- export { CreateUpdateOwnerPipe as default };
16
+ export { CreateUpdateOwnerPipe as default, verifyAssetHierarchy };
@@ -1,15 +1,15 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
4
3
  let lodash_get = require("lodash/get");
5
4
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
6
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
7
7
 
8
8
  //#region src/pipes/verify-account-migration.ts
9
9
  function CreateVerifyAccountMigrationPipe({ stateKey = "", addressKey = "", signerKey = "" }) {
10
10
  return function VerifyAccountMigration(context, next) {
11
11
  if (stateKey && addressKey) {
12
- const rawAddressList = (0, lodash_get.default)(context, addressKey);
12
+ const rawAddressList = (0, lodash_get.default)(context, addressKey) ?? (addressKey.endsWith("List") ? (0, lodash_get.default)(context, addressKey.slice(0, -4)) : void 0);
13
13
  const rawStateList = (0, lodash_get.default)(context, stateKey);
14
14
  if (rawAddressList && rawStateList) {
15
15
  const stateList = (Array.isArray(rawStateList) ? rawStateList : [rawStateList]).filter(Boolean);
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
4
3
  let lodash_get = require("lodash/get");
5
4
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
6
  let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
7
7
 
8
8
  //#region src/pipes/verify-blocked.ts
@@ -1,12 +1,14 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- let _ocap_util = require("@ocap/util");
4
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
5
3
  let lodash_get = require("lodash/get");
6
4
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
+ let _ocap_util = require("@ocap/util");
6
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
+ let _ocap_mcrypto = require("@ocap/mcrypto");
8
+ let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
7
9
  let lodash_set = require("lodash/set");
8
10
  lodash_set = require_rolldown_runtime.__toESM(lodash_set);
9
- let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
11
+ let _arcblock_did = require("@arcblock/did");
10
12
  let _ocap_util_lib_get_related_addr = require("@ocap/util/lib/get-related-addr");
11
13
  let lodash_isEmpty = require("lodash/isEmpty");
12
14
  lodash_isEmpty = require_rolldown_runtime.__toESM(lodash_isEmpty);
@@ -17,6 +19,8 @@ const ZERO = (0, _ocap_util.toBN)(0);
17
19
  const isDelegationSufficient = (requirements, limitation) => {
18
20
  if (!limitation || !limitation.tokens.length && !limitation.assets.length) return { sufficient: true };
19
21
  const now = Math.floor(Date.now() / 1e3);
22
+ const countedLimits = /* @__PURE__ */ new Set();
23
+ const txSpentByLimit = /* @__PURE__ */ new Map();
20
24
  for (const requirement of requirements) {
21
25
  if (requirement.type === "token") {
22
26
  const limit = limitation.tokens.find((token) => (0, _ocap_util.isSameDid)(token.address, requirement.address));
@@ -27,25 +31,30 @@ const isDelegationSufficient = (requirements, limitation) => {
27
31
  sufficient: false,
28
32
  reason: "token receiver is not allowed"
29
33
  };
30
- if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
31
- sufficient: false,
32
- reason: "tx count exceeds threshold"
33
- };
34
- if (limit.validUntil > 0 && limit.validUntil < now) return {
35
- sufficient: false,
36
- reason: "delegation expired"
37
- };
38
- if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
39
- const { interval } = limit.rate;
40
- const { lastTx = 0 } = limit;
41
- if (lastTx + interval > now) return {
34
+ const isFirstMatchInTx = !countedLimits.has(limit);
35
+ if (isFirstMatchInTx) {
36
+ if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
42
37
  sufficient: false,
43
- reason: "delegation rate limit exceeded"
38
+ reason: "tx count exceeds threshold"
44
39
  };
40
+ if (limit.validUntil > 0 && limit.validUntil < now) return {
41
+ sufficient: false,
42
+ reason: "delegation expired"
43
+ };
44
+ if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
45
+ const { interval } = limit.rate;
46
+ const { lastTx = 0 } = limit;
47
+ if (lastTx + interval > now) return {
48
+ sufficient: false,
49
+ reason: "delegation rate limit exceeded"
50
+ };
51
+ }
45
52
  }
46
53
  const requirementValue = (0, _ocap_util.toBN)(requirement.value || "0");
54
+ const currentTxSpent = (txSpentByLimit.get(limit) || ZERO).add(requirementValue);
55
+ txSpentByLimit.set(limit, currentTxSpent);
47
56
  const txAllowance = (0, _ocap_util.toBN)(limit.txAllowance || "0");
48
- if (txAllowance.gt(ZERO) && requirementValue.gt(txAllowance)) return {
57
+ if (txAllowance.gt(ZERO) && currentTxSpent.gt(txAllowance)) return {
49
58
  sufficient: false,
50
59
  reason: "token amount exceeds tx allowance"
51
60
  };
@@ -55,9 +64,12 @@ const isDelegationSufficient = (requirements, limitation) => {
55
64
  sufficient: false,
56
65
  reason: "token amount exceeds total allowance"
57
66
  };
58
- limit.txSent = (limit.txSent || 0) + 1;
67
+ if (isFirstMatchInTx) {
68
+ countedLimits.add(limit);
69
+ limit.txSent = (limit.txSent || 0) + 1;
70
+ limit.lastTx = now;
71
+ }
59
72
  limit.spentAllowance = spentAllowance.add(requirementValue).toString();
60
- limit.lastTx = now;
61
73
  continue;
62
74
  }
63
75
  return {
@@ -74,24 +86,27 @@ const isDelegationSufficient = (requirements, limitation) => {
74
86
  sufficient: false,
75
87
  reason: "asset receiver is not allowed"
76
88
  };
77
- if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
78
- sufficient: false,
79
- reason: "tx count exceeds threshold"
80
- };
81
- if (limit.validUntil > 0 && limit.validUntil < now) return {
82
- sufficient: false,
83
- reason: "delegation expired"
84
- };
85
- if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
86
- const { interval } = limit.rate;
87
- const { lastTx = 0 } = limit;
88
- if (lastTx + interval > now) return {
89
+ if (!countedLimits.has(limit)) {
90
+ if (limit.txCount > 0 && limit.txSent >= limit.txCount) return {
89
91
  sufficient: false,
90
- reason: "delegation rate limit exceeded"
92
+ reason: "tx count exceeds threshold"
91
93
  };
94
+ if (limit.validUntil > 0 && limit.validUntil < now) return {
95
+ sufficient: false,
96
+ reason: "delegation expired"
97
+ };
98
+ if (limit.rate && limit.lastTx && limit.rate.interval > 0) {
99
+ const { interval } = limit.rate;
100
+ const { lastTx = 0 } = limit;
101
+ if (lastTx + interval > now) return {
102
+ sufficient: false,
103
+ reason: "delegation rate limit exceeded"
104
+ };
105
+ }
106
+ countedLimits.add(limit);
107
+ limit.txSent = (limit.txSent || 0) + 1;
108
+ limit.lastTx = now;
92
109
  }
93
- limit.txSent = (limit.txSent || 0) + 1;
94
- limit.lastTx = now;
95
110
  continue;
96
111
  }
97
112
  return {
@@ -106,12 +121,38 @@ const isDelegationSufficient = (requirements, limitation) => {
106
121
  }
107
122
  return { sufficient: true };
108
123
  };
124
+ const verifyImplicitAssetOwnership = async (signerAddress, delegatorState, context, delegatorAddress) => {
125
+ if (!signerAddress || !delegatorState || !context.statedb?.asset?.get) return false;
126
+ if ((0, _arcblock_did.toTypeInfo)(signerAddress).role !== _ocap_mcrypto.types.RoleType.ROLE_ASSET) return false;
127
+ const targetDelegator = delegatorAddress || delegatorState.address;
128
+ let resolvedDelegatorState = delegatorState;
129
+ if (targetDelegator && !("migratedFrom" in resolvedDelegatorState) && !("migratedTo" in resolvedDelegatorState) && context.statedb?.account?.get) {
130
+ const fetched = await context.statedb.account.get(targetDelegator, context);
131
+ if (fetched) resolvedDelegatorState = fetched;
132
+ }
133
+ if (targetDelegator && resolvedDelegatorState.address && !(0, _ocap_util.isSameDid)(resolvedDelegatorState.address, targetDelegator) || Array.isArray(resolvedDelegatorState.migratedTo) && resolvedDelegatorState.migratedTo.length > 0) throw new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${targetDelegator} is migrated`, { persist: true });
134
+ const delegatorAddresses = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(resolvedDelegatorState);
135
+ if (!delegatorAddresses.length && resolvedDelegatorState.address) delegatorAddresses.push(resolvedDelegatorState.address);
136
+ const visited = /* @__PURE__ */ new Set();
137
+ let currentAddress = signerAddress;
138
+ while (currentAddress) {
139
+ if (visited.has(currentAddress)) return false;
140
+ visited.add(currentAddress);
141
+ const assetState = await context.statedb.asset.get(currentAddress, context);
142
+ if (!assetState || !assetState.owner) return false;
143
+ if (assetState.consumedTime) throw new _ocap_util_lib_error.CustomError("ASSET_ALREADY_CONSUMED", `Asset ${currentAddress} is already consumed`, { persist: true });
144
+ if (delegatorAddresses.some((addr) => (0, _ocap_util.isSameDid)(addr, assetState.owner))) return true;
145
+ if ((0, _arcblock_did.toTypeInfo)(assetState.owner).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
146
+ currentAddress = assetState.owner;
147
+ continue;
148
+ }
149
+ return false;
150
+ }
151
+ return false;
152
+ };
109
153
  function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "delegationState", requirementsKey = "delegationRequirements", signerKey = "signerState", delegatorKey = "delegatorState", getRequirements }) {
110
154
  return async function VerifyDelegation(context, next) {
111
155
  const { tx, txType, statedb } = context;
112
- let requirements = [];
113
- if (typeof getRequirements === "function") requirements = getRequirements(context) || [];
114
- (0, lodash_set.default)(context, requirementsKey, requirements);
115
156
  const getDelegationState = async (signerState, delegatorState) => {
116
157
  if (delegatorState) {
117
158
  const related = (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(delegatorState);
@@ -123,7 +164,7 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
123
164
  }
124
165
  return null;
125
166
  };
126
- const checkDelegation = (delegationState) => {
167
+ const checkDelegation = (delegationState, requirements) => {
127
168
  const now = Math.floor(Date.now() / 1e3);
128
169
  const validUntil = delegationState.validUntil || 0;
129
170
  if (validUntil > 0 && validUntil < now) return {
@@ -157,11 +198,10 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
157
198
  tokens: [],
158
199
  assets: []
159
200
  };
160
- const limitation = {
201
+ const result = isDelegationSufficient(requirements, {
161
202
  tokens: rawLimit.tokens || [],
162
203
  assets: rawLimit.assets || []
163
- };
164
- const result = isDelegationSufficient(requirements, limitation);
204
+ });
165
205
  if (result.sufficient === false) return {
166
206
  valid: false,
167
207
  code: "INSUFFICIENT_DELEGATION",
@@ -170,9 +210,23 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
170
210
  return { valid: true };
171
211
  };
172
212
  if (type === "signature") {
213
+ const requirements = typeof getRequirements === "function" ? getRequirements(context) || [] : [];
214
+ (0, lodash_set.default)(context, requirementsKey, requirements);
173
215
  if ((0, lodash_isEmpty.default)(tx?.delegator)) return next();
174
216
  const signerState = (0, lodash_get.default)(context, signerKey);
175
217
  const delegatorState = (0, lodash_get.default)(context, delegatorKey);
218
+ const signerAddress = signerState?.address || tx?.from;
219
+ if (signerAddress && (0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
220
+ try {
221
+ if (await verifyImplicitAssetOwnership(signerAddress, delegatorState || (tx?.delegator ? { address: tx.delegator } : null), context, tx?.delegator)) {
222
+ (0, lodash_set.default)(context, "isImplicitDelegation", true);
223
+ return next();
224
+ }
225
+ } catch (err) {
226
+ return next(err);
227
+ }
228
+ return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || tx?.delegator} is not the owner of asset ${signerAddress}`, { persist: true }));
229
+ }
176
230
  const delegationState = await getDelegationState(signerState, delegatorState ?? null);
177
231
  if (!delegationState) {
178
232
  console.error("invalid_delegation", {
@@ -181,22 +235,40 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
181
235
  });
182
236
  return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "No delegation found between sender and delegator", { persist: true }));
183
237
  }
184
- const result = checkDelegation(delegationState);
238
+ const result = checkDelegation(delegationState, requirements);
185
239
  if (result.code) return next(new _ocap_util_lib_error.CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: true }));
186
240
  (0, lodash_set.default)(context, delegationKey, delegationState);
187
241
  (0, lodash_set.default)(context, "isDelegationChanged", true);
188
242
  return next();
189
243
  }
190
244
  if (type === "multisig") {
191
- const delegated = (0, _ocap_util_lib_get_list_field.getListField)(tx, "signatures").filter((x) => x.delegator);
192
- if (!delegated.length) return next();
245
+ const signatures = (0, _ocap_util_lib_get_list_field.getListField)(tx, "signatures");
246
+ if (!signatures.some((x) => x.delegator)) {
247
+ (0, lodash_set.default)(context, requirementsKey, []);
248
+ return next();
249
+ }
193
250
  const signerStates = (0, lodash_get.default)(context, signerKey);
194
251
  const delegatorStates = (0, lodash_get.default)(context, delegatorKey);
195
252
  const delegationStates = [];
196
- for (const signature of delegated) {
253
+ const allRequirements = [];
254
+ for (let index = 0; index < signatures.length; index++) {
255
+ const signature = signatures[index];
256
+ if (!signature.delegator) continue;
197
257
  const { signer, delegator } = signature;
258
+ const sigRequirements = typeof getRequirements === "function" ? getRequirements(context, index, signature) || [] : [];
259
+ allRequirements.push(...sigRequirements);
198
260
  const signerState = signerStates?.find((x) => signer && (0, _ocap_util.isSameDid)(x.address, signer));
199
- const delegatorState = delegatorStates?.find((x) => delegator && (0, _ocap_util.isSameDid)(x.address, delegator));
261
+ const delegatorState = delegatorStates?.find((x) => delegator && (0, _ocap_util_lib_get_related_addr.getRelatedAddresses)(x).some((addr) => (0, _ocap_util.isSameDid)(addr, delegator)));
262
+ if (delegatorState && (delegator && !(0, _ocap_util.isSameDid)(delegatorState.address, delegator) || Array.isArray(delegatorState.migratedTo) && delegatorState.migratedTo.length > 0)) return next(new _ocap_util_lib_error.CustomError("ACCOUNT_MIGRATED", `Delegator account ${delegator} is migrated`, { persist: true }));
263
+ const signerAddress = signerState?.address || signer;
264
+ if (signerAddress && (0, _arcblock_did.toTypeInfo)(signerAddress).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) {
265
+ try {
266
+ if (await verifyImplicitAssetOwnership(signerAddress, delegatorState || (delegator ? { address: delegator } : null), context, delegator)) continue;
267
+ } catch (err) {
268
+ return next(err);
269
+ }
270
+ return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", `Account ${delegatorState?.address || delegator} is not the owner of asset ${signerAddress}`, { persist: true }));
271
+ }
200
272
  const delegationState = await getDelegationState(signerState, delegatorState ?? null);
201
273
  if (!delegationState) {
202
274
  console.error("invalid_delegation", {
@@ -205,11 +277,13 @@ function CreateVerifyDelegationPipe({ type = "signature", delegationKey = "deleg
205
277
  });
206
278
  return next(new _ocap_util_lib_error.CustomError("INVALID_DELEGATION", "No delegation found between signer and delegator", { persist: true }));
207
279
  }
208
- const result = checkDelegation(delegationState);
280
+ const result = checkDelegation(delegationState, sigRequirements);
209
281
  if (result.code) return next(new _ocap_util_lib_error.CustomError(result.code, `Delegation check failed: ${result.reason}`, { persist: true }));
210
282
  delegationStates.push(delegationState);
211
283
  }
284
+ (0, lodash_set.default)(context, requirementsKey, allRequirements);
212
285
  (0, lodash_set.default)(context, delegationKey, delegationStates);
286
+ if (delegationStates.length > 0) (0, lodash_set.default)(context, "isDelegationChanged", true);
213
287
  return next();
214
288
  }
215
289
  next();
@@ -219,4 +293,5 @@ CreateVerifyDelegationPipe.isDelegationSufficient = isDelegationSufficient;
219
293
 
220
294
  //#endregion
221
295
  exports.default = CreateVerifyDelegationPipe;
222
- exports.isDelegationSufficient = isDelegationSufficient;
296
+ exports.isDelegationSufficient = isDelegationSufficient;
297
+ exports.verifyImplicitAssetOwnership = verifyImplicitAssetOwnership;
@@ -1,5 +1,5 @@
1
1
  import { PipeFunction } from "../runner.cjs";
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,8 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
4
3
  let lodash_get = require("lodash/get");
5
4
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
6
 
7
7
  //#region src/pipes/verify-list-size.ts
8
8
  function CreateVerifyListSizePipe({ listKey }) {
@@ -1,43 +1,74 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- const require_helpers_encode_tx_by_context = require('../helpers/encode-tx-by-context.cjs');
3
+ const require_helpers_dedup_height = require('../helpers/dedup-height.cjs');
4
+ const require_package = require('../package.cjs');
4
5
  const require_helpers_unwrap_opaque_any = require('../helpers/unwrap-opaque-any.cjs');
5
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
+ const require_helpers_encode_tx_by_context = require('../helpers/encode-tx-by-context.cjs');
6
7
  let lodash_get = require("lodash/get");
7
8
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
9
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
8
10
  let _ocap_message = require("@ocap/message");
11
+ let _ocap_mcrypto = require("@ocap/mcrypto");
9
12
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
10
- let _arcblock_did = require("@arcblock/did");
11
13
  let lodash_cloneDeep = require("lodash/cloneDeep");
12
14
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
13
- let _ocap_wallet = require("@ocap/wallet");
14
15
  let lodash_omit = require("lodash/omit");
15
16
  lodash_omit = require_rolldown_runtime.__toESM(lodash_omit);
17
+ let debug = require("debug");
18
+ debug = require_rolldown_runtime.__toESM(debug);
19
+ let _arcblock_did = require("@arcblock/did");
20
+ let _ocap_wallet = require("@ocap/wallet");
16
21
 
17
22
  //#region src/pipes/verify-multisig-v2.ts
23
+ const debug$1 = (0, debug.default)(`${require_package.name}:pipe:verify-multisig-v2`);
18
24
  function CreateVerifyMultiSigV2Pipe({ signersKey }) {
19
25
  return async function VerifyMultiSigV2(context, next) {
20
26
  const signers = (0, lodash_get.default)(context, signersKey);
21
27
  if (!signers || signers.length === 0) return next();
28
+ if (new Set(signers).size !== signers.length) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Duplicate signers found in ${signersKey}`));
22
29
  const tx = (0, lodash_cloneDeep.default)(context.tx);
23
30
  const signatures = (0, _ocap_util_lib_get_list_field.getListField)(tx, "signatures");
24
31
  if (signatures.length !== signers.length) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Expect ${signers.length} signatures but found ${signatures.length}`));
25
- for (const signer of signers) if (!signatures.find((x) => [x.delegator, x.signer].includes(signer))) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Signature for ${signer} not found in tx.signatures`));
32
+ const sigToSigner = new Array(signatures.length).fill(-1);
33
+ const tryMatch = (signerIdx, visited) => {
34
+ const target = signers[signerIdx];
35
+ const candidateIndices = [];
36
+ for (let idx = 0; idx < signatures.length; idx++) if (signatures[idx].signer === target) candidateIndices.push(idx);
37
+ for (let idx = 0; idx < signatures.length; idx++) if (signatures[idx].signer !== target && signatures[idx].delegator === target) candidateIndices.push(idx);
38
+ for (const sigIdx of candidateIndices) {
39
+ if (visited.has(sigIdx)) continue;
40
+ visited.add(sigIdx);
41
+ if (sigToSigner[sigIdx] === -1 || tryMatch(sigToSigner[sigIdx], visited)) {
42
+ sigToSigner[sigIdx] = signerIdx;
43
+ return true;
44
+ }
45
+ }
46
+ return false;
47
+ };
48
+ for (let i = 0; i < signers.length; i++) if (!tryMatch(i, /* @__PURE__ */ new Set())) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Signature for ${signers[i]} not found in tx.signatures`));
26
49
  signatures.forEach((sig) => {
27
50
  sig.data = require_helpers_unwrap_opaque_any.unwrapOpaqueAnyData(sig.data ? (0, _ocap_message.decodeAny)(sig.data) : void 0);
28
51
  });
29
52
  tx.signature = void 0;
30
- (0, _ocap_util_lib_get_list_field.setListField)(tx, "signatures", signatures.map((x) => (0, lodash_omit.default)(x, "signature")));
53
+ (0, _ocap_util_lib_get_list_field.setListField)(tx, "signatures", signatures.map((x) => (0, lodash_omit.default)(x, ["signature", "extra"])));
54
+ let txBytes;
31
55
  for (let i = 0; i < signatures.length; i++) {
32
56
  const { signer, pk, delegator, signature, extra = "" } = signatures[i];
57
+ if ((0, _arcblock_did.toTypeInfo)(signer).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET && !delegator) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Asset signer ${signer} requires a delegator`));
58
+ if (delegator && (0, _arcblock_did.toTypeInfo)(delegator).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Asset ${delegator} cannot act as a delegator signer`));
33
59
  const address = delegator || signer;
34
60
  if ((0, _arcblock_did.isFromPublicKey)(address, pk) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `signer ${address} and pk do not match`));
35
- const wallet = (0, _ocap_wallet.fromPublicKey)(pk, (0, _arcblock_did.toTypeInfo)(address));
36
- const txBytes = require_helpers_encode_tx_by_context.encodeTxByEncoding(context.txEncoding, tx);
61
+ const type = (0, _arcblock_did.toTypeInfo)(address);
62
+ const isPasskey = type.role === _ocap_mcrypto.types.RoleType.ROLE_PASSKEY || type.pk === _ocap_mcrypto.types.KeyType.PASSKEY;
63
+ const dedupActive = await require_helpers_dedup_height.isDedupHeightActive(context);
64
+ if (!isPasskey && extra && dedupActive) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Unexpected extra data for non-passkey signer ${address}`));
65
+ if (isPasskey && extra && dedupActive && !require_helpers_dedup_height.isCanonicalPasskeyExtra(extra)) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Non-canonical extra data for passkey signer ${address}`));
66
+ const wallet = (0, _ocap_wallet.fromPublicKey)(pk, type);
67
+ txBytes ??= require_helpers_encode_tx_by_context.encodeTxByEncoding(context.txEncoding, tx);
37
68
  try {
38
69
  if (await wallet.verify(txBytes, signature, true, extra) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Signature for ${address} is not valid`));
39
70
  } catch (err) {
40
- console.error(err);
71
+ debug$1("verify failed", err);
41
72
  return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Signature for ${address} verify failed: ${err.message}`));
42
73
  }
43
74
  }
@@ -1,13 +1,17 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- const require_helpers_encode_tx_by_context = require('../helpers/encode-tx-by-context.cjs');
3
+ const require_helpers_dedup_height = require('../helpers/dedup-height.cjs');
4
4
  const require_helpers_unwrap_opaque_any = require('../helpers/unwrap-opaque-any.cjs');
5
+ const require_helpers_encode_tx_by_context = require('../helpers/encode-tx-by-context.cjs');
6
+ let lodash_get = require("lodash/get");
7
+ lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
8
  let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
9
  let _ocap_message = require("@ocap/message");
10
+ let _ocap_mcrypto = require("@ocap/mcrypto");
7
11
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
8
- let _arcblock_did = require("@arcblock/did");
9
12
  let lodash_cloneDeep = require("lodash/cloneDeep");
10
13
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
14
+ let _arcblock_did = require("@arcblock/did");
11
15
  let _ocap_wallet = require("@ocap/wallet");
12
16
 
13
17
  //#region src/pipes/verify-multisig.ts
@@ -19,10 +23,18 @@ function CreateVerifyMultiSigPipe(numSigs = 0) {
19
23
  if (numSigs === 0) return next();
20
24
  (0, _ocap_util_lib_get_list_field.deleteListField)(tx, "signatures");
21
25
  while (signatures.length > 0) {
22
- const { signer, pk, delegator, signature, data } = signatures.shift();
26
+ const { signer, pk, delegator, signature, data, extra: sigExtra } = signatures.shift();
27
+ if ((0, _arcblock_did.toTypeInfo)(signer).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET && !delegator) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Asset signer ${signer} requires a delegator`));
28
+ if (delegator && (0, _arcblock_did.toTypeInfo)(delegator).role === _ocap_mcrypto.types.RoleType.ROLE_ASSET) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Asset ${delegator} cannot act as a delegator signer`));
23
29
  const address = delegator || signer;
24
30
  if ((0, _arcblock_did.isFromPublicKey)(address, pk) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `signer ${address} and pk do not match`));
25
- const wallet = (0, _ocap_wallet.fromPublicKey)(pk, (0, _arcblock_did.toTypeInfo)(address));
31
+ const type = (0, _arcblock_did.toTypeInfo)(address);
32
+ const isPasskey = type.role === _ocap_mcrypto.types.RoleType.ROLE_PASSKEY || type.pk === _ocap_mcrypto.types.KeyType.PASSKEY;
33
+ const dedupActive = await require_helpers_dedup_height.isDedupHeightActive(context);
34
+ if (!isPasskey && sigExtra && dedupActive) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Unexpected extra data for non-passkey signer ${address}`));
35
+ if (isPasskey && sigExtra && dedupActive && !require_helpers_dedup_height.isCanonicalPasskeyExtra(sigExtra)) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Non-canonical extra data for passkey signer ${address}`));
36
+ const wallet = (0, _ocap_wallet.fromPublicKey)(pk, type);
37
+ const extra = sigExtra || (isPasskey ? (0, lodash_get.default)(context, "extra.txExtra") || "" : "");
26
38
  (0, _ocap_util_lib_get_list_field.setListField)(tx, "signatures", [{
27
39
  signer,
28
40
  pk,
@@ -30,7 +42,11 @@ function CreateVerifyMultiSigPipe(numSigs = 0) {
30
42
  data: require_helpers_unwrap_opaque_any.unwrapOpaqueAnyData(data ? (0, _ocap_message.decodeAny)(data) : void 0)
31
43
  }].concat(signatures));
32
44
  const txBytes = require_helpers_encode_tx_by_context.encodeTxByEncoding(context.txEncoding, tx);
33
- if (await wallet.verify(txBytes, signature) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Multi signature for ${address} is not valid`));
45
+ try {
46
+ if (await wallet.verify(txBytes, signature, true, extra) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Multi signature for ${address} is not valid`));
47
+ } catch (err) {
48
+ return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Multi signature for ${address} verify failed: ${err.message}`));
49
+ }
34
50
  }
35
51
  next();
36
52
  };
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
4
3
  let lodash_get = require("lodash/get");
5
4
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
5
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
6
6
 
7
7
  //#region src/pipes/verify-sender.ts
8
8
  function CreateVerifySenderPipe({ state = "senderState" } = {}) {
@@ -1,31 +1,40 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
+ const require_helpers_dedup_height = require('../helpers/dedup-height.cjs');
3
4
  const require_helpers_encode_tx_by_context = require('../helpers/encode-tx-by-context.cjs');
4
- let _ocap_util_lib_error = require("@ocap/util/lib/error");
5
5
  let lodash_get = require("lodash/get");
6
6
  lodash_get = require_rolldown_runtime.__toESM(lodash_get);
7
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
7
8
  let _ocap_mcrypto = require("@ocap/mcrypto");
8
9
  let _ocap_util_lib_get_list_field = require("@ocap/util/lib/get-list-field");
9
- let _arcblock_did = require("@arcblock/did");
10
10
  let lodash_cloneDeep = require("lodash/cloneDeep");
11
11
  lodash_cloneDeep = require_rolldown_runtime.__toESM(lodash_cloneDeep);
12
+ let _arcblock_did = require("@arcblock/did");
12
13
  let _ocap_wallet = require("@ocap/wallet");
13
14
 
14
15
  //#region src/pipes/verify-signature.ts
16
+ const V1_MULTISIG_TX_TYPES = new Set(["fg:t:exchange", "fg:t:exchange_v2"]);
15
17
  async function VerifySignature(context, next) {
16
18
  const tx = (0, lodash_cloneDeep.default)(context.tx);
17
19
  const { signature } = tx;
18
20
  tx.signature = void 0;
19
21
  const multiSignV2Txs = (0, lodash_get.default)(context, "config.transaction.multiSignV2Txs", []);
20
22
  const txType = context.txType;
21
- if (!txType || multiSignV2Txs.includes(txType) === false) (0, _ocap_util_lib_get_list_field.deleteListField)(tx, "signatures");
23
+ if (!txType || multiSignV2Txs.includes(txType) === false) {
24
+ const sigs = (0, _ocap_util_lib_get_list_field.getListField)(tx, "signatures");
25
+ if (txType && sigs.length > 0 && await require_helpers_dedup_height.isDedupHeightActive(context)) {
26
+ if (!V1_MULTISIG_TX_TYPES.has(txType)) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Expect 0 multi signatures but found ${sigs.length}`));
27
+ if (sigs.length > 1) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", `Expect 1 multi signatures but found ${sigs.length}`));
28
+ }
29
+ (0, _ocap_util_lib_get_list_field.deleteListField)(tx, "signatures");
30
+ }
22
31
  const { pk, delegator, from } = tx;
23
32
  const signer = delegator || from;
24
33
  if ((0, _arcblock_did.isFromPublicKey)(signer, pk) === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", "signer and pk does not match"));
25
34
  const txBytes = require_helpers_encode_tx_by_context.encodeTxByEncoding(context.txEncoding, tx);
26
35
  const type = (0, _arcblock_did.toTypeInfo)(signer);
27
36
  const wallet = (0, _ocap_wallet.fromPublicKey)(pk, type);
28
- const extra = type.role === _ocap_mcrypto.types.RoleType.ROLE_PASSKEY ? (0, lodash_get.default)(context, "extra.txExtra") : "";
37
+ const extra = type.role === _ocap_mcrypto.types.RoleType.ROLE_PASSKEY || type.pk === _ocap_mcrypto.types.KeyType.PASSKEY ? (0, lodash_get.default)(context, "extra.txExtra") : "";
29
38
  try {
30
39
  if (!signature || await wallet.verify(txBytes, signature, true, extra || "") === false) return next(new _ocap_util_lib_error.CustomError("INVALID_SIGNATURE", "tx.signature is invalid"));
31
40
  } catch (err) {