@waku/core 0.0.36-6d86b6f.0 → 0.0.36-76fb1ea.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.
Files changed (72) hide show
  1. package/bundle/{base_protocol-DvQrudwy.js → base_protocol-DbwKyDLW.js} +1 -1
  2. package/bundle/{index-CTo1my9M.js → index-JnhMR9ZE.js} +20 -1
  3. package/bundle/index.js +510 -58
  4. package/bundle/lib/base_protocol.js +2 -2
  5. package/bundle/lib/message/version_0.js +2 -2
  6. package/bundle/{version_0-CiYGrPc2.js → version_0-sWyv9XWm.js} +920 -185
  7. package/dist/.tsbuildinfo +1 -1
  8. package/dist/index.d.ts +2 -0
  9. package/dist/index.js +2 -0
  10. package/dist/index.js.map +1 -1
  11. package/dist/lib/connection_manager/connection_manager.d.ts +1 -1
  12. package/dist/lib/connection_manager/connection_manager.js +1 -1
  13. package/dist/lib/filter/filter.d.ts +4 -2
  14. package/dist/lib/filter/filter.js +21 -3
  15. package/dist/lib/filter/filter.js.map +1 -1
  16. package/dist/lib/light_push/index.d.ts +5 -1
  17. package/dist/lib/light_push/index.js +5 -1
  18. package/dist/lib/light_push/index.js.map +1 -1
  19. package/dist/lib/light_push/light_push.d.ts +3 -4
  20. package/dist/lib/light_push/light_push.js +12 -21
  21. package/dist/lib/light_push/light_push.js.map +1 -1
  22. package/dist/lib/light_push/light_push_v3.d.ts +9 -0
  23. package/dist/lib/light_push/light_push_v3.js +171 -0
  24. package/dist/lib/light_push/light_push_v3.js.map +1 -0
  25. package/dist/lib/light_push/push_rpc.d.ts +1 -1
  26. package/dist/lib/light_push/push_rpc.js.map +1 -1
  27. package/dist/lib/light_push/push_rpc_v2.d.ts +11 -0
  28. package/dist/lib/light_push/push_rpc_v2.js +32 -0
  29. package/dist/lib/light_push/push_rpc_v2.js.map +1 -0
  30. package/dist/lib/light_push/push_rpc_v3.d.ts +11 -0
  31. package/dist/lib/light_push/push_rpc_v3.js +33 -0
  32. package/dist/lib/light_push/push_rpc_v3.js.map +1 -0
  33. package/dist/lib/light_push/status_codes.d.ts +14 -0
  34. package/dist/lib/light_push/status_codes.js +49 -0
  35. package/dist/lib/light_push/status_codes.js.map +1 -0
  36. package/dist/lib/light_push/status_codes_v3.d.ts +4 -0
  37. package/dist/lib/light_push/status_codes_v3.js +53 -0
  38. package/dist/lib/light_push/status_codes_v3.js.map +1 -0
  39. package/dist/lib/light_push/utils.d.ts +6 -0
  40. package/dist/lib/light_push/utils.js +41 -0
  41. package/dist/lib/light_push/utils.js.map +1 -1
  42. package/dist/lib/message/version_0.d.ts +2 -3
  43. package/dist/lib/message/version_0.js +1 -4
  44. package/dist/lib/message/version_0.js.map +1 -1
  45. package/dist/lib/message_hash/index.d.ts +1 -0
  46. package/dist/lib/message_hash/index.js +2 -0
  47. package/dist/lib/message_hash/index.js.map +1 -0
  48. package/dist/lib/message_hash/message_hash.d.ts +52 -0
  49. package/dist/lib/message_hash/message_hash.js +84 -0
  50. package/dist/lib/message_hash/message_hash.js.map +1 -0
  51. package/dist/lib/store/rpc.js +16 -10
  52. package/dist/lib/store/rpc.js.map +1 -1
  53. package/dist/lib/store/store.js +12 -2
  54. package/dist/lib/store/store.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/index.ts +7 -0
  57. package/src/lib/connection_manager/connection_manager.ts +1 -1
  58. package/src/lib/filter/filter.ts +33 -6
  59. package/src/lib/light_push/index.ts +22 -1
  60. package/src/lib/light_push/light_push.ts +19 -25
  61. package/src/lib/light_push/light_push_v3.ts +232 -0
  62. package/src/lib/light_push/push_rpc.ts +1 -1
  63. package/src/lib/light_push/push_rpc_v2.ts +38 -0
  64. package/src/lib/light_push/push_rpc_v3.ts +46 -0
  65. package/src/lib/light_push/status_codes.ts +71 -0
  66. package/src/lib/light_push/status_codes_v3.ts +80 -0
  67. package/src/lib/light_push/utils.ts +57 -0
  68. package/src/lib/message/version_0.ts +3 -7
  69. package/src/lib/message_hash/index.ts +1 -0
  70. package/src/lib/message_hash/message_hash.ts +106 -0
  71. package/src/lib/store/rpc.ts +23 -19
  72. package/src/lib/store/store.ts +13 -1
