@ocap/tx-protocols 1.30.25 → 1.31.0
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.
- package/esm/execute.d.mts +7 -0
- package/esm/execute.mjs +196 -71
- package/esm/gas-security-guard.d.mts +374 -0
- package/esm/gas-security-guard.mjs +1101 -0
- package/esm/index.d.mts +35 -5
- package/esm/index.mjs +3 -1
- package/esm/pipes/ensure-cost.mjs +314 -58
- package/esm/protocols/account/delegate.mjs +64 -16
- package/esm/protocols/account/migrate.d.mts +3 -0
- package/esm/protocols/account/migrate.mjs +235 -35
- package/esm/protocols/account/revoke-delegate.d.mts +3 -3
- package/esm/protocols/account/revoke-delegate.mjs +70 -38
- package/esm/protocols/asset/acquire-v2.mjs +29 -12
- package/esm/protocols/asset/acquire-v3.mjs +78 -22
- package/esm/protocols/asset/calls/transfer-token.mjs +2 -1
- package/esm/protocols/asset/calls/transfer.mjs +1 -0
- package/esm/protocols/asset/consume.mjs +12 -4
- package/esm/protocols/asset/create.mjs +18 -5
- package/esm/protocols/asset/mint.mjs +23 -1
- package/esm/protocols/asset/pipes/exec-mint-hook.d.mts +21 -1
- package/esm/protocols/asset/pipes/exec-mint-hook.mjs +115 -1
- package/esm/protocols/asset/pipes/extract-factory-tokens.mjs +14 -8
- package/esm/protocols/asset/pipes/verify-itx-address.mjs +9 -0
- package/esm/protocols/asset/pipes/verify-itx-assets.mjs +21 -5
- package/esm/protocols/asset/update.d.mts +13 -2
- package/esm/protocols/asset/update.mjs +133 -14
- package/esm/protocols/factory/create.mjs +14 -6
- package/esm/protocols/governance/claim-stake.mjs +92 -10
- package/esm/protocols/governance/return-stake.mjs +44 -12
- package/esm/protocols/governance/revoke-stake.mjs +17 -5
- package/esm/protocols/governance/slash-stake.mjs +64 -25
- package/esm/protocols/governance/stake.mjs +63 -13
- package/esm/protocols/rollup/claim-reward.mjs +39 -20
- package/esm/protocols/rollup/close.mjs +1 -1
- package/esm/protocols/rollup/create-block.mjs +8 -7
- package/esm/protocols/rollup/create.mjs +17 -6
- package/esm/protocols/rollup/join.mjs +3 -3
- package/esm/protocols/rollup/leave.mjs +1 -1
- package/esm/protocols/rollup/migrate.mjs +7 -4
- package/esm/protocols/rollup/pipes/verify-evidence.mjs +12 -4
- package/esm/protocols/rollup/update.mjs +6 -1
- package/esm/protocols/token/create.mjs +23 -12
- package/esm/protocols/token/deposit-v2.d.mts +5 -1
- package/esm/protocols/token/deposit-v2.mjs +81 -29
- package/esm/protocols/token/withdraw-v2.mjs +33 -16
- package/esm/protocols/token-factory/burn.mjs +43 -10
- package/esm/protocols/token-factory/create.mjs +23 -14
- package/esm/protocols/token-factory/mint.mjs +54 -21
- package/esm/protocols/token-factory/pipes/verify-icon.mjs +1 -1
- package/esm/protocols/token-factory/update.mjs +16 -6
- package/esm/protocols/trade/exchange-v2.d.mts +4 -0
- package/esm/protocols/trade/exchange-v2.mjs +78 -22
- package/esm/protocols/trade/transfer-v2.mjs +44 -13
- package/esm/protocols/trade/transfer-v3.mjs +72 -31
- package/esm/util.d.mts +3 -1
- package/esm/util.mjs +26 -17
- package/lib/execute.cjs +193 -67
- package/lib/execute.d.cts +7 -0
- package/lib/gas-security-guard.cjs +1140 -0
- package/lib/gas-security-guard.d.cts +374 -0
- package/lib/index.cjs +122 -1
- package/lib/index.d.cts +36 -6
- package/lib/pipes/ensure-cost.cjs +313 -57
- package/lib/protocols/account/delegate.cjs +64 -16
- package/lib/protocols/account/migrate.cjs +235 -35
- package/lib/protocols/account/migrate.d.cts +3 -0
- package/lib/protocols/account/revoke-delegate.cjs +71 -39
- package/lib/protocols/account/revoke-delegate.d.cts +3 -3
- package/lib/protocols/asset/acquire-v2.cjs +28 -11
- package/lib/protocols/asset/acquire-v3.cjs +77 -20
- package/lib/protocols/asset/calls/transfer-token.cjs +3 -2
- package/lib/protocols/asset/calls/transfer.cjs +1 -0
- package/lib/protocols/asset/consume.cjs +11 -3
- package/lib/protocols/asset/create.cjs +19 -6
- package/lib/protocols/asset/mint.cjs +23 -1
- package/lib/protocols/asset/pipes/exec-mint-hook.cjs +117 -1
- package/lib/protocols/asset/pipes/exec-mint-hook.d.cts +21 -1
- package/lib/protocols/asset/pipes/extract-factory-tokens.cjs +14 -9
- package/lib/protocols/asset/pipes/verify-itx-address.cjs +9 -0
- package/lib/protocols/asset/pipes/verify-itx-assets.cjs +21 -5
- package/lib/protocols/asset/update.cjs +131 -12
- package/lib/protocols/asset/update.d.cts +13 -2
- package/lib/protocols/factory/create.cjs +14 -6
- package/lib/protocols/governance/claim-stake.cjs +92 -9
- package/lib/protocols/governance/claim-stake.d.cts +1 -1
- package/lib/protocols/governance/return-stake.cjs +44 -11
- package/lib/protocols/governance/return-stake.d.cts +1 -1
- package/lib/protocols/governance/revoke-stake.cjs +17 -5
- package/lib/protocols/governance/revoke-stake.d.cts +1 -1
- package/lib/protocols/governance/slash-stake.cjs +64 -24
- package/lib/protocols/governance/slash-stake.d.cts +1 -1
- package/lib/protocols/governance/stake.cjs +65 -14
- package/lib/protocols/rollup/claim-reward.cjs +39 -20
- package/lib/protocols/rollup/close.cjs +1 -1
- package/lib/protocols/rollup/create-block.cjs +9 -8
- package/lib/protocols/rollup/create-block.d.cts +1 -1
- package/lib/protocols/rollup/create.cjs +18 -7
- package/lib/protocols/rollup/join.cjs +3 -3
- package/lib/protocols/rollup/leave.cjs +1 -1
- package/lib/protocols/rollup/migrate.cjs +7 -4
- package/lib/protocols/rollup/pipes/verify-evidence.cjs +11 -3
- package/lib/protocols/rollup/update.cjs +6 -1
- package/lib/protocols/token/create.cjs +24 -13
- package/lib/protocols/token/deposit-v2.cjs +80 -28
- package/lib/protocols/token/deposit-v2.d.cts +5 -1
- package/lib/protocols/token/withdraw-v2.cjs +32 -15
- package/lib/protocols/token-factory/burn.cjs +42 -9
- package/lib/protocols/token-factory/create.cjs +24 -15
- package/lib/protocols/token-factory/mint.cjs +53 -20
- package/lib/protocols/token-factory/pipes/verify-icon.cjs +1 -1
- package/lib/protocols/token-factory/update.cjs +16 -6
- package/lib/protocols/trade/exchange-v2.cjs +76 -20
- package/lib/protocols/trade/exchange-v2.d.cts +4 -0
- package/lib/protocols/trade/transfer-v2.cjs +45 -14
- package/lib/protocols/trade/transfer-v3.cjs +72 -30
- package/lib/util.cjs +26 -17
- package/lib/util.d.cts +4 -2
- package/package.json +16 -16
|
@@ -1,38 +1,54 @@
|
|
|
1
1
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
2
2
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
3
|
+
import { toTypeInfo } from "@arcblock/did";
|
|
4
|
+
import { toDelegateAddress } from "@arcblock/did-util";
|
|
5
|
+
import { types } from "@ocap/mcrypto";
|
|
3
6
|
import { account, delegation } from "@ocap/state";
|
|
4
7
|
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
5
|
-
import { scopeMatchAny } from "@ocap/util";
|
|
8
|
+
import { isSameDid, scopeMatchAny } from "@ocap/util";
|
|
6
9
|
import { CustomError } from "@ocap/util/lib/error";
|
|
10
|
+
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
11
|
+
import cloneDeep from "lodash/cloneDeep.js";
|
|
7
12
|
import get from "lodash/get.js";
|
|
8
13
|
import pick from "lodash/pick.js";
|
|
9
|
-
import { toDelegateAddress } from "@arcblock/did-util";
|
|
10
14
|
import Debug from "debug";
|
|
11
15
|
import { formatMessage } from "@ocap/message";
|
|
12
|
-
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
13
|
-
import cloneDeep from "lodash/cloneDeep.js";
|
|
14
16
|
import { v, vBN, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
15
17
|
|
|
16
18
|
//#region src/protocols/account/delegate.ts
|
|
17
19
|
const debug = Debug("@ocap/tx-protocols:delegate");
|
|
18
20
|
const runner = new Runner("delegate");
|
|
21
|
+
runner.use((context, next) => {
|
|
22
|
+
const signatures = getListField(context.tx, "signatures");
|
|
23
|
+
if (context.tx?.delegator || signatures.some((s) => Boolean(s?.delegator))) return next(new CustomError("INVALID_DELEGATION", "Delegation is not supported for this transaction", { persist: false }));
|
|
24
|
+
return next();
|
|
25
|
+
});
|
|
19
26
|
runner.use(pipes.VerifyMultiSig(0));
|
|
20
27
|
const rateLimit = v.object({
|
|
21
28
|
interval: v.pipe(v.number(), v.integer(), v.minValue(1)),
|
|
22
29
|
anchor: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))), 0)
|
|
23
30
|
});
|
|
24
|
-
const
|
|
31
|
+
const vNonNegativeBN = () => v.pipe(vBN(), v.check((val) => /^\d+$/.test(String(val).trim()), "Allowance must be a non-negative integer string"));
|
|
32
|
+
const tokenLimit = v.pipe(v.object({
|
|
25
33
|
address: vDID({
|
|
26
34
|
prefix: true,
|
|
27
35
|
role: "ROLE_TOKEN"
|
|
28
36
|
}),
|
|
29
37
|
toList: v.optional(v.nullable(v.pipe(v.array(vDID({ prefix: true })), v.maxLength(32))), []),
|
|
30
38
|
txCount: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))), 0),
|
|
31
|
-
txAllowance: v.optional(v.nullable(
|
|
32
|
-
|
|
39
|
+
txAllowance: v.optional(v.nullable(vNonNegativeBN()), "0"),
|
|
40
|
+
maxPerTx: v.optional(v.nullable(vNonNegativeBN())),
|
|
41
|
+
totalAllowance: v.optional(v.nullable(vNonNegativeBN()), "0"),
|
|
33
42
|
validUntil: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))), 0),
|
|
34
|
-
rate: v.optional(v.nullable(rateLimit))
|
|
35
|
-
|
|
43
|
+
rate: v.optional(v.nullable(rateLimit)),
|
|
44
|
+
windowLimit: v.optional(v.nullable(vNonNegativeBN())),
|
|
45
|
+
windowSeconds: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(1)))),
|
|
46
|
+
coSignAllowance: v.optional(v.nullable(vNonNegativeBN())),
|
|
47
|
+
coSignRequired: v.optional(v.nullable(v.boolean())),
|
|
48
|
+
requirePinnedPayee: v.optional(v.nullable(v.boolean())),
|
|
49
|
+
notifyBeforeDebit: v.optional(v.nullable(v.boolean())),
|
|
50
|
+
notifyLeadSeconds: v.optional(v.nullable(v.pipe(v.number(), v.integer(), v.minValue(0))))
|
|
51
|
+
}), v.check((t) => (!t.windowLimit || t.windowLimit === "0" || typeof t.windowSeconds === "number" && t.windowSeconds > 0) && (!t.windowSeconds || Boolean(t.windowLimit) && t.windowLimit !== "0"), "windowLimit and windowSeconds (> 0) must be configured together"), v.check((t) => !t.requirePinnedPayee || Array.isArray(t.toList) && t.toList.length > 0, "requirePinnedPayee requires a non-empty toList"));
|
|
36
52
|
const assetLimit = v.object({
|
|
37
53
|
address: v.optional(v.nullable(v.pipe(v.array(vDID({
|
|
38
54
|
prefix: true,
|
|
@@ -52,8 +68,9 @@ const schema = v.pipe(v.object({
|
|
|
52
68
|
opsList: v.pipe(v.array(v.object({
|
|
53
69
|
typeUrl: v.string(),
|
|
54
70
|
limit: v.optional(v.nullable(v.object({
|
|
55
|
-
tokensList: v.optional(v.pipe(v.array(tokenLimit), v.maxLength(32)), []),
|
|
56
|
-
assetsList: v.optional(v.pipe(v.array(assetLimit), v.maxLength(32)), [])
|
|
71
|
+
tokensList: v.optional(v.pipe(v.array(tokenLimit), v.maxLength(32), v.check((arr) => arr.every((item, idx) => arr.findIndex((other) => isSameDid(other.address, item.address)) === idx), "tokensList must not contain duplicate token addresses")), []),
|
|
72
|
+
assetsList: v.optional(v.pipe(v.array(assetLimit), v.maxLength(32)), []),
|
|
73
|
+
unlimited: v.optional(v.nullable(v.boolean()))
|
|
57
74
|
})), {
|
|
58
75
|
tokensList: [],
|
|
59
76
|
assetsList: []
|
|
@@ -75,6 +92,19 @@ runner.use(pipes.VerifyInfo([{
|
|
|
75
92
|
message: "Delegation address does not match",
|
|
76
93
|
fn: (ctx) => {
|
|
77
94
|
const context = ctx;
|
|
95
|
+
const toInfo = toTypeInfo(context.itx.to);
|
|
96
|
+
if ([
|
|
97
|
+
types.RoleType.ROLE_DELEGATION,
|
|
98
|
+
types.RoleType.ROLE_STAKE,
|
|
99
|
+
types.RoleType.ROLE_TOKEN,
|
|
100
|
+
types.RoleType.ROLE_FACTORY,
|
|
101
|
+
types.RoleType.ROLE_ROLLUP,
|
|
102
|
+
types.RoleType.ROLE_TX,
|
|
103
|
+
types.RoleType.ROLE_TETHER,
|
|
104
|
+
types.RoleType.ROLE_SWAP,
|
|
105
|
+
types.RoleType.ROLE_VC,
|
|
106
|
+
types.RoleType.ROLE_ANY
|
|
107
|
+
].includes(toInfo.role)) return false;
|
|
78
108
|
return toDelegateAddress(context.tx.from, context.itx.to) === context.itx.address;
|
|
79
109
|
}
|
|
80
110
|
}, {
|
|
@@ -140,19 +170,37 @@ runner.use(async (context, next) => {
|
|
|
140
170
|
const merged = cloneDeep(ops).reduce((acc, x, i) => {
|
|
141
171
|
const tokens = x.limit?.tokens || [];
|
|
142
172
|
const assets = x.limit?.assets || [];
|
|
173
|
+
const rawLimitInput = opsList[i]?.limit || {};
|
|
143
174
|
acc[x.typeUrl] = { limit: {
|
|
175
|
+
...rawLimitInput.unlimited === true ? { unlimited: true } : {},
|
|
144
176
|
tokens: tokens.map((y, j) => {
|
|
145
177
|
const input = getListField(opsList[i]?.limit, "tokens")[j] || {};
|
|
146
|
-
|
|
178
|
+
const basePicked = pick(input, [
|
|
147
179
|
"txCount",
|
|
148
180
|
"txAllowance",
|
|
149
181
|
"totalAllowance",
|
|
150
182
|
"validUntil",
|
|
151
183
|
"rate"
|
|
152
|
-
])
|
|
184
|
+
]);
|
|
185
|
+
const extPicked = {};
|
|
186
|
+
for (const extKey of [
|
|
187
|
+
"maxPerTx",
|
|
188
|
+
"windowLimit",
|
|
189
|
+
"windowSeconds",
|
|
190
|
+
"coSignAllowance",
|
|
191
|
+
"coSignRequired",
|
|
192
|
+
"requirePinnedPayee",
|
|
193
|
+
"notifyBeforeDebit",
|
|
194
|
+
"notifyLeadSeconds"
|
|
195
|
+
]) if (input[extKey] !== void 0 && input[extKey] !== null && input[extKey] !== "") extPicked[extKey] = input[extKey];
|
|
196
|
+
return Object.assign(y, basePicked, extPicked, {
|
|
153
197
|
txSent: 0,
|
|
154
198
|
lastTx: y.rate ? y.rate.anchor : 0,
|
|
155
|
-
spentAllowance: "0"
|
|
199
|
+
spentAllowance: "0",
|
|
200
|
+
...extPicked.windowLimit ? {
|
|
201
|
+
windowSpent: "0",
|
|
202
|
+
windowStart: 0
|
|
203
|
+
} : {}
|
|
156
204
|
});
|
|
157
205
|
}),
|
|
158
206
|
assets: assets.map((y, j) => {
|
|
@@ -168,7 +216,7 @@ runner.use(async (context, next) => {
|
|
|
168
216
|
})
|
|
169
217
|
} };
|
|
170
218
|
return acc;
|
|
171
|
-
}, delegationState ? delegationState.ops : {});
|
|
219
|
+
}, delegationState ? cloneDeep(delegationState.ops) : {});
|
|
172
220
|
const sender = senderState ? senderState.address : tx$1.from;
|
|
173
221
|
const receiver = receiverState ? receiverState.address : itx.to;
|
|
174
222
|
const tokenAddress = context.config.token.address;
|
|
@@ -177,7 +225,7 @@ runner.use(async (context, next) => {
|
|
|
177
225
|
...senderUpdates,
|
|
178
226
|
address: sender,
|
|
179
227
|
nonce: tx$1.nonce,
|
|
180
|
-
pk: tx$1.pk
|
|
228
|
+
pk: tx$1.delegator ? senderState?.pk : senderState?.pk || tx$1.pk
|
|
181
229
|
}, context), context),
|
|
182
230
|
receiverState ? Promise.resolve(receiverState) : statedb.account.create(receiver, account.create({
|
|
183
231
|
address: receiver,
|
|
@@ -12,6 +12,9 @@ import { IAccountState, IReadyContext, IWithSender, TAccountMigrateTx } from "@o
|
|
|
12
12
|
type Context = IReadyContext<TAccountMigrateTx> & Partial<IWithSender> & {
|
|
13
13
|
/** Receiver state - created during business logic */
|
|
14
14
|
receiverState?: IAccountState;
|
|
15
|
+
/** Whether receiver key was already cryptographically verified via KERI nextKeyCommitment or dual-signed keyRotationEvent */
|
|
16
|
+
hasVerifiedPreRotationOrEvent?: boolean;
|
|
17
|
+
hasActivePreRotationCommitment?: boolean;
|
|
15
18
|
};
|
|
16
19
|
declare const runner: Runner<Context>;
|
|
17
20
|
//#endregion
|
|
@@ -1,22 +1,50 @@
|
|
|
1
1
|
import { decodeAnySafe } from "../../util.mjs";
|
|
2
2
|
import ensure_cost_default from "../../pipes/ensure-cost.mjs";
|
|
3
3
|
import ensure_gas_default from "../../pipes/ensure-gas.mjs";
|
|
4
|
+
import { MAX_ROTATION_CHAIN_LENGTH, createPreRotationCommitment, extractAccountPreRotationData, fromPublicKey, isSameEntity, isValidPreRotationCommitment, normalizePreRotationCommitment, normalizePublicKeyHex, toTypeInfo, verifyPreRotationCommitment, verifySingleKeyRotationEvent } from "@arcblock/did";
|
|
4
5
|
import { types } from "@ocap/mcrypto";
|
|
5
6
|
import { account } from "@ocap/state";
|
|
6
7
|
import { Runner, pipes } from "@ocap/tx-pipeline";
|
|
8
|
+
import { toBN } from "@ocap/util";
|
|
7
9
|
import { CustomError } from "@ocap/util/lib/error";
|
|
8
|
-
import {
|
|
10
|
+
import { getListField } from "@ocap/util/lib/get-list-field";
|
|
11
|
+
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
9
12
|
import Debug from "debug";
|
|
10
13
|
import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
|
|
11
|
-
import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
|
|
12
14
|
import flatten from "lodash/flatten.js";
|
|
13
15
|
import uniq from "lodash/uniq.js";
|
|
14
16
|
|
|
15
17
|
//#region src/protocols/account/migrate.ts
|
|
16
|
-
const { RoleType } = types;
|
|
17
18
|
const debug = Debug("@ocap/tx-protocols:migrate");
|
|
19
|
+
function decodeAccountData(rawData) {
|
|
20
|
+
if (!rawData || typeof rawData !== "object" || Array.isArray(rawData) || rawData instanceof Uint8Array) return { payload: null };
|
|
21
|
+
const rawObj = rawData;
|
|
22
|
+
if (typeof rawObj.typeUrl === "string" && rawObj.value !== void 0 && (rawObj.value instanceof Uint8Array || typeof rawObj.value === "string" || Buffer.isBuffer(rawObj.value))) {
|
|
23
|
+
const decoded = decodeAnySafe(rawData);
|
|
24
|
+
if (decoded && typeof decoded === "object" && decoded.value && typeof decoded.value === "object" && !Array.isArray(decoded.value) && !(decoded.value instanceof Uint8Array)) return {
|
|
25
|
+
wrapperTypeUrl: typeof decoded.typeUrl === "string" ? decoded.typeUrl : "json",
|
|
26
|
+
payload: decoded.value
|
|
27
|
+
};
|
|
28
|
+
return { payload: null };
|
|
29
|
+
}
|
|
30
|
+
const extracted = extractAccountPreRotationData(rawData);
|
|
31
|
+
if (!extracted) return { payload: null };
|
|
32
|
+
if (typeof rawObj.typeUrl === "string" && rawObj.value && typeof rawObj.value === "object") return {
|
|
33
|
+
wrapperTypeUrl: rawObj.typeUrl,
|
|
34
|
+
payload: extracted
|
|
35
|
+
};
|
|
36
|
+
if (typeof rawObj.type === "string" && rawObj.value && typeof rawObj.value === "object") return {
|
|
37
|
+
wrapperType: rawObj.type,
|
|
38
|
+
payload: extracted
|
|
39
|
+
};
|
|
40
|
+
return { payload: extracted };
|
|
41
|
+
}
|
|
18
42
|
const runner = new Runner("account_migrate");
|
|
19
|
-
|
|
43
|
+
const verifyMultiSigOne = pipes.VerifyMultiSig(1);
|
|
44
|
+
runner.use((context, next) => {
|
|
45
|
+
if (context.tx.delegator) return next(new CustomError("INVALID_DELEGATION", "Account migration cannot be delegated"));
|
|
46
|
+
return next();
|
|
47
|
+
});
|
|
20
48
|
const schema = v.pipe(v.object({
|
|
21
49
|
address: vDID({ prefix: true }),
|
|
22
50
|
pk: v.any(),
|
|
@@ -32,7 +60,10 @@ runner.use(pipes.VerifyInfo([{
|
|
|
32
60
|
message: "Receiver pk and address does not match",
|
|
33
61
|
fn: (ctx) => {
|
|
34
62
|
const context = ctx;
|
|
35
|
-
|
|
63
|
+
if (!context.itx.pk || !context.itx.address) return false;
|
|
64
|
+
const pkHex = normalizePublicKeyHex(context.itx.pk);
|
|
65
|
+
if (!pkHex) return false;
|
|
66
|
+
return isSameEntity(fromPublicKey(typeof context.itx.pk === "string" ? `0x${pkHex}` : context.itx.pk, toTypeInfo(context.itx.address)), context.itx.address) && !isSameEntity(context.itx.address, context.tx.from);
|
|
36
67
|
}
|
|
37
68
|
}]));
|
|
38
69
|
runner.use(pipes.ExtractState({
|
|
@@ -45,37 +76,121 @@ runner.use(pipes.VerifyAccountMigration({
|
|
|
45
76
|
stateKey: "senderState",
|
|
46
77
|
addressKey: "tx.from"
|
|
47
78
|
}));
|
|
48
|
-
runner.use(
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
79
|
+
runner.use(pipes.VerifyBlocked({ stateKeys: [
|
|
80
|
+
"tx.from",
|
|
81
|
+
"senderState",
|
|
82
|
+
"itx.address"
|
|
83
|
+
] }));
|
|
84
|
+
runner.use((context, next) => {
|
|
85
|
+
const sender = context.senderState;
|
|
86
|
+
const senderAddress = sender?.address || context.tx.from;
|
|
87
|
+
const senderDecoded = decodeAccountData(sender?.data);
|
|
88
|
+
const itxDecoded = decodeAccountData(context.itx.data);
|
|
89
|
+
const senderData = senderDecoded.payload;
|
|
90
|
+
const itxData = itxDecoded.payload;
|
|
91
|
+
const hasActiveSenderCommitment = Boolean(senderData && Object.prototype.hasOwnProperty.call(senderData, "nextKeyCommitment") && senderData.nextKeyCommitment !== null && senderData.nextKeyCommitment !== void 0 && senderData.nextKeyCommitment !== "");
|
|
92
|
+
if (hasActiveSenderCommitment) {
|
|
93
|
+
const activeCommitment = senderData.nextKeyCommitment;
|
|
94
|
+
if (!isValidPreRotationCommitment(activeCommitment) || !verifyPreRotationCommitment({
|
|
95
|
+
commitment: activeCommitment,
|
|
96
|
+
publicKey: context.itx.pk,
|
|
97
|
+
address: context.itx.address
|
|
98
|
+
})) return next(new CustomError("INVALID_PRE_ROTATION_KEY", "Receiver public key does not match sender pre-rotation nextKeyCommitment"));
|
|
99
|
+
}
|
|
100
|
+
const hasInlineEvent = Boolean(itxData && Object.prototype.hasOwnProperty.call(itxData, "keyRotationEvent") && itxData.keyRotationEvent !== null && itxData.keyRotationEvent !== void 0);
|
|
101
|
+
let eventNextCommitment;
|
|
102
|
+
if (hasInlineEvent) {
|
|
103
|
+
const genesisDid = sender?.migratedFrom && sender.migratedFrom.length > 0 ? sender.migratedFrom[sender.migratedFrom.length - 1] : senderAddress;
|
|
104
|
+
const expectedSeq = (sender?.migratedFrom?.length ?? 0) + 1;
|
|
105
|
+
const prevLastEvent = senderData?.lastKeyRotationEvent;
|
|
106
|
+
const minRotatedAt = prevLastEvent && typeof prevLastEvent === "object" && typeof prevLastEvent.rotatedAt === "number" ? prevLastEvent.rotatedAt : void 0;
|
|
107
|
+
const evCheck = verifySingleKeyRotationEvent({
|
|
108
|
+
event: itxData.keyRotationEvent,
|
|
109
|
+
senderAddress,
|
|
110
|
+
receiverAddress: context.itx.address,
|
|
111
|
+
receiverPublicKey: context.itx.pk,
|
|
112
|
+
activePreRotationCommitment: hasActiveSenderCommitment && typeof senderData?.nextKeyCommitment === "string" ? senderData.nextKeyCommitment : void 0,
|
|
113
|
+
expectedGenesisDid: genesisDid,
|
|
114
|
+
expectedSeq,
|
|
115
|
+
minRotatedAt
|
|
116
|
+
});
|
|
117
|
+
if (!evCheck.valid) return next(new CustomError("INVALID_PRE_ROTATION_KEY", `Invalid KeyRotationEvent in account migration: ${evCheck.reason}`));
|
|
118
|
+
eventNextCommitment = evCheck.nextKeyCommitment;
|
|
119
|
+
}
|
|
120
|
+
const hasExplicitItxCommitment = Boolean(itxData && Object.prototype.hasOwnProperty.call(itxData, "nextKeyCommitment"));
|
|
121
|
+
if (hasInlineEvent && hasExplicitItxCommitment) {
|
|
122
|
+
const rawExplicit = itxData.nextKeyCommitment;
|
|
123
|
+
const isExplicitEmpty = rawExplicit === null || rawExplicit === void 0 || rawExplicit === "";
|
|
124
|
+
if (eventNextCommitment && isExplicitEmpty) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "itx.data.nextKeyCommitment cannot strip keyRotationEvent.nextKeyCommitment"));
|
|
125
|
+
if (!eventNextCommitment && !isExplicitEmpty) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "itx.data.nextKeyCommitment cannot inject an unsigned commitment absent from keyRotationEvent"));
|
|
57
126
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
127
|
+
const rawIncomingCommitment = hasExplicitItxCommitment ? itxData.nextKeyCommitment : eventNextCommitment;
|
|
128
|
+
if (rawIncomingCommitment !== void 0 && rawIncomingCommitment !== null && rawIncomingCommitment !== "") {
|
|
129
|
+
if (!isValidPreRotationCommitment(rawIncomingCommitment)) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "Invalid nextKeyCommitment format in account migration data"));
|
|
130
|
+
const normalizedIncoming = normalizePreRotationCommitment(rawIncomingCommitment);
|
|
131
|
+
if (hasExplicitItxCommitment && eventNextCommitment && normalizedIncoming !== eventNextCommitment) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "itx.data.nextKeyCommitment conflicts with keyRotationEvent.nextKeyCommitment"));
|
|
132
|
+
const receiverKeyType = toTypeInfo(context.itx.address).pk ?? types.KeyType.ED25519;
|
|
133
|
+
if (normalizedIncoming === normalizePreRotationCommitment(createPreRotationCommitment(context.itx.pk, receiverKeyType))) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "nextKeyCommitment cannot commit to the current receiver key (would deadlock future migration)"));
|
|
134
|
+
const senderPk = sender?.pk || context.tx.pk;
|
|
135
|
+
if (senderPk) {
|
|
136
|
+
if (normalizedIncoming === normalizePreRotationCommitment(createPreRotationCommitment(senderPk, toTypeInfo(senderAddress).pk ?? types.KeyType.ED25519))) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "nextKeyCommitment cannot commit to an already-retired key"));
|
|
137
|
+
}
|
|
138
|
+
if (typeof senderData?.previousKeyCommitment === "string" && isValidPreRotationCommitment(senderData.previousKeyCommitment) && normalizedIncoming === normalizePreRotationCommitment(senderData.previousKeyCommitment)) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "nextKeyCommitment cannot reuse a consumed historical commitment"));
|
|
139
|
+
if (Array.isArray(senderData?.consumedKeyCommitments)) {
|
|
140
|
+
for (const histCommitment of senderData.consumedKeyCommitments) if (isValidPreRotationCommitment(histCommitment) && normalizedIncoming === normalizePreRotationCommitment(histCommitment)) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "nextKeyCommitment cannot reuse a consumed historical commitment"));
|
|
67
141
|
}
|
|
68
142
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
143
|
+
context.hasVerifiedPreRotationOrEvent = Boolean(hasInlineEvent);
|
|
144
|
+
context.hasActivePreRotationCommitment = Boolean(hasActiveSenderCommitment);
|
|
145
|
+
return next();
|
|
146
|
+
});
|
|
147
|
+
const isPassiveUninitializedAccount = (state) => {
|
|
148
|
+
if (!state) return false;
|
|
149
|
+
const hasPk = Boolean(state.pk && String(state.pk).trim() !== "");
|
|
150
|
+
const hasNonce = Boolean(state.nonce && String(state.nonce) !== "0");
|
|
151
|
+
const hasMigratedFrom = Array.isArray(state.migratedFrom) && state.migratedFrom.length > 0;
|
|
152
|
+
const hasMigratedTo = Array.isArray(state.migratedTo) && state.migratedTo.length > 0;
|
|
153
|
+
return !hasPk && !hasNonce && !hasMigratedFrom && !hasMigratedTo;
|
|
154
|
+
};
|
|
155
|
+
runner.use(async (context, next) => {
|
|
156
|
+
const { statedb, itx } = context;
|
|
157
|
+
const existingReceiver = await statedb.account.get(itx.address, {
|
|
158
|
+
traceMigration: false,
|
|
159
|
+
txn: context.txn
|
|
160
|
+
}) || await statedb.account.get(itx.address, context);
|
|
161
|
+
if (existingReceiver) {
|
|
162
|
+
if (context.hasActivePreRotationCommitment && isPassiveUninitializedAccount(existingReceiver)) {
|
|
163
|
+
context.receiverState = existingReceiver;
|
|
164
|
+
return next();
|
|
165
|
+
}
|
|
166
|
+
return next(new CustomError("INVALID_RECEIVER_STATE", "Can not migrate to an existing account"));
|
|
167
|
+
}
|
|
168
|
+
return next();
|
|
169
|
+
});
|
|
170
|
+
runner.use(ensure_gas_default((context) => ({
|
|
171
|
+
create: context.senderState ? 1 : 2,
|
|
172
|
+
update: context.senderState ? getRelatedAddresses(context.senderState).length : 0,
|
|
173
|
+
payment: 0
|
|
174
|
+
})));
|
|
75
175
|
runner.use(ensure_cost_default({
|
|
76
176
|
attachSenderChanges: true,
|
|
77
177
|
throwOnInsufficientFund: false
|
|
78
178
|
}));
|
|
179
|
+
runner.use((context, next) => {
|
|
180
|
+
const signatures = getListField(context.tx, "signatures");
|
|
181
|
+
if (signatures.length === 0) {
|
|
182
|
+
if (context.hasVerifiedPreRotationOrEvent) return next();
|
|
183
|
+
return next(new CustomError("INVALID_SIGNATURE", `Account migration requires receiver ${context.itx.address} multi-signature in tx.signatures`));
|
|
184
|
+
}
|
|
185
|
+
if (signatures.length !== 1) return next(new CustomError("INVALID_SIGNATURE", `Expect 1 multi signature but found ${signatures.length}`));
|
|
186
|
+
const [sig] = signatures;
|
|
187
|
+
if (sig.delegator) return next(new CustomError("INVALID_SIGNATURE", "Receiver signature in account_migrate cannot be delegated"));
|
|
188
|
+
if (!sig.signer || !isSameEntity(sig.signer, context.itx.address)) return next(new CustomError("INVALID_SIGNATURE", `Expect multisig signer to be ${context.itx.address} but got ${sig.signer}`));
|
|
189
|
+
const sigPkHex = normalizePublicKeyHex(sig.pk);
|
|
190
|
+
const receiverPkHex = normalizePublicKeyHex(context.itx.pk);
|
|
191
|
+
if (!sigPkHex || !receiverPkHex || sigPkHex !== receiverPkHex) return next(new CustomError("INVALID_SIGNATURE", "Multisig public key does not match receiver pk"));
|
|
192
|
+
return verifyMultiSigOne(context, next);
|
|
193
|
+
});
|
|
79
194
|
runner.use(pipes.TakeStateSnapshot());
|
|
80
195
|
runner.use(async (context, next) => {
|
|
81
196
|
const { statedb, tx: tx$1, itx, senderUpdates, updateVaults } = context;
|
|
@@ -84,28 +199,113 @@ runner.use(async (context, next) => {
|
|
|
84
199
|
const tokenAddress = context.config.token.address;
|
|
85
200
|
const senderTokens = sender?.tokens || { [tokenAddress]: "0" };
|
|
86
201
|
const senderAddress = sender?.address || tx$1.from;
|
|
87
|
-
if (receiver) return next(new CustomError("INVALID_RECEIVER_STATE", "Can not migrate to an existing account"));
|
|
88
|
-
const
|
|
202
|
+
if (receiver && !(context.hasActivePreRotationCommitment && isPassiveUninitializedAccount(receiver))) return next(new CustomError("INVALID_RECEIVER_STATE", "Can not migrate to an existing account"));
|
|
203
|
+
const senderDecoded = decodeAccountData(sender?.data);
|
|
204
|
+
const itxDecoded = decodeAccountData(itx.data);
|
|
205
|
+
const senderData = senderDecoded.payload;
|
|
206
|
+
const itxData = itxDecoded.payload;
|
|
207
|
+
const hasSenderPreRotation = Boolean(senderData && (Object.prototype.hasOwnProperty.call(senderData, "nextKeyCommitment") || Object.prototype.hasOwnProperty.call(senderData, "previousKeyCommitment") || Object.prototype.hasOwnProperty.call(senderData, "consumedKeyCommitments") || Object.prototype.hasOwnProperty.call(senderData, "preRotationSeq")));
|
|
208
|
+
const hasIncomingPreRotation = Boolean(itxData && (Object.prototype.hasOwnProperty.call(itxData, "nextKeyCommitment") || Object.prototype.hasOwnProperty.call(itxData, "keyRotationEvent")));
|
|
209
|
+
const rawNextCommitment = Boolean(itxData && Object.prototype.hasOwnProperty.call(itxData, "nextKeyCommitment")) ? itxData.nextKeyCommitment : (itxData?.keyRotationEvent)?.nextKeyCommitment;
|
|
210
|
+
const normalizedNextCommitment = typeof rawNextCommitment === "string" && rawNextCommitment.trim() !== "" ? normalizePreRotationCommitment(rawNextCommitment) : void 0;
|
|
211
|
+
const addresses = sender ? getRelatedAddresses(sender) : [senderAddress];
|
|
212
|
+
const ancestorStates = /* @__PURE__ */ new Map();
|
|
213
|
+
for (const address of addresses) if (address !== senderAddress) {
|
|
214
|
+
const old = await statedb.account.get(address, {
|
|
215
|
+
traceMigration: false,
|
|
216
|
+
txn: context.txn
|
|
217
|
+
});
|
|
218
|
+
if (old) {
|
|
219
|
+
ancestorStates.set(address, old);
|
|
220
|
+
if (normalizedNextCommitment && old.pk) {
|
|
221
|
+
const ancestorKeyType = toTypeInfo(old.address).pk ?? types.KeyType.ED25519;
|
|
222
|
+
if (normalizedNextCommitment === normalizePreRotationCommitment(createPreRotationCommitment(old.pk, ancestorKeyType))) return next(new CustomError("INVALID_PRE_ROTATION_COMMITMENT", "nextKeyCommitment cannot commit to an already-retired ancestor key"));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
let resolvedNewAccountData = sender?.data;
|
|
227
|
+
if (hasSenderPreRotation || hasIncomingPreRotation) {
|
|
228
|
+
const nextPayload = { ...senderData || {} };
|
|
229
|
+
const consumedSet = new Set(Array.isArray(senderData?.consumedKeyCommitments) ? senderData.consumedKeyCommitments.filter((c) => isValidPreRotationCommitment(c)).map((c) => normalizePreRotationCommitment(c)) : []);
|
|
230
|
+
const effectiveSenderPk = sender?.pk || tx$1.pk;
|
|
231
|
+
if (effectiveSenderPk) {
|
|
232
|
+
const senderKeyType = toTypeInfo(senderAddress).pk ?? types.KeyType.ED25519;
|
|
233
|
+
consumedSet.add(normalizePreRotationCommitment(createPreRotationCommitment(effectiveSenderPk, senderKeyType)));
|
|
234
|
+
}
|
|
235
|
+
if (senderData && typeof senderData.nextKeyCommitment === "string" && isValidPreRotationCommitment(senderData.nextKeyCommitment)) {
|
|
236
|
+
const normalizedConsumed = normalizePreRotationCommitment(senderData.nextKeyCommitment);
|
|
237
|
+
nextPayload.previousKeyCommitment = normalizedConsumed;
|
|
238
|
+
consumedSet.add(normalizedConsumed);
|
|
239
|
+
nextPayload.preRotationSeq = (typeof nextPayload.preRotationSeq === "number" && Number.isSafeInteger(nextPayload.preRotationSeq) && nextPayload.preRotationSeq >= 0 ? nextPayload.preRotationSeq : 0) + 1;
|
|
240
|
+
}
|
|
241
|
+
if (consumedSet.size > 0) nextPayload.consumedKeyCommitments = Array.from(consumedSet).slice(-MAX_ROTATION_CHAIN_LENGTH);
|
|
242
|
+
if (normalizedNextCommitment) nextPayload.nextKeyCommitment = normalizedNextCommitment;
|
|
243
|
+
else delete nextPayload.nextKeyCommitment;
|
|
244
|
+
if (itxData?.keyRotationEvent) nextPayload.lastKeyRotationEvent = itxData.keyRotationEvent;
|
|
245
|
+
if (senderDecoded.wrapperTypeUrl) resolvedNewAccountData = {
|
|
246
|
+
typeUrl: senderDecoded.wrapperTypeUrl,
|
|
247
|
+
value: nextPayload
|
|
248
|
+
};
|
|
249
|
+
else if (senderDecoded.wrapperType) resolvedNewAccountData = {
|
|
250
|
+
type: senderDecoded.wrapperType,
|
|
251
|
+
value: nextPayload
|
|
252
|
+
};
|
|
253
|
+
else if (sender?.data && typeof sender.data === "object") resolvedNewAccountData = nextPayload;
|
|
254
|
+
else if (itxDecoded.wrapperTypeUrl) resolvedNewAccountData = {
|
|
255
|
+
typeUrl: itxDecoded.wrapperTypeUrl,
|
|
256
|
+
value: nextPayload
|
|
257
|
+
};
|
|
258
|
+
else if (itxDecoded.wrapperType) resolvedNewAccountData = {
|
|
259
|
+
type: itxDecoded.wrapperType,
|
|
260
|
+
value: nextPayload
|
|
261
|
+
};
|
|
262
|
+
else resolvedNewAccountData = {
|
|
263
|
+
type: "json",
|
|
264
|
+
value: nextPayload
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
const baseSenderState = {
|
|
89
268
|
...sender || { tokens: senderTokens },
|
|
90
|
-
...senderUpdates
|
|
269
|
+
...senderUpdates
|
|
270
|
+
};
|
|
271
|
+
const mergedTokens = {};
|
|
272
|
+
for (const [tokAddr, bal] of Object.entries(baseSenderState.tokens || {})) if (bal && bal !== "0") mergedTokens[tokAddr] = bal;
|
|
273
|
+
const mergedTotalReceived = { ...baseSenderState.totalReceived || {} };
|
|
274
|
+
if (receiver) {
|
|
275
|
+
for (const [tokAddr, bal] of Object.entries(receiver.tokens || {})) {
|
|
276
|
+
const sum = toBN(mergedTokens[tokAddr] || "0").add(toBN(bal || "0")).toString();
|
|
277
|
+
if (sum !== "0") mergedTokens[tokAddr] = sum;
|
|
278
|
+
else delete mergedTokens[tokAddr];
|
|
279
|
+
}
|
|
280
|
+
for (const [tokAddr, rec] of Object.entries(receiver.totalReceived || {})) mergedTotalReceived[tokAddr] = toBN(mergedTotalReceived[tokAddr] || "0").add(toBN(rec || "0")).toString();
|
|
281
|
+
}
|
|
282
|
+
if (Object.keys(mergedTokens).length === 0) mergedTokens[tokenAddress] = "0";
|
|
283
|
+
const newAccountAttrs = {
|
|
284
|
+
...baseSenderState,
|
|
285
|
+
nonce: 0,
|
|
286
|
+
tokens: mergedTokens,
|
|
287
|
+
...Object.keys(mergedTotalReceived).length > 0 ? { totalReceived: mergedTotalReceived } : {},
|
|
288
|
+
...hasSenderPreRotation || hasIncomingPreRotation ? { data: resolvedNewAccountData } : {},
|
|
91
289
|
address: itx.address,
|
|
92
290
|
pk: itx.pk,
|
|
93
291
|
migratedFrom: sender ? uniq(flatten([sender.address, ...sender.migratedFrom || []])) : [senderAddress]
|
|
94
|
-
}
|
|
292
|
+
};
|
|
293
|
+
const createdAccountState = account.create(newAccountAttrs, context);
|
|
294
|
+
const newAccount = await statedb.account.updateOrCreate(receiver ?? null, createdAccountState, context);
|
|
95
295
|
debug("new account", newAccount);
|
|
96
|
-
const addresses = sender ? getRelatedAddresses(sender) : [senderAddress];
|
|
97
296
|
const states = await Promise.all(addresses.map(async (address) => {
|
|
98
297
|
let state;
|
|
99
298
|
if (address === senderAddress) {
|
|
100
299
|
state = account.updateOrCreate(sender ?? null, {
|
|
101
300
|
address,
|
|
301
|
+
pk: sender?.pk || tx$1.pk,
|
|
102
302
|
tokens: senderTokens,
|
|
103
303
|
migratedTo: [itx.address],
|
|
104
304
|
nonce: tx$1.nonce
|
|
105
305
|
}, context);
|
|
106
306
|
await statedb.account.updateOrCreate(sender ?? null, state, context);
|
|
107
307
|
} else {
|
|
108
|
-
const old = await statedb.account.get(address, {
|
|
308
|
+
const old = ancestorStates.get(address) || await statedb.account.get(address, {
|
|
109
309
|
traceMigration: false,
|
|
110
310
|
txn: context.txn
|
|
111
311
|
});
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { Runner } from "@ocap/tx-pipeline";
|
|
2
|
-
import { IReadyContext, IWithDelegation, IWithSender, TRevokeDelegateTx } from "@ocap/types";
|
|
2
|
+
import { IReadyContext, IWithDelegation, IWithReceiver, IWithSender, TRevokeDelegateTx } from "@ocap/types";
|
|
3
3
|
|
|
4
4
|
//#region src/protocols/account/revoke-delegate.d.ts
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Context type for revoke-delegate protocol.
|
|
8
8
|
* Phase: IReadyContext (after TakeStateSnapshot)
|
|
9
|
-
* Mixins: IWithSender (required), IWithDelegation (required)
|
|
9
|
+
* Mixins: IWithSender (required), IWithDelegation (required), Partial<IWithReceiver>
|
|
10
10
|
*/
|
|
11
|
-
type Context = IReadyContext<TRevokeDelegateTx> & IWithSender & IWithDelegation & {
|
|
11
|
+
type Context = IReadyContext<TRevokeDelegateTx> & IWithSender & IWithDelegation & Partial<IWithReceiver> & {
|
|
12
12
|
/** Type URLs to revoke from delegation */
|
|
13
13
|
typeUrls?: string[];
|
|
14
14
|
};
|