@sig-net/midnight 0.0.2 → 0.0.3
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/package.json +2 -2
- package/src/constants.ts +0 -97
- package/src/epsilon-derivation.ts +0 -62
- package/src/index.ts +0 -29
- package/src/managed/compiler/contract-info.json +0 -222
- package/src/managed/compiler/contract-manifest.json +0 -32
- package/src/managed/contract/index.d.ts +0 -78
- package/src/managed/contract/index.js +0 -676
- package/src/managed/contract/index.js.map +0 -8
- package/src/schnorr.ts +0 -210
- package/src/signature-requests-state-reader.ts +0 -223
- package/src/signature-response-verification.ts +0 -64
- package/src/signature-state-reading.ts +0 -87
- package/src/signet-contract-state-reader.ts +0 -587
- package/src/signet-request-feed.ts +0 -208
- package/src/signet-request-resolver.ts +0 -116
- package/src/signet-request-response-reader.ts +0 -324
- package/src/signet-requests.ts +0 -762
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
// The MPC's single entry point for discovering signature requests: poll the
|
|
2
|
-
// central signet contract's notification registry (ledger field 4), resolve
|
|
3
|
-
// each notification to an AUTHENTICATED request read from the named caller's
|
|
4
|
-
// own ledger, and yield only the ones that pass the membership check. The
|
|
5
|
-
// registry is append-only with no on-ledger cursor, so the feed's in-memory
|
|
6
|
-
// `yielded` set is the diff cursor: every poll enumerates the registry and
|
|
7
|
-
// serves what it has not served before.
|
|
8
|
-
//
|
|
9
|
-
// The requester allow-list is an OPTIONAL policy filter here (drop requests
|
|
10
|
-
// from contracts you choose not to serve), never a security requirement and
|
|
11
|
-
// never the discovery mechanism — attribution comes from the resolver's
|
|
12
|
-
// authenticated read (see signet-request-resolver.ts and
|
|
13
|
-
// knowledge-base/caller-attribution.md).
|
|
14
|
-
|
|
15
|
-
import {
|
|
16
|
-
decodeSignBidirectionalNotification,
|
|
17
|
-
readSignBidirectionalNotificationIndexFromState,
|
|
18
|
-
} from "./signet-contract-state-reader.ts";
|
|
19
|
-
import {
|
|
20
|
-
SignetRequestResolver,
|
|
21
|
-
type ResolvedSignetRequest,
|
|
22
|
-
} from "./signet-request-resolver.ts";
|
|
23
|
-
import type { SignetPublicStateSource } from "./signet-request-response-reader.ts";
|
|
24
|
-
import { stripHexPrefix, type RequestIdHex } from "./signet-requests.ts";
|
|
25
|
-
|
|
26
|
-
/** Default gap between poll cycles of {@link SignetRequestFeed.requests}. */
|
|
27
|
-
export const DEFAULT_FEED_POLL_INTERVAL_MS = 3000;
|
|
28
|
-
|
|
29
|
-
/** Everything a {@link SignetRequestFeed} needs. */
|
|
30
|
-
export interface SignetRequestFeedConfig {
|
|
31
|
-
/** Address of the central signet contract whose notification registry to poll. */
|
|
32
|
-
readonly signetContractAddress: string;
|
|
33
|
-
/**
|
|
34
|
-
* Source of raw contract state for BOTH the signet contract's registry and
|
|
35
|
-
* the requester ledgers the resolver authenticates against — a full
|
|
36
|
-
* `indexerPublicDataProvider` is assignable.
|
|
37
|
-
*/
|
|
38
|
-
readonly source: SignetPublicStateSource;
|
|
39
|
-
/**
|
|
40
|
-
* Optional policy allow-list of requester contract addresses to serve
|
|
41
|
-
* (matched case- and `0x`-prefix-insensitively). Omit to serve every
|
|
42
|
-
* requester the resolver can authenticate. NOT a security control.
|
|
43
|
-
*/
|
|
44
|
-
readonly allowContracts?: Iterable<string>;
|
|
45
|
-
/** Poll cadence for {@link SignetRequestFeed.requests}; default {@link DEFAULT_FEED_POLL_INTERVAL_MS}. */
|
|
46
|
-
readonly pollIntervalMs?: number;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Resolve after `ms`, or immediately once `signal` aborts. Used to space out
|
|
51
|
-
* polls without wedging a shutdown.
|
|
52
|
-
*
|
|
53
|
-
* @param ms - Milliseconds to wait.
|
|
54
|
-
* @param signal - Abort to resolve early.
|
|
55
|
-
* @returns A promise that settles after the delay or the abort.
|
|
56
|
-
*/
|
|
57
|
-
export function sleepUnlessAborted(
|
|
58
|
-
ms: number,
|
|
59
|
-
signal?: AbortSignal,
|
|
60
|
-
): Promise<void> {
|
|
61
|
-
return new Promise((resolve) => {
|
|
62
|
-
if (signal?.aborted) return resolve();
|
|
63
|
-
const timer = setTimeout(() => {
|
|
64
|
-
signal?.removeEventListener("abort", onAbort);
|
|
65
|
-
resolve();
|
|
66
|
-
}, ms);
|
|
67
|
-
const onAbort = () => {
|
|
68
|
-
clearTimeout(timer);
|
|
69
|
-
resolve();
|
|
70
|
-
};
|
|
71
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** Canonical form for comparing contract addresses: no `0x`, lowercase. */
|
|
76
|
-
function normalizeAddress(address: string): string {
|
|
77
|
-
return stripHexPrefix(address).toLowerCase();
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* The registry-polling request feed. Reads the signet contract's notification
|
|
82
|
-
* registry (discovery) and hands each notification to a
|
|
83
|
-
* {@link SignetRequestResolver} (authentication), yielding only notifications
|
|
84
|
-
* that resolve to a real, member request. Dedupes by request id across its
|
|
85
|
-
* lifetime, so a re-registered notification is not re-yielded; call
|
|
86
|
-
* {@link forget} to re-arm a request whose downstream processing failed.
|
|
87
|
-
*/
|
|
88
|
-
export class SignetRequestFeed {
|
|
89
|
-
private readonly signetContractAddress: string;
|
|
90
|
-
private readonly source: SignetPublicStateSource;
|
|
91
|
-
private readonly resolver: SignetRequestResolver;
|
|
92
|
-
private readonly allowContracts?: Set<string>;
|
|
93
|
-
private readonly pollIntervalMs: number;
|
|
94
|
-
|
|
95
|
-
// Request ids already yielded. NOT the security boundary (the resolver is) —
|
|
96
|
-
// just an at-most-once gate so one request is not processed twice.
|
|
97
|
-
private readonly yielded = new Set<RequestIdHex>();
|
|
98
|
-
|
|
99
|
-
/**
|
|
100
|
-
* @param config - The signet contract, state source, and optional policy
|
|
101
|
-
* allow-list.
|
|
102
|
-
*/
|
|
103
|
-
constructor(config: SignetRequestFeedConfig) {
|
|
104
|
-
this.signetContractAddress = config.signetContractAddress;
|
|
105
|
-
this.source = config.source;
|
|
106
|
-
this.resolver = new SignetRequestResolver({ source: config.source });
|
|
107
|
-
this.allowContracts = config.allowContracts
|
|
108
|
-
? new Set(Array.from(config.allowContracts, normalizeAddress))
|
|
109
|
-
: undefined;
|
|
110
|
-
this.pollIntervalMs =
|
|
111
|
-
config.pollIntervalMs ?? DEFAULT_FEED_POLL_INTERVAL_MS;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** Whether the policy allow-list admits `callerAddress` (always true when unset). */
|
|
115
|
-
private allowed(callerAddress: string): boolean {
|
|
116
|
-
return (
|
|
117
|
-
this.allowContracts === undefined ||
|
|
118
|
-
this.allowContracts.has(normalizeAddress(callerAddress))
|
|
119
|
-
);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* One-shot: every currently-registered notification that decodes, is
|
|
124
|
-
* admitted by the allow-list, not already yielded, and resolves to an
|
|
125
|
-
* authenticated member request. Registry enumeration has no meaningful
|
|
126
|
-
* on-ledger order, so entries are processed in ascending request-id-hex
|
|
127
|
-
* order — a stable, deterministic sequence. Forged / not-yet-indexed /
|
|
128
|
-
* wrong-field notifications resolve to nothing and are dropped WITHOUT
|
|
129
|
-
* being marked yielded, so a genuine request whose ledger write has not
|
|
130
|
-
* indexed yet is retried next cycle; undecodable or unsupported-version
|
|
131
|
-
* records are likewise skipped (and logged) without being marked.
|
|
132
|
-
*
|
|
133
|
-
* Dedupe and resolution key off the notification PAYLOAD's request id (the
|
|
134
|
-
* canonical one — the registry map key is caller-supplied and could
|
|
135
|
-
* disagree; the resolver's membership check authenticates the payload's).
|
|
136
|
-
*
|
|
137
|
-
* @returns The newly-authenticated requests this cycle.
|
|
138
|
-
* @throws Error if the signet contract has no readable state at the
|
|
139
|
-
* configured address (wrong address or not yet deployed/indexed).
|
|
140
|
-
*/
|
|
141
|
-
async poll(): Promise<ResolvedSignetRequest[]> {
|
|
142
|
-
const state = await this.source.queryContractState(
|
|
143
|
-
this.signetContractAddress,
|
|
144
|
-
);
|
|
145
|
-
if (!state?.data) {
|
|
146
|
-
throw new Error(
|
|
147
|
-
`No contract state at signet contract ${this.signetContractAddress} ` +
|
|
148
|
-
`— wrong address, or not yet deployed/indexed`,
|
|
149
|
-
);
|
|
150
|
-
}
|
|
151
|
-
const registry = readSignBidirectionalNotificationIndexFromState(
|
|
152
|
-
state.data,
|
|
153
|
-
);
|
|
154
|
-
const out: ResolvedSignetRequest[] = [];
|
|
155
|
-
for (const [registryKey, record] of [...registry.entries()].sort(
|
|
156
|
-
([a], [b]) => (a < b ? -1 : a > b ? 1 : 0),
|
|
157
|
-
)) {
|
|
158
|
-
let notification;
|
|
159
|
-
try {
|
|
160
|
-
notification = decodeSignBidirectionalNotification(record);
|
|
161
|
-
} catch (error) {
|
|
162
|
-
console.warn(
|
|
163
|
-
`SignetRequestFeed: skipping undecodable notification ` +
|
|
164
|
-
`registered under ${registryKey}: ${String(error)}`,
|
|
165
|
-
);
|
|
166
|
-
continue;
|
|
167
|
-
}
|
|
168
|
-
if (this.yielded.has(notification.requestId)) continue;
|
|
169
|
-
if (!this.allowed(notification.callerAddress)) continue;
|
|
170
|
-
const resolved = await this.resolver.resolve(notification);
|
|
171
|
-
if (resolved === undefined) continue;
|
|
172
|
-
this.yielded.add(notification.requestId);
|
|
173
|
-
out.push(resolved);
|
|
174
|
-
}
|
|
175
|
-
return out;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Re-arm `requestId` for redelivery on the next {@link poll} / {@link requests}
|
|
180
|
-
* cycle — call when downstream processing of a yielded request failed, so it
|
|
181
|
-
* is retried (mirrors the MPC's delete-on-failure of its processed set).
|
|
182
|
-
*
|
|
183
|
-
* @param requestId - The request id to allow through again.
|
|
184
|
-
*/
|
|
185
|
-
forget(requestId: RequestIdHex): void {
|
|
186
|
-
this.yielded.delete(requestId);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/**
|
|
190
|
-
* Live stream: poll + sleep, yielding each authenticated request exactly once
|
|
191
|
-
* (subject to {@link forget}), until `opts.signal` aborts. The natural
|
|
192
|
-
* sequential `for await` consumption serializes downstream processing — no
|
|
193
|
-
* two requests are handed over concurrently.
|
|
194
|
-
*
|
|
195
|
-
* @param opts.signal - Abort to stop the stream.
|
|
196
|
-
* @yields Each authenticated request, in discovery order.
|
|
197
|
-
*/
|
|
198
|
-
async *requests(opts?: {
|
|
199
|
-
signal?: AbortSignal;
|
|
200
|
-
}): AsyncIterableIterator<ResolvedSignetRequest> {
|
|
201
|
-
while (!opts?.signal?.aborted) {
|
|
202
|
-
const batch = await this.poll();
|
|
203
|
-
for (const resolved of batch) yield resolved;
|
|
204
|
-
if (opts?.signal?.aborted) break;
|
|
205
|
-
await sleepUnlessAborted(this.pollIntervalMs, opts?.signal);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
}
|
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
// Turn a SignBidirectionalNotification into an AUTHENTICATED request record.
|
|
2
|
-
// This is the security core of the discovery flow (see
|
|
3
|
-
// knowledge-base/caller-attribution.md): the notification says only WHERE to
|
|
4
|
-
// look; the request that gets signed is read from the named caller's own
|
|
5
|
-
// authenticated ledger, and the notification's `requestId` must be a member
|
|
6
|
-
// of that contract's request index. An attacker cannot write into a contract
|
|
7
|
-
// it does not control, so a forged notification can at most re-point at a
|
|
8
|
-
// legitimate request that already exists — never inject one.
|
|
9
|
-
//
|
|
10
|
-
// Key derivation stays f(callerAddress, path), keyed off the contract whose
|
|
11
|
-
// authenticated state was actually read — the notification registry is a
|
|
12
|
-
// pointer board, never an authority.
|
|
13
|
-
|
|
14
|
-
import { lookupSignetRequestAt } from "./signature-requests-state-reader.ts";
|
|
15
|
-
import type { RawContractState } from "./signature-state-reading.ts";
|
|
16
|
-
import type { SignBidirectionalNotification } from "./signet-contract-state-reader.ts";
|
|
17
|
-
import type { SignetPublicStateSource } from "./signet-request-response-reader.ts";
|
|
18
|
-
import type {
|
|
19
|
-
RequestIdHex,
|
|
20
|
-
SignBidirectionalRequest,
|
|
21
|
-
} from "./signet-requests.ts";
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* A {@link SignBidirectionalNotification} resolved to the authenticated
|
|
25
|
-
* request it refers to: the request record read from `callerAddress`'s own
|
|
26
|
-
* ledger, with `requestId` confirmed to be a member of that contract's index.
|
|
27
|
-
*/
|
|
28
|
-
export interface ResolvedSignetRequest {
|
|
29
|
-
/**
|
|
30
|
-
* The contract whose authenticated state the request was read from — the
|
|
31
|
-
* epsilon-derivation predecessor. Key derivation keys off THIS, never off a
|
|
32
|
-
* field taken from the notification on faith.
|
|
33
|
-
*/
|
|
34
|
-
callerAddress: string;
|
|
35
|
-
/** The request id, confirmed to be a member of `callerAddress`'s index. */
|
|
36
|
-
requestId: RequestIdHex;
|
|
37
|
-
/** The authenticated request record to sign. */
|
|
38
|
-
request: SignBidirectionalRequest;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Everything a {@link SignetRequestResolver} needs. */
|
|
42
|
-
export interface SignetRequestResolverConfig {
|
|
43
|
-
/** Source of raw contract state, e.g. midnight-js's `indexerPublicDataProvider`. */
|
|
44
|
-
readonly source: SignetPublicStateSource;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Resolves {@link SignBidirectionalNotification}s to authenticated
|
|
49
|
-
* {@link ResolvedSignetRequest}s by reading the named caller's ledger and
|
|
50
|
-
* enforcing the membership check. Construct once and reuse: resolved records
|
|
51
|
-
* are immutable (their ledger key is their hash), so they are cached by request
|
|
52
|
-
* id and a repeated notification for the same request costs no query.
|
|
53
|
-
*
|
|
54
|
-
* NB the cache is keyed by request id, NOT by contract address: a caller
|
|
55
|
-
* contract's state grows as it stores new requests, so caching its state would
|
|
56
|
-
* make the resolver blind to later requests from the same caller. Caching the
|
|
57
|
-
* immutable resolved record instead is the same pattern
|
|
58
|
-
* {@link SignetRequestResponseReader.getSignatureRequest} uses.
|
|
59
|
-
*/
|
|
60
|
-
export class SignetRequestResolver {
|
|
61
|
-
private readonly source: SignetPublicStateSource;
|
|
62
|
-
|
|
63
|
-
// Resolved records never change; cache them so a redelivered notification for
|
|
64
|
-
// the same request id does not re-query the caller's state.
|
|
65
|
-
private readonly resolvedCache = new Map<RequestIdHex, ResolvedSignetRequest>();
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* @param config - The state source to read caller ledgers through.
|
|
69
|
-
*/
|
|
70
|
-
constructor(config: SignetRequestResolverConfig) {
|
|
71
|
-
this.source = config.source;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Resolve a notification to its authenticated request, or `undefined` when it
|
|
76
|
-
* cannot be trusted: the caller contract has no state, or `requestId` is not
|
|
77
|
-
* a member of the index at `requestsIndexField` (forged, stale, wrong field,
|
|
78
|
-
* or not yet indexed — poll again). Never throws on an untrusted
|
|
79
|
-
* notification; a bad one is dropped, not surfaced as an error.
|
|
80
|
-
*
|
|
81
|
-
* @param notification - The decoded notification.
|
|
82
|
-
* @returns The authenticated request, or `undefined` to drop the notification.
|
|
83
|
-
*/
|
|
84
|
-
async resolve(
|
|
85
|
-
notification: SignBidirectionalNotification,
|
|
86
|
-
): Promise<ResolvedSignetRequest | undefined> {
|
|
87
|
-
const cached = this.resolvedCache.get(notification.requestId);
|
|
88
|
-
if (cached !== undefined) {
|
|
89
|
-
return cached;
|
|
90
|
-
}
|
|
91
|
-
let state: { data: RawContractState } | null;
|
|
92
|
-
try {
|
|
93
|
-
state = await this.source.queryContractState(notification.callerAddress);
|
|
94
|
-
} catch {
|
|
95
|
-
return undefined; // caller address not a contract / transient read error
|
|
96
|
-
}
|
|
97
|
-
if (!state?.data) {
|
|
98
|
-
return undefined; // no state at the named caller — cannot authenticate
|
|
99
|
-
}
|
|
100
|
-
const request = lookupSignetRequestAt(
|
|
101
|
-
state.data,
|
|
102
|
-
notification.requestsIndexField,
|
|
103
|
-
notification.requestId,
|
|
104
|
-
);
|
|
105
|
-
if (request === undefined) {
|
|
106
|
-
return undefined; // membership check failed — drop the notification
|
|
107
|
-
}
|
|
108
|
-
const resolved: ResolvedSignetRequest = {
|
|
109
|
-
callerAddress: notification.callerAddress,
|
|
110
|
-
requestId: notification.requestId,
|
|
111
|
-
request,
|
|
112
|
-
};
|
|
113
|
-
this.resolvedCache.set(notification.requestId, resolved);
|
|
114
|
-
return resolved;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
@@ -1,324 +0,0 @@
|
|
|
1
|
-
// One-stop client-side reader for the signet request/response flow: fetch a
|
|
2
|
-
// request record from the requester contract's ledger, enumerate the posts in
|
|
3
|
-
// the signet contract's signature response log, and verify each candidate
|
|
4
|
-
// against the request.
|
|
5
|
-
// This is the helper the Signet.compact "Response Ledger Layout" comment
|
|
6
|
-
// promises — the log is UNAUTHENTICATED, so a client must verify every post
|
|
7
|
-
// and take the first valid one; this class packages that flow so every
|
|
8
|
-
// consumer (CLI poller, integration tests, a future UI) shares one
|
|
9
|
-
// implementation. Single-shot by design: each call queries state once; the
|
|
10
|
-
// caller owns any poll loop.
|
|
11
|
-
|
|
12
|
-
import type { PublicDataProvider } from "@midnight-ntwrk/midnight-js-types";
|
|
13
|
-
import type { Transaction } from "ethers";
|
|
14
|
-
|
|
15
|
-
import { readSignetRequestsLedgerFromState } from "./signature-requests-state-reader.ts";
|
|
16
|
-
import {
|
|
17
|
-
readSignetContractLedgerFromState,
|
|
18
|
-
signetResponseIndexKey,
|
|
19
|
-
type SignatureResponse,
|
|
20
|
-
type RespondBidirectional,
|
|
21
|
-
} from "./signet-contract-state-reader.ts";
|
|
22
|
-
import { recoverSignatureResponseSigner } from "./signature-response-verification.ts";
|
|
23
|
-
import type { RawContractState } from "./signature-state-reading.ts";
|
|
24
|
-
import {
|
|
25
|
-
signBidirectionalRequestToSignedEVMTransaction,
|
|
26
|
-
signBidirectionalRequestToUnsignedEVMTransaction,
|
|
27
|
-
type SignBidirectionalRequest,
|
|
28
|
-
type RequestIdHex,
|
|
29
|
-
} from "./signet-requests.ts";
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* The least of midnight-js's `PublicDataProvider` the reader needs: raw
|
|
33
|
-
* contract state by address. Declared structurally (rather than a `Pick`) so
|
|
34
|
-
* tests can satisfy it with a plain stub; any full `PublicDataProvider`
|
|
35
|
-
* (e.g. `indexerPublicDataProvider`) is assignable to it.
|
|
36
|
-
*/
|
|
37
|
-
export interface SignetPublicStateSource {
|
|
38
|
-
/**
|
|
39
|
-
* Retrieve the on-chain state of a contract at the latest block.
|
|
40
|
-
*
|
|
41
|
-
* @param contractAddress - The contract address to query.
|
|
42
|
-
* @returns The state (its `data` is the raw ledger tree), or `null` when
|
|
43
|
-
* the address holds no contract.
|
|
44
|
-
*/
|
|
45
|
-
queryContractState(
|
|
46
|
-
contractAddress: Parameters<PublicDataProvider["queryContractState"]>[0],
|
|
47
|
-
): Promise<{ data: RawContractState } | null>;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** Everything a {@link SignetRequestResponseReader} needs to operate. */
|
|
51
|
-
export interface SignetRequestResponseReaderConfig {
|
|
52
|
-
/** Address of the signet-compliant requester contract (e.g. the vault). */
|
|
53
|
-
readonly requesterContractAddress: string;
|
|
54
|
-
/** Address of the central signet contract. */
|
|
55
|
-
readonly signetContractAddress: string;
|
|
56
|
-
/** Source of raw contract state, e.g. midnight-js's `indexerPublicDataProvider`. */
|
|
57
|
-
readonly publicDataProvider: SignetPublicStateSource;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** The verdict on one posted response, in `count` order. */
|
|
61
|
-
export interface SignatureResponseVerdict {
|
|
62
|
-
/** 0-based position of the post in the request's response log. */
|
|
63
|
-
count: bigint;
|
|
64
|
-
/** The posted signature record, verbatim. */
|
|
65
|
-
response: SignatureResponse;
|
|
66
|
-
/** Recovered signer address — absent when the signature did not decode. */
|
|
67
|
-
signer?: string;
|
|
68
|
-
/** Why the post was rejected; absent when the post is valid. */
|
|
69
|
-
rejectedReason?: string;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Result of {@link SignetRequestResponseReader['getVerifiedSignatureResponse']}. */
|
|
73
|
-
export interface VerifiedSignatureResponseResult {
|
|
74
|
-
/**
|
|
75
|
-
* The first valid response (lowest count), or `undefined` when no valid
|
|
76
|
-
* response has been posted yet — poll again.
|
|
77
|
-
*/
|
|
78
|
-
verified?: SignatureResponse;
|
|
79
|
-
/**
|
|
80
|
-
* One verdict per post, count order. Pure data: the reader never logs, so
|
|
81
|
-
* callers decide how to surface rejected posts.
|
|
82
|
-
*/
|
|
83
|
-
verdicts: SignatureResponseVerdict[];
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* Reader over one requester contract / signet contract pair.
|
|
88
|
-
* Construct once per pair and reuse: fetched request records are cached (they
|
|
89
|
-
* are immutable — the ledger key is their hash), so repeated verification
|
|
90
|
-
* calls cost one responses-contract query each.
|
|
91
|
-
*/
|
|
92
|
-
export class SignetRequestResponseReader {
|
|
93
|
-
private readonly config: SignetRequestResponseReaderConfig;
|
|
94
|
-
|
|
95
|
-
// Request records never change once stored; cache them across calls.
|
|
96
|
-
private readonly requestCache = new Map<
|
|
97
|
-
RequestIdHex,
|
|
98
|
-
SignBidirectionalRequest
|
|
99
|
-
>();
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* @param config - The contract pair and state source to read through.
|
|
103
|
-
*/
|
|
104
|
-
constructor(config: SignetRequestResponseReaderConfig) {
|
|
105
|
-
this.config = config;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/**
|
|
109
|
-
* Query one contract's raw state, throwing a uniform error when absent.
|
|
110
|
-
*
|
|
111
|
-
* @param contractAddress - The contract to query.
|
|
112
|
-
* @param role - Human name of the contract for the error message.
|
|
113
|
-
* @returns The raw ledger state tree.
|
|
114
|
-
* @throws Error when the address holds no contract state.
|
|
115
|
-
*/
|
|
116
|
-
private async queryRawState(
|
|
117
|
-
contractAddress: string,
|
|
118
|
-
role: string,
|
|
119
|
-
): Promise<RawContractState> {
|
|
120
|
-
const state =
|
|
121
|
-
await this.config.publicDataProvider.queryContractState(contractAddress);
|
|
122
|
-
if (!state?.data) {
|
|
123
|
-
throw new Error(
|
|
124
|
-
`no state data found for ${role} contract '${contractAddress}' - is it deployed?`,
|
|
125
|
-
);
|
|
126
|
-
}
|
|
127
|
-
return state.data;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Fetch the request record for `requestId` from the requester contract's
|
|
132
|
-
* ledger (request index, field 0 by the signet layout convention). Cached
|
|
133
|
-
* after the first fetch.
|
|
134
|
-
*
|
|
135
|
-
* @param requestId - The request id to look up.
|
|
136
|
-
* @returns The stored request record.
|
|
137
|
-
* @throws Error when the requester contract has no state or holds no
|
|
138
|
-
* request under `requestId`.
|
|
139
|
-
*/
|
|
140
|
-
async getSignatureRequest(
|
|
141
|
-
requestId: RequestIdHex,
|
|
142
|
-
): Promise<SignBidirectionalRequest> {
|
|
143
|
-
const cached = this.requestCache.get(requestId);
|
|
144
|
-
if (cached !== undefined) {
|
|
145
|
-
return cached;
|
|
146
|
-
}
|
|
147
|
-
const raw = await this.queryRawState(
|
|
148
|
-
this.config.requesterContractAddress,
|
|
149
|
-
"requester",
|
|
150
|
-
);
|
|
151
|
-
const { requestsIndex } = readSignetRequestsLedgerFromState(raw);
|
|
152
|
-
const request = requestsIndex.get(requestId);
|
|
153
|
-
if (request === undefined) {
|
|
154
|
-
throw new Error(
|
|
155
|
-
`request ${requestId} is not on the requester contract's ledger — was it submitted?`,
|
|
156
|
-
);
|
|
157
|
-
}
|
|
158
|
-
this.requestCache.set(requestId, request);
|
|
159
|
-
return request;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* Fetch every response posted for `requestId`, in post (count) order.
|
|
164
|
-
* UNVERIFIED — any of them may be garbage; see
|
|
165
|
-
* {@link getVerifiedSignatureResponse}.
|
|
166
|
-
*
|
|
167
|
-
* @param requestId - The request id whose posts to enumerate.
|
|
168
|
-
* @returns The posted payloads, index = count; empty when none yet.
|
|
169
|
-
* @throws Error when the responses contract has no state, or its counter
|
|
170
|
-
* disagrees with the log (inconsistent ledger).
|
|
171
|
-
*/
|
|
172
|
-
async getSignatureResponses(
|
|
173
|
-
requestId: RequestIdHex,
|
|
174
|
-
): Promise<SignatureResponse[]> {
|
|
175
|
-
const raw = await this.queryRawState(
|
|
176
|
-
this.config.signetContractAddress,
|
|
177
|
-
"signet contract",
|
|
178
|
-
);
|
|
179
|
-
const { signatureResponseCounterIndex, signatureResponseIndex } =
|
|
180
|
-
readSignetContractLedgerFromState(raw);
|
|
181
|
-
const totalPosts = signatureResponseCounterIndex.get(requestId) ?? 0n;
|
|
182
|
-
const responses: SignatureResponse[] = [];
|
|
183
|
-
for (let count = 0n; count < totalPosts; count++) {
|
|
184
|
-
const response = signatureResponseIndex.get(
|
|
185
|
-
signetResponseIndexKey(requestId, count),
|
|
186
|
-
);
|
|
187
|
-
if (response === undefined) {
|
|
188
|
-
throw new Error(
|
|
189
|
-
`response log has no entry ${count} for request ${requestId} ` +
|
|
190
|
-
`despite its counter reading ${totalPosts} — ledger state is inconsistent`,
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
responses.push(response);
|
|
194
|
-
}
|
|
195
|
-
return responses;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Fetch and verify the responses posted for `requestId`: each post's
|
|
200
|
-
* `{ bigR, s, recoveryId }` signature must recover to `expectedSigner`
|
|
201
|
-
* (compared case-insensitively) over the signing hash of the transaction
|
|
202
|
-
* the request record describes. The first valid post wins; every post gets
|
|
203
|
-
* a verdict so callers can report the noise.
|
|
204
|
-
*
|
|
205
|
-
* @param requestId - The request id to fetch a verified response for.
|
|
206
|
-
* @param expectedSigner - The EVM address (0x hex, any case) the genuine
|
|
207
|
-
* response must be signed by — the requester's MPC-derived address.
|
|
208
|
-
* @returns The first valid response (if any) plus per-post verdicts.
|
|
209
|
-
* @throws Error when either contract has no state, the request is not on
|
|
210
|
-
* the requester's ledger, or the responses ledger is inconsistent.
|
|
211
|
-
*/
|
|
212
|
-
async getVerifiedSignatureResponse(
|
|
213
|
-
requestId: RequestIdHex,
|
|
214
|
-
expectedSigner: string,
|
|
215
|
-
): Promise<VerifiedSignatureResponseResult> {
|
|
216
|
-
const request = await this.getSignatureRequest(requestId);
|
|
217
|
-
const responses = await this.getSignatureResponses(requestId);
|
|
218
|
-
const verdicts = responses.map(
|
|
219
|
-
(response, index): SignatureResponseVerdict => {
|
|
220
|
-
const count = BigInt(index);
|
|
221
|
-
let signer: string;
|
|
222
|
-
try {
|
|
223
|
-
signer = recoverSignatureResponseSigner(request, response);
|
|
224
|
-
} catch (error) {
|
|
225
|
-
return {
|
|
226
|
-
count,
|
|
227
|
-
response,
|
|
228
|
-
rejectedReason: `not a decodable signature (${String(error)})`,
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
if (signer.toLowerCase() !== expectedSigner.toLowerCase()) {
|
|
232
|
-
return {
|
|
233
|
-
count,
|
|
234
|
-
response,
|
|
235
|
-
signer,
|
|
236
|
-
rejectedReason: `signed by ${signer}, expected ${expectedSigner}`,
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
return { count, response, signer };
|
|
240
|
-
},
|
|
241
|
-
);
|
|
242
|
-
return {
|
|
243
|
-
verified: verdicts.find((v) => v.rejectedReason === undefined)?.response,
|
|
244
|
-
verdicts,
|
|
245
|
-
};
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
/**
|
|
249
|
-
* Rebuild the unsigned EIP-1559 transaction for `requestId` — the exact
|
|
250
|
-
* transaction the MPC signs, assembled from the request record's decomposed
|
|
251
|
-
* fields. No responses-contract query: this needs only the request record
|
|
252
|
-
* (fetched via {@link getSignatureRequest}, cached).
|
|
253
|
-
*
|
|
254
|
-
* @param requestId - The request id whose transaction to rebuild.
|
|
255
|
-
* @returns The unsigned ethers transaction (`unsignedHash` is the MPC's
|
|
256
|
-
* signing digest).
|
|
257
|
-
* @throws Error when the requester contract has no state or holds no
|
|
258
|
-
* request under `requestId`.
|
|
259
|
-
*/
|
|
260
|
-
async getUnsignedEVMTransaction(
|
|
261
|
-
requestId: RequestIdHex,
|
|
262
|
-
): Promise<Transaction> {
|
|
263
|
-
return signBidirectionalRequestToUnsignedEVMTransaction(
|
|
264
|
-
await this.getSignatureRequest(requestId),
|
|
265
|
-
);
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Assemble the broadcast-ready signed EIP-1559 transaction for `requestId`:
|
|
270
|
-
* rebuild the request's transaction and attach the first VERIFIED response
|
|
271
|
-
* signed by `expectedSigner` (see {@link getVerifiedSignatureResponse} — the
|
|
272
|
-
* response log is unauthenticated, so an `expectedSigner` is required and
|
|
273
|
-
* unverified posts are never attached).
|
|
274
|
-
*
|
|
275
|
-
* @param requestId - The request id to produce a signed transaction for.
|
|
276
|
-
* @param expectedSigner - The EVM address (0x hex, any case) the genuine
|
|
277
|
-
* response must be signed by — the requester's MPC-derived address.
|
|
278
|
-
* @returns The signed ethers transaction (`serialized` is the payload for
|
|
279
|
-
* `eth_sendRawTransaction`), or `undefined` when no valid response has
|
|
280
|
-
* been posted yet — poll again.
|
|
281
|
-
* @throws Error when either contract has no state, the request is not on the
|
|
282
|
-
* requester's ledger, or the responses ledger is inconsistent.
|
|
283
|
-
*/
|
|
284
|
-
async getSignedEVMTransaction(
|
|
285
|
-
requestId: RequestIdHex,
|
|
286
|
-
expectedSigner: string,
|
|
287
|
-
): Promise<Transaction | undefined> {
|
|
288
|
-
const { verified } = await this.getVerifiedSignatureResponse(
|
|
289
|
-
requestId,
|
|
290
|
-
expectedSigner,
|
|
291
|
-
);
|
|
292
|
-
if (verified === undefined) {
|
|
293
|
-
return undefined;
|
|
294
|
-
}
|
|
295
|
-
// getSignatureRequest is cached — getVerifiedSignatureResponse already
|
|
296
|
-
// fetched it, so this is a free lookup, not a second query.
|
|
297
|
-
const request = await this.getSignatureRequest(requestId);
|
|
298
|
-
return signBidirectionalRequestToSignedEVMTransaction(request, verified);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
/**
|
|
302
|
-
* Fetch the MPC's respond-bidirectional attestation for `requestId`,
|
|
303
|
-
* if posted. The signet contract verified it IN-CIRCUIT at post time
|
|
304
|
-
* (Schnorr over `(requestId, hash(serializedOutput, outputLen))` against
|
|
305
|
-
* the sealed MPC key), so it is single-slot and needs no off-chain
|
|
306
|
-
* verification or verdicts — `undefined` simply means not posted yet, poll
|
|
307
|
-
* again.
|
|
308
|
-
*
|
|
309
|
-
* @param requestId - The request id whose attestation to fetch.
|
|
310
|
-
* @returns The attestation record, or `undefined` when none is posted.
|
|
311
|
-
* @throws Error when the signet contract has no state on-chain.
|
|
312
|
-
*/
|
|
313
|
-
async getRespondBidirectional(
|
|
314
|
-
requestId: RequestIdHex,
|
|
315
|
-
): Promise<RespondBidirectional | undefined> {
|
|
316
|
-
const raw = await this.queryRawState(
|
|
317
|
-
this.config.signetContractAddress,
|
|
318
|
-
"signet contract",
|
|
319
|
-
);
|
|
320
|
-
return readSignetContractLedgerFromState(raw).respondBidirectionalIndex.get(
|
|
321
|
-
requestId,
|
|
322
|
-
);
|
|
323
|
-
}
|
|
324
|
-
}
|