@@ -0,0 +1,232 @@
1
+ import type { PeerId, Stream } from "@libp2p/interface";
2
+ import {
3
+ type CoreProtocolResult,
4
+ type IBaseProtocolCore,
5
+ type IEncoder,
6
+ type IMessage,
7
+ isSuccessStatusCodeV3,
8
+ type Libp2p,
9
+ LightPushCodecV3,
10
+ LightPushStatusCodeV3,
11
+ ProtocolError,
12
+ PubsubTopic,
13
+ type ThisOrThat
14
+ } from "@waku/interfaces";
15
+ import { proto_lightpush_v3, WakuMessage } from "@waku/proto";
16
+ import { isMessageSizeUnderCap } from "@waku/utils";
17
+ import { Logger } from "@waku/utils";
18
+ import all from "it-all";
19
+ import * as lp from "it-length-prefixed";
20
+ import { pipe } from "it-pipe";
21
+ import { Uint8ArrayList } from "uint8arraylist";
22
+
23
+ import { BaseProtocol } from "../base_protocol.js";
24
+
25
+ import { PushRpcV3 } from "./push_rpc_v3.js";
26
+ import {
27
+ getLightPushStatusDescriptionV3,
28
+ lightPushStatusCodeToProtocolErrorV3
29
+ } from "./status_codes_v3.js";
30
+ import { isRLNResponseError } from "./utils.js";
31
+
32
+ const log = new Logger("light-push-v3");
33
+
34
+ type PreparePushMessageResult = ThisOrThat<"query", PushRpcV3>;
35
+
36
+ export class LightPushCoreV3 extends BaseProtocol implements IBaseProtocolCore {
37
+ public constructor(
38
+ public readonly pubsubTopics: PubsubTopic[],
39
+ libp2p: Libp2p
40
+ ) {
41
+ super(LightPushCodecV3, libp2p.components, pubsubTopics);
42
+ }
43
+
44
+ private async preparePushMessage(
45
+ encoder: IEncoder,
46
+ message: IMessage
47
+ ): Promise<PreparePushMessageResult> {
48
+ try {
49
+ if (!message.payload || message.payload.length === 0) {
50
+ log.error("Failed to send waku light push: payload is empty");
51
+ return { query: null, error: ProtocolError.EMPTY_PAYLOAD };
52
+ }
53
+
54
+ if (!(await isMessageSizeUnderCap(encoder, message))) {
55
+ log.error("Failed to send waku light push: message is bigger than 1MB");
56
+ return { query: null, error: ProtocolError.SIZE_TOO_BIG };
57
+ }
58
+
59
+ const protoMessage = await encoder.toProtoObj(message);
60
+ if (!protoMessage) {
61
+ log.error("Failed to encode to protoMessage, aborting push");
62
+ return {
63
+ query: null,
64
+ error: ProtocolError.ENCODE_FAILED
65
+ };
66
+ }
67
+
68
+ const query = PushRpcV3.createRequest(
69
+ protoMessage as WakuMessage,
70
+ encoder.pubsubTopic
71
+ );
72
+ return { query, error: null };
73
+ } catch (error) {
74
+ log.error("Failed to prepare push message", error);
75
+
76
+ return {
77
+ query: null,
78
+ error: ProtocolError.GENERIC_FAIL
79
+ };
80
+ }
81
+ }
82
+
83
+ public async send(
84
+ encoder: IEncoder,
85
+ message: IMessage,
86
+ peerId: PeerId
87
+ ): Promise<CoreProtocolResult> {
88
+ const { query, error: preparationError } = await this.preparePushMessage(
89
+ encoder,
90
+ message
91
+ );
92
+
93
+ if (preparationError || !query) {
94
+ return {
95
+ success: null,
96
+ failure: {
97
+ error: preparationError,
98
+ peerId
99
+ }
100
+ };
101
+ }
102
+
103
+ let stream: Stream;
104
+ try {
105
+ stream = await this.getStream(peerId);
106
+ } catch (error) {
107
+ log.error("Failed to get stream", error);
108
+ return {
109
+ success: null,
110
+ failure: {
111
+ error: ProtocolError.NO_STREAM_AVAILABLE,
112
+ peerId: peerId
113
+ }
114
+ };
115
+ }
116
+
117
+ let res: Uint8ArrayList[] | undefined;
118
+ try {
119
+ res = await pipe(
120
+ [query.encode()],
121
+ lp.encode,
122
+ stream,
123
+ lp.decode,
124
+ async (source) => await all(source)
125
+ );
126
+ } catch (err) {
127
+ log.error("Failed to send waku light push request", err);
128
+ return {
129
+ success: null,
130
+ failure: {
131
+ error: ProtocolError.STREAM_ABORTED,
132
+ peerId: peerId
133
+ }
134
+ };
135
+ }
136
+
137
+ const bytes = new Uint8ArrayList();
138
+ res.forEach((chunk) => {
139
+ bytes.append(chunk);
140
+ });
141
+
142
+ let response: proto_lightpush_v3.LightpushResponse | undefined;
143
+ try {
144
+ response = proto_lightpush_v3.LightpushResponse.decode(bytes);
145
+ } catch (err) {
146
+ log.error("Failed to decode push response", err);
147
+ return {
148
+ success: null,
149
+ failure: {
150
+ error: ProtocolError.DECODE_FAILED,
151
+ peerId: peerId
152
+ }
153
+ };
154
+ }
155
+
156
+ if (!response) {
157
+ log.error("Remote peer fault: No response received");
158
+ return {
159
+ success: null,
160
+ failure: {
161
+ error: ProtocolError.NO_RESPONSE,
162
+ peerId: peerId
163
+ }
164
+ };
165
+ }
166
+
167
+ // Validate request ID matches (except for rate limiting responses)
168
+ if (response.requestId !== query.query?.requestId) {
169
+ // nwaku sends "N/A" for rate limiting responses
170
+ if (response.statusCode !== LightPushStatusCodeV3.TOO_MANY_REQUESTS) {
171
+ log.error("Request ID mismatch", {
172
+ sent: query.query?.requestId,
173
+ received: response.requestId
174
+ });
175
+ return {
176
+ success: null,
177
+ failure: {
178
+ error: ProtocolError.GENERIC_FAIL,
179
+ peerId: peerId
180
+ }
181
+ };
182
+ }
183
+ }
184
+
185
+ const statusCode = response.statusCode;
186
+ const isSuccess = isSuccessStatusCodeV3(statusCode);
187
+
188
+ // Special handling for nwaku rate limiting
189
+ if (statusCode === LightPushStatusCodeV3.TOO_MANY_REQUESTS) {
190
+ if (response.requestId === "N/A") {
191
+ log.warn("Rate limited by nwaku node", {
192
+ statusDesc:
193
+ response.statusDesc || "Request rejected due to too many requests"
194
+ });
195
+ }
196
+ }
197
+
198
+ if (response.relayPeerCount !== undefined) {
199
+ log.info(`Message relayed to ${response.relayPeerCount} peers`);
200
+ }
201
+
202
+ if (response.statusDesc && isRLNResponseError(response.statusDesc)) {
203
+ log.error("Remote peer fault: RLN generation");
204
+ return {
205
+ success: null,
206
+ failure: {
207
+ error: ProtocolError.RLN_PROOF_GENERATION,
208
+ peerId: peerId
209
+ }
210
+ };
211
+ }
212
+
213
+ if (!isSuccess) {
214
+ const errorMessage = getLightPushStatusDescriptionV3(
215
+ statusCode,
216
+ response.statusDesc
217
+ );
218
+ log.error("Remote peer rejected the message: ", errorMessage);
219
+
220
+ const protocolError = lightPushStatusCodeToProtocolErrorV3(statusCode);
221
+ return {
222
+ success: null,
223
+ failure: {
224
+ error: protocolError,
225
+ peerId: peerId
226
+ }
227
+ };
228
+ }
229
+
230
+ return { success: peerId, failure: null };
231
+ }
232
+ }
@@ -7,7 +7,7 @@ export class PushRpc {
7
7
 
8
8
  public static createRequest(
9
9
  message: proto.WakuMessage,
10
- pubsubTopic: string
10
+ pubsubTopic?: string
11
11
  ): PushRpc {
12
12
  return new PushRpc({
13
13
  requestId: uuid(),
@@ -0,0 +1,38 @@
1
+ import { proto_lightpush_v2 as proto } from "@waku/proto";
2
+ import type { Uint8ArrayList } from "uint8arraylist";
3
+ import { v4 as uuid } from "uuid";
4
+
5
+ export class PushRpcV2 {
6
+ public constructor(public proto: proto.PushRpc) {}
7
+
8
+ public static createRequest(
9
+ message: proto.WakuMessage,
10
+ pubsubTopic: string
11
+ ): PushRpcV2 {
12
+ return new PushRpcV2({
13
+ requestId: uuid(),
14
+ request: {
15
+ message: message,
16
+ pubsubTopic: pubsubTopic
17
+ },
18
+ response: undefined
19
+ });
20
+ }
21
+
22
+ public static decode(bytes: Uint8ArrayList): PushRpcV2 {
23
+ const res = proto.PushRpc.decode(bytes);
24
+ return new PushRpcV2(res);
25
+ }
26
+
27
+ public encode(): Uint8Array {
28
+ return proto.PushRpc.encode(this.proto);
29
+ }
30
+
31
+ public get query(): proto.PushRequest | undefined {
32
+ return this.proto.request;
33
+ }
34
+
35
+ public get response(): proto.PushResponse | undefined {
36
+ return this.proto.response;
37
+ }
38
+ }
@@ -0,0 +1,46 @@
1
+ import { proto_lightpush_v3, WakuMessage } from "@waku/proto";
2
+ import type { Uint8ArrayList } from "uint8arraylist";
3
+ import { v4 as uuid } from "uuid";
4
+
5
+ export class PushRpcV3 {
6
+ public request?: proto_lightpush_v3.LightpushRequest;
7
+ public response?: proto_lightpush_v3.LightpushResponse;
8
+
9
+ private constructor(
10
+ request?: proto_lightpush_v3.LightpushRequest,
11
+ response?: proto_lightpush_v3.LightpushResponse
12
+ ) {
13
+ this.request = request;
14
+ this.response = response;
15
+ }
16
+
17
+ public static createRequest(
18
+ message: WakuMessage,
19
+ pubsubTopic?: string
20
+ ): PushRpcV3 {
21
+ const request: proto_lightpush_v3.LightpushRequest = {
22
+ requestId: uuid(),
23
+ message: message,
24
+ // Only include pubsubTopic if explicitly provided (for nwaku autosharding compatibility)
25
+ ...(pubsubTopic && { pubsubTopic })
26
+ };
27
+
28
+ return new PushRpcV3(request, undefined);
29
+ }
30
+
31
+ public static decode(bytes: Uint8ArrayList | Uint8Array): PushRpcV3 {
32
+ const response = proto_lightpush_v3.LightpushResponse.decode(bytes);
33
+ return new PushRpcV3(undefined, response);
34
+ }
35
+
36
+ public encode(): Uint8Array {
37
+ if (!this.request) {
38
+ throw new Error("Cannot encode without a request");
39
+ }
40
+ return proto_lightpush_v3.LightpushRequest.encode(this.request);
41
+ }
42
+
43
+ public get query(): proto_lightpush_v3.LightpushRequest | undefined {
44
+ return this.request;
45
+ }
46
+ }
@@ -0,0 +1,71 @@
1
+ import { ProtocolError } from "@waku/interfaces";
2
+
3
+ export enum LightPushStatusCode {
4
+ SUCCESS = 200,
5
+ BAD_REQUEST = 400,
6
+ UNSUPPORTED_PUBSUB_TOPIC = 404,
7
+ REQUEST_TOO_LARGE = 413,
8
+ TOO_MANY_REQUESTS = 429,
9
+ INTERNAL_SERVER_ERROR = 500,
10
+ NO_PEERS_TO_RELAY = 503
11
+ }
12
+
13
+ export function lightPushStatusCodeToProtocolError(
14
+ statusCode: number
15
+ ): ProtocolError | null {
16
+ switch (statusCode) {
17
+ case LightPushStatusCode.SUCCESS:
18
+ return null;
19
+
20
+ case LightPushStatusCode.BAD_REQUEST:
21
+ return ProtocolError.GENERIC_FAIL;
22
+
23
+ case LightPushStatusCode.UNSUPPORTED_PUBSUB_TOPIC:
24
+ return ProtocolError.TOPIC_NOT_CONFIGURED;
25
+
26
+ case LightPushStatusCode.REQUEST_TOO_LARGE:
27
+ return ProtocolError.SIZE_TOO_BIG;
28
+
29
+ case LightPushStatusCode.TOO_MANY_REQUESTS:
30
+ return ProtocolError.GENERIC_FAIL;
31
+
32
+ case LightPushStatusCode.INTERNAL_SERVER_ERROR:
33
+ return ProtocolError.REMOTE_PEER_REJECTED;
34
+
35
+ case LightPushStatusCode.NO_PEERS_TO_RELAY:
36
+ return ProtocolError.NO_PEER_AVAILABLE;
37
+
38
+ default:
39
+ return ProtocolError.REMOTE_PEER_REJECTED;
40
+ }
41
+ }
42
+
43
+ export const lightPushStatusDescriptions: Record<number, string> = {
44
+ [LightPushStatusCode.SUCCESS]: "Message pushed successfully",
45
+ [LightPushStatusCode.BAD_REQUEST]:
46
+ "Invalid request format or missing required fields",
47
+ [LightPushStatusCode.UNSUPPORTED_PUBSUB_TOPIC]:
48
+ "The specified pubsub topic is not supported",
49
+ [LightPushStatusCode.REQUEST_TOO_LARGE]:
50
+ "Message size exceeds maximum allowed size",
51
+ [LightPushStatusCode.TOO_MANY_REQUESTS]:
52
+ "Rate limit exceeded, too many requests",
53
+ [LightPushStatusCode.INTERNAL_SERVER_ERROR]: "Internal server error occurred",
54
+ [LightPushStatusCode.NO_PEERS_TO_RELAY]:
55
+ "No relay peers available to forward the message"
56
+ };
57
+
58
+ export function isSuccessStatusCode(statusCode: number): boolean {
59
+ return statusCode === LightPushStatusCode.SUCCESS;
60
+ }
61
+
62
+ export function getLightPushStatusDescription(
63
+ statusCode: number,
64
+ statusDesc?: string
65
+ ): string {
66
+ return (
67
+ statusDesc ||
68
+ lightPushStatusDescriptions[statusCode] ||
69
+ `Unknown status code: ${statusCode}`
70
+ );
71
+ }
@@ -0,0 +1,80 @@
1
+ import { LightPushStatusCodeV3, ProtocolError } from "@waku/interfaces";
2
+
3
+ export const lightPushStatusDescriptionsV3: Record<
4
+ LightPushStatusCodeV3,
5
+ string
6
+ > = {
7
+ [LightPushStatusCodeV3.SUCCESS]: "Message sent successfully",
8
+ [LightPushStatusCodeV3.BAD_REQUEST]: "Bad request format",
9
+ [LightPushStatusCodeV3.PAYLOAD_TOO_LARGE]:
10
+ "Message payload exceeds maximum size",
11
+ [LightPushStatusCodeV3.INVALID_MESSAGE_ERROR]: "Message validation failed",
12
+ [LightPushStatusCodeV3.UNSUPPORTED_PUBSUB_TOPIC]: "Unsupported pubsub topic",
13
+ [LightPushStatusCodeV3.TOO_MANY_REQUESTS]: "Rate limit exceeded",
14
+ [LightPushStatusCodeV3.INTERNAL_SERVER_ERROR]: "Internal server error",
15
+ [LightPushStatusCodeV3.SERVICE_NOT_AVAILABLE]:
16
+ "Service temporarily unavailable",
17
+ [LightPushStatusCodeV3.OUT_OF_RLN_PROOF]: "RLN proof generation failed",
18
+ [LightPushStatusCodeV3.NO_PEERS_TO_RELAY]: "No relay peers available"
19
+ };
20
+
21
+ export function lightPushStatusCodeToProtocolErrorV3(
22
+ statusCode: LightPushStatusCodeV3 | number | undefined
23
+ ): ProtocolError {
24
+ if (!statusCode) {
25
+ return ProtocolError.GENERIC_FAIL;
26
+ }
27
+
28
+ switch (statusCode) {
29
+ case LightPushStatusCodeV3.SUCCESS:
30
+ return ProtocolError.GENERIC_FAIL;
31
+
32
+ case LightPushStatusCodeV3.BAD_REQUEST:
33
+ return ProtocolError.DECODE_FAILED;
34
+
35
+ case LightPushStatusCodeV3.PAYLOAD_TOO_LARGE:
36
+ return ProtocolError.SIZE_TOO_BIG;
37
+
38
+ case LightPushStatusCodeV3.INVALID_MESSAGE_ERROR:
39
+ return ProtocolError.EMPTY_PAYLOAD;
40
+
41
+ case LightPushStatusCodeV3.UNSUPPORTED_PUBSUB_TOPIC:
42
+ return ProtocolError.TOPIC_NOT_CONFIGURED;
43
+
44
+ case LightPushStatusCodeV3.TOO_MANY_REQUESTS:
45
+ return ProtocolError.REMOTE_PEER_REJECTED;
46
+
47
+ case LightPushStatusCodeV3.INTERNAL_SERVER_ERROR:
48
+ return ProtocolError.GENERIC_FAIL;
49
+
50
+ case LightPushStatusCodeV3.SERVICE_NOT_AVAILABLE:
51
+ return ProtocolError.NO_PEER_AVAILABLE;
52
+
53
+ case LightPushStatusCodeV3.OUT_OF_RLN_PROOF:
54
+ return ProtocolError.RLN_PROOF_GENERATION;
55
+
56
+ case LightPushStatusCodeV3.NO_PEERS_TO_RELAY:
57
+ return ProtocolError.NO_PEER_AVAILABLE;
58
+
59
+ default:
60
+ return ProtocolError.REMOTE_PEER_REJECTED;
61
+ }
62
+ }
63
+
64
+ export function getLightPushStatusDescriptionV3(
65
+ statusCode: number | undefined,
66
+ customDesc?: string
67
+ ): string {
68
+ if (customDesc) {
69
+ return customDesc;
70
+ }
71
+
72
+ if (!statusCode) {
73
+ return "Unknown error";
74
+ }
75
+
76
+ return (
77
+ lightPushStatusDescriptionsV3[statusCode as LightPushStatusCodeV3] ||
78
+ `Unknown status code: ${statusCode}`
79
+ );
80
+ }
@@ -1,3 +1,5 @@
1
+ import { ProtocolError } from "@waku/interfaces";
2
+
1
3
  // should match nwaku
2
4
  // https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/rln_relay.nim#L309
3
5
  // https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/tests/waku_rln_relay/rln/waku_rln_relay_utils.nim#L20
@@ -21,3 +23,58 @@ export const isRLNResponseError = (info?: string): boolean => {
21
23
  info.includes(RLN_REMOTE_VALIDATION)
22
24
  );
23
25
  };
26
+
27
+ /**
28
+ * Maps error information from push response to appropriate ProtocolError
29
+ * Uses pattern matching to handle various error cases
30
+ */
31
+ export function mapInfoToProtocolError(info?: string): ProtocolError {
32
+ if (!info) {
33
+ return ProtocolError.REMOTE_PEER_REJECTED;
34
+ }
35
+
36
+ const lowerInfo = info.toLowerCase();
37
+
38
+ // RLN errors
39
+ if (isRLNResponseError(info)) {
40
+ return ProtocolError.RLN_PROOF_GENERATION;
41
+ }
42
+
43
+ // Rate limiting patterns
44
+ if (
45
+ lowerInfo.includes("rate limit") ||
46
+ lowerInfo.includes("too many requests")
47
+ ) {
48
+ return ProtocolError.REMOTE_PEER_REJECTED;
49
+ }
50
+
51
+ // Topic errors
52
+ if (
53
+ lowerInfo.includes("topic") &&
54
+ (lowerInfo.includes("not found") || lowerInfo.includes("not configured"))
55
+ ) {
56
+ return ProtocolError.TOPIC_NOT_CONFIGURED;
57
+ }
58
+
59
+ // Size errors
60
+ if (lowerInfo.includes("too large") || lowerInfo.includes("size")) {
61
+ return ProtocolError.SIZE_TOO_BIG;
62
+ }
63
+
64
+ // Decoding errors
65
+ if (
66
+ lowerInfo.includes("decode") ||
67
+ lowerInfo.includes("invalid") ||
68
+ lowerInfo.includes("malformed")
69
+ ) {
70
+ return ProtocolError.DECODE_FAILED;
71
+ }
72
+
73
+ // Empty payload
74
+ if (lowerInfo.includes("empty") && lowerInfo.includes("payload")) {
75
+ return ProtocolError.EMPTY_PAYLOAD;
76
+ }
77
+
78
+ // Default case
79
+ return ProtocolError.REMOTE_PEER_REJECTED;
80
+ }
@@ -22,7 +22,7 @@ export { proto };
22
22
  export class DecodedMessage implements IDecodedMessage {
23
23
  public constructor(
24
24
  public pubsubTopic: string,
25
- protected proto: proto.WakuMessage
25
+ private proto: proto.WakuMessage
26
26
  ) {}
27
27
 
28
28
  public get ephemeral(): boolean {
@@ -37,10 +37,6 @@ export class DecodedMessage implements IDecodedMessage {
37
37
  return this.proto.contentTopic;
38
38
  }
39
39
 
40
- public get _rawTimestamp(): bigint | undefined {
41
- return this.proto.timestamp;
42
- }
43
-
44
40
  public get timestamp(): Date | undefined {
45
41
  // In the case we receive a value that is bigger than JS's max number,
46
42
  // we catch the error and return undefined.
@@ -63,7 +59,7 @@ export class DecodedMessage implements IDecodedMessage {
63
59
  public get version(): number {
64
60
  // https://rfc.vac.dev/spec/14/
65
61
  // > If omitted, the value SHOULD be interpreted as version 0.
66
- return this.proto.version ?? 0;
62
+ return this.proto.version ?? Version;
67
63
  }
68
64
 
69
65
  public get rateLimitProof(): IRateLimitProof | undefined {
@@ -160,7 +156,7 @@ export class Decoder implements IDecoder<IDecodedMessage> {
160
156
  public async fromProtoObj(
161
157
  pubsubTopic: string,
162
158
  proto: IProtoMessage
163
- ): Promise<DecodedMessage | undefined> {
159
+ ): Promise<IDecodedMessage | undefined> {
164
160
  // https://rfc.vac.dev/spec/14/
165
161
  // > If omitted, the value SHOULD be interpreted as version 0.
166
162
  if (proto.version ?? 0 !== Version) {
@@ -0,0 +1 @@
1
+ export { messageHash, messageHashStr } from "./message_hash.js";
@@ -0,0 +1,106 @@
1
+ import { sha256 } from "@noble/hashes/sha256";
2
+ import type { IDecodedMessage, IProtoMessage } from "@waku/interfaces";
3
+ import { isDefined } from "@waku/utils";
4
+ import {
5
+ bytesToHex,
6
+ concat,
7
+ numberToBytes,
8
+ utf8ToBytes
9
+ } from "@waku/utils/bytes";
10
+
11
+ /**
12
+ * Deterministic Message Hashing as defined in
13
+ * [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)
14
+ *
15
+ * Computes a SHA-256 hash of the concatenation of pubsub topic, payload, content topic, meta, and timestamp.
16
+ *
17
+ * @param pubsubTopic - The pubsub topic string
18
+ * @param message - The message to be hashed
19
+ * @returns A Uint8Array containing the SHA-256 hash
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * import { messageHash } from "@waku/core";
24
+ *
25
+ * const pubsubTopic = "/waku/2/default-waku/proto";
26
+ * const message = {
27
+ * payload: new Uint8Array([1, 2, 3, 4]),
28
+ * contentTopic: "/waku/2/default-content/proto",
29
+ * meta: new Uint8Array([5, 6, 7, 8]),
30
+ * timestamp: new Date()
31
+ * };
32
+ *
33
+ * const hash = messageHash(pubsubTopic, message);
34
+ * ```
35
+ */
36
+ export function messageHash(
37
+ pubsubTopic: string,
38
+ message: IProtoMessage | IDecodedMessage
39
+ ): Uint8Array {
40
+ const pubsubTopicBytes = utf8ToBytes(pubsubTopic);
41
+ const contentTopicBytes = utf8ToBytes(message.contentTopic);
42
+ const timestampBytes = tryConvertTimestampToBytes(message.timestamp);
43
+
44
+ const bytes = concat(
45
+ [
46
+ pubsubTopicBytes,
47
+ message.payload,
48
+ contentTopicBytes,
49
+ message.meta,
50
+ timestampBytes
51
+ ].filter(isDefined)
52
+ );
53
+
54
+ return sha256(bytes);
55
+ }
56
+
57
+ function tryConvertTimestampToBytes(
58
+ timestamp: Date | number | bigint | undefined
59
+ ): undefined | Uint8Array {
60
+ if (!timestamp) {
61
+ return;
62
+ }
63
+
64
+ let bigIntTimestamp: bigint;
65
+
66
+ if (typeof timestamp === "bigint") {
67
+ bigIntTimestamp = timestamp;
68
+ } else {
69
+ bigIntTimestamp = BigInt(timestamp.valueOf()) * 1000000n;
70
+ }
71
+
72
+ return numberToBytes(bigIntTimestamp);
73
+ }
74
+
75
+ /**
76
+ * Computes a deterministic message hash and returns it as a hexadecimal string.
77
+ * This is a convenience wrapper around messageHash that converts the result to a hex string.
78
+ *
79
+ * @param pubsubTopic - The pubsub topic string
80
+ * @param message - The message to be hashed
81
+ * @returns A string containing the hex representation of the SHA-256 hash
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * import { messageHashStr } from "@waku/core";
86
+ *
87
+ * const pubsubTopic = "/waku/2/default-waku/proto";
88
+ * const message = {
89
+ * payload: new Uint8Array([1, 2, 3, 4]),
90
+ * contentTopic: "/waku/2/default-content/proto",
91
+ * meta: new Uint8Array([5, 6, 7, 8]),
92
+ * timestamp: new Date()
93
+ * };
94
+ *
95
+ * const hashString = messageHashStr(pubsubTopic, message);
96
+ * console.log(hashString); // e.g. "a1b2c3d4..."
97
+ * ```
98
+ */
99
+ export function messageHashStr(
100
+ pubsubTopic: string,
101
+ message: IProtoMessage | IDecodedMessage
102
+ ): string {
103
+ const hash = messageHash(pubsubTopic, message);
104
+ const hashStr = bytesToHex(hash);
105
+ return hashStr;
106
+ }