@ocap/wallet-hsm 0.0.0-stage → 1.33.8

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.
@@ -0,0 +1,34 @@
1
+ import { MpcProtocolError } from "@ocap/mpc-hsm/personal";
2
+ import { toHex, toUint8Array } from "@ocap/util";
3
+ import { fromExternalSigner } from "@ocap/wallet";
4
+
5
+ //#region src/logical-hsm-wallet.ts
6
+ function createLogicalHsmWallet(options) {
7
+ if (!options || typeof options.signWithBox !== "function") throw new MpcProtocolError("INVALID_PARAMETER", "createLogicalHsmWallet requires a signWithBox callback");
8
+ return fromExternalSigner({
9
+ publicKey: toHex(toUint8Array(options.publicKey)),
10
+ address: options.address,
11
+ method: options.method,
12
+ async sign(_signingInput, context) {
13
+ if (!options.allowRawDigestSigning) {
14
+ if (context.kind === "raw") {
15
+ if (!context.hashBeforeSign || context.rawPayloadBytes.byteLength === 32) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Logical-HSM keyless wallet forbids raw 32-byte or unhashed blind digest signing");
16
+ }
17
+ if (context.kind === "jwt" && !context.hashBeforeSign) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Logical-HSM keyless wallet requires v1.1.0 prehashed JWT signing");
18
+ }
19
+ return options.signWithBox({
20
+ keyAlias: options.keyAlias,
21
+ kind: context.kind,
22
+ rawPayloadBytes: context.rawPayloadBytes,
23
+ signingDigestHex: context.digestHex,
24
+ hashBeforeSign: context.hashBeforeSign,
25
+ publicKeyHex: context.publicKey,
26
+ address: context.address,
27
+ extra: context.extra
28
+ });
29
+ }
30
+ }, options.didType ?? "default");
31
+ }
32
+
33
+ //#endregion
34
+ export { createLogicalHsmWallet };
@@ -0,0 +1,88 @@
1
+ import { GatewayPrepareAuthProof, TxBroadcaster } from "./broadcaster.mjs";
2
+ import { Eip1559UnsignedTxFields, FirewallCommercialTier, MpcAggregatedSignature, MpcChildDerivationSpec, PersonalChildDerivationInput, PersonalClearSigningPreview, PersonalCosignerTransport, PersonalMpcEoaSigner, PersonalPolicyProofBundle, PersonalPostConditions, PersonalSignedEip1559Result, PersonalVaultPolicy, RandomBytesFn, SignedFirewallAttestation, SimulatedBalanceDelta, VaultEntitlementTicket } from "@ocap/mpc-hsm/personal";
3
+ import { WalletObject } from "@ocap/wallet";
4
+
5
+ //#region src/personal-hsm-wallet.d.ts
6
+
7
+ interface PersonalHsmSignOptions {
8
+ readonly policyProof?: PersonalPolicyProofBundle;
9
+ readonly entitlementTicket?: VaultEntitlementTicket;
10
+ readonly postConditions?: PersonalPostConditions;
11
+ readonly simulatedDelta?: SimulatedBalanceDelta;
12
+ readonly firewallAttestation?: SignedFirewallAttestation;
13
+ readonly attestedProxyImplementationAddress?: string;
14
+ }
15
+ interface PersonalHsmSendEip1559Options extends PersonalHsmSignOptions {
16
+ readonly tier?: FirewallCommercialTier;
17
+ readonly knownCounterparties?: ReadonlyArray<string>;
18
+ readonly authProof?: GatewayPrepareAuthProof;
19
+ readonly preferPrivateMevRpc?: boolean;
20
+ }
21
+ interface PersonalSignedOcapResult {
22
+ readonly derSignatureHex: string;
23
+ readonly signature: MpcAggregatedSignature;
24
+ readonly signingDigest32: Uint8Array;
25
+ readonly clearSigningPreview: PersonalClearSigningPreview;
26
+ readonly clearSigningPreviewHash32: Uint8Array;
27
+ }
28
+ interface PersonalHsmWallet {
29
+ readonly address: string;
30
+ readonly ocapSecp256k1Address: string;
31
+ readonly ocapSecp256k1Did: string;
32
+ readonly publicKeyComp33: Uint8Array;
33
+ readonly publicKeyCompHex: string;
34
+ readonly ethUncompressedPublicKeyHex: string;
35
+ readonly secp256k1UncompressedPublicKeyHex: string;
36
+ readonly childDerivation: MpcChildDerivationSpec;
37
+ signEip1559Transaction(tx: Eip1559UnsignedTxFields, options?: PersonalHsmSignOptions): Promise<PersonalSignedEip1559Result>;
38
+ sendEip1559Transaction(tx: Eip1559UnsignedTxFields, options?: PersonalHsmSendEip1559Options): Promise<{
39
+ readonly txHashHex: string;
40
+ readonly via: string;
41
+ readonly signed: PersonalSignedEip1559Result;
42
+ readonly firewallAttestation?: SignedFirewallAttestation;
43
+ }>;
44
+ readonly signOcapTransaction: (rawUnsignedCborBytes: Uint8Array | string, options?: PersonalHsmSignOptions & {
45
+ readonly nowSec?: bigint;
46
+ }) => Promise<PersonalSignedOcapResult>;
47
+ signArcblockJwt(payload?: Record<string, unknown>, options?: PersonalHsmSignOptions & {
48
+ readonly didType?: 'ethereum' | 'secp256k1';
49
+ readonly nowSec?: bigint;
50
+ }): Promise<string>;
51
+ signArcblockDelegationToken(payload: {
52
+ sub: string;
53
+ ops: string[];
54
+ deny?: string[];
55
+ delegation?: string;
56
+ iat?: string;
57
+ nbf?: string;
58
+ exp?: string;
59
+ }, options: PersonalHsmSignOptions & {
60
+ readonly didType?: 'ethereum' | 'secp256k1';
61
+ readonly nowSec?: bigint;
62
+ }): Promise<string>;
63
+ toEip1193Provider(options?: {
64
+ readonly defaultSendOptions?: PersonalHsmSendEip1559Options | (() => PersonalHsmSendEip1559Options | undefined);
65
+ }): Pick<PersonalMpcEoaSigner, 'request'>;
66
+ toViemLocalAccount(): ReturnType<PersonalMpcEoaSigner['toViemLocalAccount']>;
67
+ toOcapWallet(options?: {
68
+ readonly didType?: 'ethereum' | 'secp256k1';
69
+ readonly defaultSignOptions?: () => PersonalHsmSignOptions | undefined;
70
+ }): WalletObject<string>;
71
+ }
72
+ declare function createPersonalHsmWallet(params: {
73
+ readonly vaultId: string;
74
+ readonly slotId: string;
75
+ readonly policyEpoch: bigint;
76
+ readonly rootPublicKeyComp33: Uint8Array | string;
77
+ readonly xActorComp33?: Uint8Array | string;
78
+ readonly getActorShareBytes32: () => Promise<Uint8Array> | Uint8Array;
79
+ readonly policy?: PersonalVaultPolicy;
80
+ readonly childDerivation?: PersonalChildDerivationInput;
81
+ readonly transport: PersonalCosignerTransport;
82
+ readonly broadcaster?: TxBroadcaster;
83
+ readonly defaultSendOptions?: () => PersonalHsmSendEip1559Options | undefined;
84
+ readonly nowSec?: () => bigint;
85
+ readonly rng?: RandomBytesFn;
86
+ }): PersonalHsmWallet;
87
+ //#endregion
88
+ export { PersonalHsmSendEip1559Options, PersonalHsmSignOptions, PersonalHsmWallet, PersonalSignedOcapResult, createPersonalHsmWallet };
@@ -0,0 +1,383 @@
1
+ import { MpcProtocolError, VolatilePresignaturePool, aggregateOnlineSignature, buildPersonalClearSigningPreview, buildPersonalVaultClusterInfo, bytes32ToScalarNonZero, bytesToHex, computePersonalClearSigningPreviewHash32, createOnlineSignShare, createPersonalMpcEoaSigner, decodeAndRecoverSignedEip1559Tx, decodeAndVerifyPersonalArcblockJwt, decodeAndVerifyPersonalEip1559Tx, decodeAndVerifyPersonalOcapTx, decodePointCompressed, deriveOcapIdentitiesFromChildPoint, derivePersonalVaultChildKey, encodePointCompressed, mulBaseG, normalizeHexBytes, runPersonalClientPresignWithTransport, zeroizeBytes } from "@ocap/mpc-hsm/personal";
2
+ import * as JWT from "@arcblock/jwt";
3
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
4
+ import { types } from "@ocap/mcrypto";
5
+ import { toUint8Array } from "@ocap/util";
6
+ import { fromExternalSigner } from "@ocap/wallet";
7
+
8
+ //#region src/personal-hsm-wallet.ts
9
+ /**
10
+ * Dual-Surface Keyless Personal & Agent MPC Wallet (`@ocap/wallet-hsm`, #2333).
11
+ *
12
+ * Bridges `@ocap/mpc-hsm/personal` (`Slot 1` client share + `Slot 2` Stateless Sealed HSM cosigner)
13
+ * across BOTH:
14
+ * 1. EVM Clear-Signing (`signEip1559Transaction`, `sendEip1559Transaction`, `toEip1193Provider()`, `toViemLocalAccount()`)
15
+ * 2. OCAP Ecosystem `WalletObject` (`toOcapWallet()`, `signOcapTransaction`, `signArcblockJwt`, `signArcblockDelegationToken`)
16
+ *
17
+ * Non-negotiable invariants:
18
+ * - Zero `node:*` imports and zero `Buffer` references.
19
+ * - Full secret key `x_child` is NEVER reconstructed; `s_actor` is copied & zeroized in `finally`;
20
+ * `WalletObject.secretKey` is `''` and `toJSON().sk === ''`.
21
+ * - Raw 32-byte blind digests, `hashBeforeSign === false`, `eth_sign`, `personal_sign`, and EIP-7702 are hard-banned.
22
+ */
23
+ function aggregatedSigToCanonicalDerHex(sig) {
24
+ return `0x${bytesToHex(new secp256k1.Signature(sig.r, sig.s).toBytes("der"))}`;
25
+ }
26
+ function createPersonalHsmWallet(params) {
27
+ const pRootComp33 = encodePointCompressed(decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false));
28
+ const derivedChild = derivePersonalVaultChildKey({
29
+ vaultId: params.vaultId,
30
+ rootPublicKeyComp33: pRootComp33,
31
+ derivation: params.childDerivation
32
+ });
33
+ const identities = deriveOcapIdentitiesFromChildPoint(derivedChild.childPublicKeyComp33);
34
+ const nowSecFn = params.nowSec ?? (() => BigInt(Math.floor(Date.now() / 1e3)));
35
+ let cachedCluster = params.xActorComp33 !== void 0 ? buildPersonalVaultClusterInfo({
36
+ vaultId: params.vaultId,
37
+ slotId: params.slotId,
38
+ policyEpoch: params.policyEpoch,
39
+ rootPublicKeyComp33: pRootComp33,
40
+ xActorComp33: params.xActorComp33
41
+ }) : null;
42
+ const transportWithBroadcaster = {
43
+ initPresign: (r) => params.transport.initPresign(r),
44
+ stepPresign: (r) => params.transport.stepPresign(r),
45
+ signOnline: (r) => params.transport.signOnline(r),
46
+ broadcastRawTransaction: params.transport.broadcastRawTransaction ?? (params.broadcaster ? async (rawSignedTxHex) => {
47
+ const decoded = decodeAndRecoverSignedEip1559Tx(rawSignedTxHex);
48
+ return (await params.broadcaster.broadcastEip1559({
49
+ chainId: decoded.chainId,
50
+ rawSignedTxHex,
51
+ tier: "pro-shield"
52
+ })).txHashHex;
53
+ } : void 0)
54
+ };
55
+ const eoaSigner = createPersonalMpcEoaSigner({
56
+ vaultId: params.vaultId,
57
+ slotId: params.slotId,
58
+ policyEpoch: params.policyEpoch,
59
+ rootPublicKeyComp33: pRootComp33,
60
+ xActorComp33: params.xActorComp33,
61
+ getActorShareBytes32: params.getActorShareBytes32,
62
+ policy: params.policy,
63
+ childDerivation: params.childDerivation,
64
+ transport: transportWithBroadcaster,
65
+ rng: params.rng
66
+ });
67
+ const executeMpcCoSign = async (coSignInput) => {
68
+ const callerSActor = await params.getActorShareBytes32();
69
+ const sActorCopy32 = new Uint8Array(callerSActor);
70
+ const localPool = new VolatilePresignaturePool();
71
+ let presigPub = null;
72
+ try {
73
+ const xActorComp33 = encodePointCompressed(mulBaseG(bytes32ToScalarNonZero(sActorCopy32)));
74
+ if (!cachedCluster) cachedCluster = buildPersonalVaultClusterInfo({
75
+ vaultId: params.vaultId,
76
+ slotId: params.slotId,
77
+ policyEpoch: params.policyEpoch,
78
+ rootPublicKeyComp33: pRootComp33,
79
+ xActorComp33
80
+ });
81
+ const clientPresigRecord = await runPersonalClientPresignWithTransport({
82
+ cluster: cachedCluster,
83
+ sActorBytes32: sActorCopy32,
84
+ transport: params.transport,
85
+ rng: params.rng
86
+ });
87
+ presigPub = clientPresigRecord.publicVerification;
88
+ localPool.store(clientPresigRecord);
89
+ const onlineReq = {
90
+ rootId: params.vaultId,
91
+ presigId: presigPub.presigId32,
92
+ subset: [1, 2],
93
+ msgDigest32: coSignInput.signingDigest32,
94
+ childDerivation: derivedChild.derivationSpec
95
+ };
96
+ const localShareRes = createOnlineSignShare({
97
+ pool: localPool,
98
+ request: onlineReq
99
+ });
100
+ const cosignerRes = await params.transport.signOnline({
101
+ vaultId: params.vaultId,
102
+ slotId: params.slotId,
103
+ presigIdHex: presigPub.presigIdHex,
104
+ payloadKind: coSignInput.payloadKind,
105
+ unsignedPayloadBytes: coSignInput.unsignedPayloadBytes,
106
+ signingDigest32: coSignInput.signingDigest32,
107
+ clearSigningPreview: coSignInput.clearSigningPreview,
108
+ clearSigningPreviewHash32: coSignInput.clearSigningPreviewHash32,
109
+ childDerivation: derivedChild.derivationSpec,
110
+ policyProof: coSignInput.options?.policyProof,
111
+ entitlementTicket: coSignInput.options?.entitlementTicket,
112
+ firewallAttestation: coSignInput.options?.firewallAttestation,
113
+ attestedProxyImplementationAddress: coSignInput.options?.attestedProxyImplementationAddress,
114
+ simulatedDelta: coSignInput.options?.simulatedDelta,
115
+ postConditions: coSignInput.options?.postConditions
116
+ });
117
+ if (!cosignerRes?.share || cosignerRes.share.slot !== 2) throw new MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", "Expected cosigner partial signature from slot 2", 2);
118
+ return aggregateOnlineSignature({
119
+ shares: [localShareRes.share, cosignerRes.share],
120
+ publicVerification: presigPub,
121
+ request: onlineReq
122
+ });
123
+ } finally {
124
+ zeroizeBytes(sActorCopy32);
125
+ localPool.wipeAll();
126
+ }
127
+ };
128
+ const signEip1559Transaction = (tx, options) => eoaSigner.signTransaction(tx, options);
129
+ const sendEip1559Transaction = async (tx, options) => {
130
+ if (!params.broadcaster) throw new MpcProtocolError("INVALID_PARAMETER", "TxBroadcaster is required for sendEip1559Transaction");
131
+ let preparedAttestation = options?.firewallAttestation;
132
+ let preparedDelta = options?.simulatedDelta;
133
+ let preparedProxyImpl = options?.attestedProxyImplementationAddress;
134
+ const preVerified = decodeAndVerifyPersonalEip1559Tx({
135
+ txOrRawBytes: tx,
136
+ policy: params.policy,
137
+ hasL2OrL3QuorumProof: options?.policyProof?.tier === "L2" || options?.policyProof?.tier === "L3"
138
+ });
139
+ const prePreviewHashHex = `0x${bytesToHex(computePersonalClearSigningPreviewHash32(buildPersonalClearSigningPreview({
140
+ fromAddress: identities.ethChecksumAddress,
141
+ verifiedTx: preVerified
142
+ })))}`;
143
+ if (!preparedAttestation && params.broadcaster.prepareEip1559) {
144
+ const prep = await params.broadcaster.prepareEip1559({
145
+ vaultId: params.vaultId,
146
+ policyEpoch: params.policyEpoch,
147
+ tier: options?.tier ?? (params.policy?.requireFirewallAttestation ? "vault-enforced" : "pro-shield"),
148
+ fromAddress: identities.ethChecksumAddress,
149
+ tx,
150
+ signingDigestHex: preVerified.signingDigestHex,
151
+ clearSigningPreviewHashHex: prePreviewHashHex,
152
+ knownCounterparties: options?.knownCounterparties,
153
+ postConditions: options?.postConditions,
154
+ authProof: options?.authProof
155
+ });
156
+ preparedAttestation = prep.firewallAttestation;
157
+ preparedDelta = prep.simulatedDelta;
158
+ preparedProxyImpl = prep.attestedProxyImplementationAddress;
159
+ }
160
+ if (params.policy?.requireFirewallAttestation && (!preparedAttestation || !preparedDelta)) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_REQUIRED", "Vault policy requires SignedFirewallAttestation + simulatedDelta, and broadcaster did not supply Stage 1 prepare output");
161
+ const signed = await signEip1559Transaction(tx, {
162
+ ...options,
163
+ simulatedDelta: preparedDelta,
164
+ firewallAttestation: preparedAttestation,
165
+ attestedProxyImplementationAddress: preparedProxyImpl
166
+ });
167
+ const broadcasted = await params.broadcaster.broadcastEip1559({
168
+ chainId: tx.chainId,
169
+ rawSignedTxHex: signed.rawSignedTxHex,
170
+ tier: options?.tier ?? (preparedAttestation ? preparedAttestation.tier : "pro-shield"),
171
+ firewallAttestation: preparedAttestation,
172
+ stage1SimulatedDelta: preparedDelta,
173
+ attestedProxyImplementationAddress: preparedProxyImpl,
174
+ postConditions: options?.postConditions,
175
+ preferPrivateMevRpc: options?.preferPrivateMevRpc
176
+ });
177
+ return {
178
+ txHashHex: broadcasted.txHashHex,
179
+ via: broadcasted.via,
180
+ signed,
181
+ ...preparedAttestation ? { firewallAttestation: preparedAttestation } : {}
182
+ };
183
+ };
184
+ const signOcapTransaction = async (rawUnsignedCborBytes, options) => {
185
+ const hasL2OrL3 = options?.policyProof?.tier === "L2" || options?.policyProof?.tier === "L3";
186
+ const hasL3Guardian = options?.policyProof?.tier === "L3" && options.policyProof.quorumProof?.kind === "guardian-quorum";
187
+ const decoded = decodeAndVerifyPersonalOcapTx({
188
+ rawTxBytes: rawUnsignedCborBytes,
189
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
190
+ policy: params.policy,
191
+ nowSec: options?.nowSec ?? nowSecFn(),
192
+ hasL2OrL3QuorumProof: hasL2OrL3,
193
+ hasL3GuardianQuorumProof: hasL3Guardian
194
+ });
195
+ const aggregated = await executeMpcCoSign({
196
+ payloadKind: "ocap-tx",
197
+ unsignedPayloadBytes: decoded.verifiedOcapTx.unsignedPayloadBytes,
198
+ signingDigest32: decoded.verifiedOcapTx.signingDigest32,
199
+ clearSigningPreview: decoded.clearSigningPreview,
200
+ clearSigningPreviewHash32: decoded.clearSigningPreviewHash32,
201
+ options
202
+ });
203
+ return {
204
+ derSignatureHex: aggregatedSigToCanonicalDerHex(aggregated),
205
+ signature: aggregated,
206
+ signingDigest32: decoded.verifiedOcapTx.signingDigest32,
207
+ clearSigningPreview: decoded.clearSigningPreview,
208
+ clearSigningPreviewHash32: decoded.clearSigningPreviewHash32
209
+ };
210
+ };
211
+ const signArcblockJwt = async (payload = {}, options) => {
212
+ const signerDid = (options?.didType ?? "secp256k1") === "ethereum" ? `did:abt:${identities.ethChecksumAddress}` : identities.ocapSecp256k1Did;
213
+ return JWT.signWithSigner(signerDid, async (_signingDigestHex, ctx) => {
214
+ const hasL2OrL3 = options?.policyProof?.tier === "L2" || options?.policyProof?.tier === "L3";
215
+ const verified = decodeAndVerifyPersonalArcblockJwt({
216
+ unsignedTokenOrBytes: ctx.unsignedToken,
217
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
218
+ nowSec: options?.nowSec ?? nowSecFn(),
219
+ policy: params.policy,
220
+ hasL2OrL3QuorumProof: hasL2OrL3
221
+ });
222
+ return aggregatedSigToCanonicalDerHex(await executeMpcCoSign({
223
+ payloadKind: "arcblock-jwt",
224
+ unsignedPayloadBytes: verified.verifiedJwt.unsignedPayloadBytes,
225
+ signingDigest32: verified.verifiedJwt.signingDigest32,
226
+ clearSigningPreview: verified.clearSigningPreview,
227
+ clearSigningPreviewHash32: verified.clearSigningPreviewHash32,
228
+ options
229
+ }));
230
+ }, payload, "1.1.0");
231
+ };
232
+ const signArcblockDelegationToken = async (payload, options) => {
233
+ const scheme = options?.didType ?? "secp256k1";
234
+ const signerDid = scheme === "ethereum" ? `did:abt:${identities.ethChecksumAddress}` : identities.ocapSecp256k1Did;
235
+ const pkHex = scheme === "ethereum" ? identities.ethUncompressedPkHex : identities.secp256k1UncompressedPkHex;
236
+ return JWT.signDelegationTokenWithSigner(signerDid, pkHex, async (_signingDigestHex, ctx) => {
237
+ const hasL2OrL3 = options?.policyProof?.tier === "L2" || options?.policyProof?.tier === "L3";
238
+ const verified = decodeAndVerifyPersonalArcblockJwt({
239
+ unsignedTokenOrBytes: ctx.unsignedToken,
240
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
241
+ nowSec: options?.nowSec ?? nowSecFn(),
242
+ policy: params.policy,
243
+ hasL2OrL3QuorumProof: hasL2OrL3
244
+ });
245
+ return aggregatedSigToCanonicalDerHex(await executeMpcCoSign({
246
+ payloadKind: "arcblock-jwt",
247
+ unsignedPayloadBytes: verified.verifiedJwt.unsignedPayloadBytes,
248
+ signingDigest32: verified.verifiedJwt.signingDigest32,
249
+ clearSigningPreview: verified.clearSigningPreview,
250
+ clearSigningPreviewHash32: verified.clearSigningPreviewHash32,
251
+ options
252
+ }));
253
+ }, payload);
254
+ };
255
+ const toOcapWallet = (opts) => {
256
+ const scheme = opts?.didType ?? "secp256k1";
257
+ const walletType = scheme === "ethereum" ? "ethereum" : {
258
+ role: types.RoleType.ROLE_ACCOUNT,
259
+ pk: types.KeyType.SECP256K1,
260
+ hash: types.HashType.SHA3,
261
+ address: types.EncodingType.BASE58
262
+ };
263
+ return fromExternalSigner({
264
+ publicKey: scheme === "ethereum" ? identities.ethUncompressedPkHex : identities.secp256k1UncompressedPkHex,
265
+ address: scheme === "ethereum" ? identities.ethChecksumAddress : identities.ocapSecp256k1Address,
266
+ async sign(_signingInput, context) {
267
+ if (context.kind === "jwt") {
268
+ if (!context.hashBeforeSign || typeof context.rawPayload !== "string") throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Personal HSM OCAP wallet requires v1.1.0 prehashed structured JWT");
269
+ const signOpts = opts?.defaultSignOptions?.();
270
+ const hasL2OrL3 = signOpts?.policyProof?.tier === "L2" || signOpts?.policyProof?.tier === "L3";
271
+ const verified = decodeAndVerifyPersonalArcblockJwt({
272
+ unsignedTokenOrBytes: context.rawPayload,
273
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
274
+ nowSec: nowSecFn(),
275
+ policy: params.policy,
276
+ hasL2OrL3QuorumProof: hasL2OrL3
277
+ });
278
+ return aggregatedSigToCanonicalDerHex(await executeMpcCoSign({
279
+ payloadKind: "arcblock-jwt",
280
+ unsignedPayloadBytes: verified.verifiedJwt.unsignedPayloadBytes,
281
+ signingDigest32: verified.verifiedJwt.signingDigest32,
282
+ clearSigningPreview: verified.clearSigningPreview,
283
+ clearSigningPreviewHash32: verified.clearSigningPreviewHash32,
284
+ options: signOpts
285
+ }));
286
+ }
287
+ if (!context.hashBeforeSign) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Pre-hashed blind digest signing (hashBeforeSign=false) is forbidden on Personal HSM wallet");
288
+ const rawBytes = toUint8Array(context.rawPayload);
289
+ if (rawBytes.length >= 4 && rawBytes[0] === 217 && rawBytes[1] === 217 && rawBytes[2] === 247) return (await signOcapTransaction(rawBytes, opts?.defaultSignOptions?.())).derSignatureHex;
290
+ throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Personal HSM OCAP wallet only signs canonical CBOR OCAP transactions (0xd9d9f7) or v1.1.0 ArcBlock JWTs");
291
+ },
292
+ async signEnvelope() {
293
+ throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Arbitrary message envelope signing is forbidden on Personal HSM wallet");
294
+ },
295
+ async signETH() {
296
+ throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Blind ethSign is forbidden on Personal HSM wallet");
297
+ }
298
+ }, walletType);
299
+ };
300
+ const parseEip1193Uint = (raw, label, fallback) => {
301
+ if (raw === void 0 || raw === null) {
302
+ if (fallback !== void 0) return fallback;
303
+ throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Missing ${label} in EIP-1193 transaction`);
304
+ }
305
+ if (typeof raw === "bigint" && raw >= 0n) return raw;
306
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 0) return BigInt(raw);
307
+ if (typeof raw === "string") {
308
+ const s = raw.trim();
309
+ if (/^0x[0-9a-fA-F]+$/.test(s)) return BigInt(s);
310
+ if (/^(?:0|[1-9][0-9]*)$/.test(s)) return BigInt(s);
311
+ }
312
+ throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid ${label} in EIP-1193 transaction`);
313
+ };
314
+ const parseEip1193TxObject = (rawTx) => {
315
+ if (!rawTx || typeof rawTx !== "object" || Array.isArray(rawTx)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "EIP-1193 eth_sendTransaction requires a tx object");
316
+ const obj = rawTx;
317
+ if (obj.type === 4 || obj.type === "0x4" || obj.type === "0x04" || obj.type === "eip7702" || obj.authorizationList !== void 0) throw new MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", "EIP-7702 transactions are forbidden");
318
+ if (obj.type !== void 0 && obj.type !== 2 && obj.type !== "0x2" && obj.type !== "0x02" && obj.type !== "eip1559") throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Unsupported EIP-1193 transaction type "${String(obj.type)}"; EIP-1559 (0x02) required`);
319
+ if (obj.from !== void 0 && String(obj.from).toLowerCase() !== identities.ethChecksumAddress.toLowerCase()) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "EIP-1193 tx.from does not match Personal HSM EOA");
320
+ if (typeof obj.to !== "string" || obj.to.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Contract creation (missing to) is forbidden on Personal HSM");
321
+ let parsedAccessList;
322
+ if (obj.accessList !== void 0) {
323
+ if (!Array.isArray(obj.accessList)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "EIP-1193 accessList must be an array");
324
+ parsedAccessList = obj.accessList.map((item, idx) => {
325
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid accessList[${idx}] entry`);
326
+ const rec = item;
327
+ if (typeof rec.address !== "string" || !Array.isArray(rec.storageKeys)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Malformed accessList[${idx}] address or storageKeys`);
328
+ return {
329
+ address: rec.address,
330
+ storageKeys: rec.storageKeys.map((sk) => sk instanceof Uint8Array ? sk : String(sk))
331
+ };
332
+ });
333
+ }
334
+ return {
335
+ chainId: parseEip1193Uint(obj.chainId, "chainId"),
336
+ nonce: parseEip1193Uint(obj.nonce, "nonce", 0n),
337
+ maxPriorityFeePerGasWei: parseEip1193Uint(obj.maxPriorityFeePerGas ?? obj.maxPriorityFeePerGasWei, "maxPriorityFeePerGas"),
338
+ maxFeePerGasWei: parseEip1193Uint(obj.maxFeePerGas ?? obj.maxFeePerGasWei, "maxFeePerGas"),
339
+ gasLimit: parseEip1193Uint(obj.gas ?? obj.gasLimit, "gas"),
340
+ to: obj.to,
341
+ valueWei: parseEip1193Uint(obj.value ?? obj.valueWei, "value", 0n),
342
+ data: obj.data instanceof Uint8Array ? obj.data : typeof obj.data === "string" && obj.data.length > 0 ? obj.data : "0x",
343
+ ...parsedAccessList ? { accessList: parsedAccessList } : {}
344
+ };
345
+ };
346
+ const toEip1193Provider = (providerOpts) => {
347
+ const resolveMergedOpts = () => {
348
+ const baseOpts = params.defaultSendOptions?.();
349
+ const overrideOpts = typeof providerOpts?.defaultSendOptions === "function" ? providerOpts.defaultSendOptions() : providerOpts?.defaultSendOptions;
350
+ return baseOpts || overrideOpts ? {
351
+ ...baseOpts,
352
+ ...overrideOpts
353
+ } : void 0;
354
+ };
355
+ const request = async (args) => {
356
+ if (args.method === "eth_sendTransaction" && params.broadcaster) return (await sendEip1559Transaction(parseEip1193TxObject(Array.isArray(args.params) ? args.params[0] : void 0), resolveMergedOpts())).txHashHex;
357
+ if (args.method === "eth_signTransaction") return (await signEip1559Transaction(parseEip1193TxObject(Array.isArray(args.params) ? args.params[0] : void 0), resolveMergedOpts())).rawSignedTxHex;
358
+ return eoaSigner.request(args);
359
+ };
360
+ return { request };
361
+ };
362
+ return {
363
+ address: identities.ethChecksumAddress,
364
+ ocapSecp256k1Address: identities.ocapSecp256k1Address,
365
+ ocapSecp256k1Did: identities.ocapSecp256k1Did,
366
+ publicKeyComp33: derivedChild.childPublicKeyComp33,
367
+ publicKeyCompHex: `0x${bytesToHex(derivedChild.childPublicKeyComp33)}`,
368
+ ethUncompressedPublicKeyHex: identities.ethUncompressedPkHex,
369
+ secp256k1UncompressedPublicKeyHex: identities.secp256k1UncompressedPkHex,
370
+ childDerivation: derivedChild.derivationSpec,
371
+ signEip1559Transaction,
372
+ sendEip1559Transaction,
373
+ signOcapTransaction,
374
+ signArcblockJwt,
375
+ signArcblockDelegationToken,
376
+ toEip1193Provider,
377
+ toViemLocalAccount: () => eoaSigner.toViemLocalAccount(),
378
+ toOcapWallet
379
+ };
380
+ }
381
+
382
+ //#endregion
383
+ export { createPersonalHsmWallet };
@@ -0,0 +1,29 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+
29
+ exports.__toESM = __toESM;