-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathevent.dart
345 lines (315 loc) · 10.8 KB
/
event.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import 'dart:convert';
import 'package:bip340/bip340.dart' as bip340;
import 'package:convert/convert.dart';
import 'package:nostr/src/utils.dart';
/// The only object type that exists is the event, which has the following format on the wire:
///
/// - "id": "32-bytes hex-encoded sha256 of the the serialized event data"
/// - "pubkey": "32-bytes hex-encoded public key of the event creator",
/// - "created_at": unix timestamp in seconds,
/// - "kind": integer,
/// - "tags": [
/// ["e", "32-bytes hex of the id of another event", "recommended relay URL"],
/// ["p", "32-bytes hex of the key", "recommended relay URL"]
/// ],
/// - "content": "arbitrary string",
/// - "sig": "64-bytes signature of the sha256 hash of the serialized event data, which is the same as the 'id' field"
class Event {
/// 32-bytes hex-encoded sha256 of the the serialized event data (hex)
late String id;
/// 32-bytes hex-encoded public key of the event creator (hex)
late String pubkey;
/// unix timestamp in seconds
late int createdAt;
/// - 0: set_metadata: the content is set to a stringified JSON object {name: username, about: string, picture: url} describing the user who created the event. A relay may delete past set_metadata events once it gets a new one for the same pubkey.
/// - 1: text_note: the content is set to the text content of a note (anything the user wants to say). Non-plaintext notes should instead use kind 1000-10000 as described in NIP-16.
/// - 2: recommend_server: the content is set to the URL (e.g., wss://somerelay.com) of a relay the event creator wants to recommend to its followers.
late int kind;
/// The tags array can store a tag identifier as the first element of each subarray, plus arbitrary information afterward (always as strings).
///
/// This NIP defines "p" — meaning "pubkey", which points to a pubkey of someone that is referred to in the event —, and "e" — meaning "event", which points to the id of an event this event is quoting, replying to or referring to somehow.
late List<List<String>> tags;
/// arbitrary string
String content = "";
/// 64-bytes signature of the sha256 hash of the serialized event data, which is the same as the "id" field
late String sig;
/// subscription_id is a random string that should be used to represent a subscription.
String? subscriptionId;
/// Default constructor
///
/// verify: ensure your event isValid() –> id, signature, timestamp…
///
///```dart
/// String id =
/// "4b697394206581b03ca5222b37449a9cdca1741b122d78defc177444e2536f49";
/// String pubKey =
/// "981cc2078af05b62ee1f98cff325aac755bf5c5836a265c254447b5933c6223b";
/// int createdAt = 1672175320;
/// int kind = 1;
/// List<List<String>> tags = [];
/// String content = "Ceci est une analyse du websocket";
/// String sig =
/// "797c47bef50eff748b8af0f38edcb390facf664b2367d72eb71c50b5f37bc83c4ae9cc9007e8489f5f63c66a66e101fd1515d0a846385953f5f837efb9afe885";
///
/// Event event = Event(
/// id,
/// pubKey,
/// createdAt,
/// kind,
/// tags,
/// content,
/// sig,
/// verify: true,
/// subscriptionId: null,
/// );
///```
Event(
this.id,
this.pubkey,
this.createdAt,
this.kind,
this.tags,
this.content,
this.sig, {
this.subscriptionId,
bool verify = true,
}) {
pubkey = pubkey.toLowerCase();
if (verify && isValid() == false) throw Exception('Invalid event');
}
/// Partial constructor, you have to fill the fields yourself
///
/// verify: ensure your event isValid() –> id, signature, timestamp…
///
/// ```dart
/// var partialEvent = Event.partial();
/// assert(partialEvent.isValid() == false);
/// partialEvent.createdAt = currentUnixTimestampSeconds();
/// partialEvent.pubkey =
/// "981cc2078af05b62ee1f98cff325aac755bf5c5836a265c254447b5933c6223b";
/// partialEvent.id = partialEvent.getEventId();
/// partialEvent.sig = partialEvent.getSignature(
/// "5ee1c8000ab28edd64d74a7d951ac2dd559814887b1b9e1ac7c5f89e96125c12",
/// );
/// assert(partialEvent.isValid() == true);
/// ```
factory Event.partial({
String id = "",
String pubkey = "",
int createdAt = 0,
int kind = 1,
List<List<String>> tags = const <List<String>>[],
String content = "",
String sig = "",
String? subscriptionId,
bool verify = false,
}) {
return Event(
id,
pubkey,
createdAt,
kind,
tags,
content,
sig,
verify: verify,
subscriptionId: subscriptionId,
);
}
/// Instantiate Event object from the minimum needed data
///
/// ```dart
///Event event = Event.from(
/// kind: 1,
/// content: "",
/// privkey:
/// "5ee1c8000ab28edd64d74a7d951ac2dd559814887b1b9e1ac7c5f89e96125c12",
///);
///```
factory Event.from({
required int kind,
required String content,
required String privkey,
int? createdAt,
List<List<String>> tags = const [],
String? pubkey,
String? subscriptionId,
bool verify = false,
}) {
createdAt ??= currentUnixTimestampSeconds();
pubkey ??= bip340.getPublicKey(privkey).toLowerCase();
final id = _processEventId(pubkey, createdAt, kind, tags, content);
final sig = _processSignature(privkey, id);
return Event(
id,
pubkey,
createdAt,
kind,
tags,
content,
sig,
subscriptionId: subscriptionId,
verify: verify,
);
}
/// Deserialize an event from a JSON
///
/// `verify`: ensure the signature is valid, `true` by default.
///
/// `verify` to `false` deserialize faster.
///
/// Throws an [Exception] if any required field is missing.
factory Event.fromMap(Map<String, dynamic> map, {bool verify = true}) {
final id = getRequiredField<String>(map, 'id');
final sig = getRequiredField<String>(map, 'sig');
final pubkey = getRequiredField<String>(map, 'pubkey');
final createdAt = getRequiredField<int>(map, 'created_at');
final kind = getRequiredField<int>(map, 'kind');
final content = getRequiredField<String>(map, 'content');
final rawTags = getRequiredField<List>(map, 'tags');
var tags = [<String>[]];
try {
tags = rawTags
.map((e) => (e as List<dynamic>).map((e) => e as String).toList())
.toList();
} catch (e) {
throw Exception("Invalid 'tags' format: $e");
}
return Event(
id,
pubkey,
createdAt,
kind,
tags,
content,
sig,
verify: verify,
);
}
factory Event.fromJson(String payload, {bool verify = true}) =>
Event.fromMap(json.decode(payload), verify: verify);
/// Serialize an event as map
Map<String, dynamic> toMap() => {
'id': id,
'pubkey': pubkey,
'created_at': createdAt,
'kind': kind,
'tags': tags,
'content': content,
'sig': sig
};
String toJson() => json.encode(toMap());
/// Serialize to nostr event message
/// - ["EVENT", event JSON as defined above]
/// - ["EVENT", subscription_id, event JSON as defined above]
String serialize() {
return json.encode([
"EVENT",
if (subscriptionId != null) subscriptionId,
toMap(),
]);
}
/// Deserialize a nostr event message
/// - ["EVENT", event JSON as defined above]
/// - ["EVENT", subscription_id, event JSON as defined above]
/// ```dart
/// Event event = Event.deserialize([
/// "EVENT",
/// {
/// "id": "67bd60e47d7fdddadebff890143167bcd7b5d28b2c3008eae40e0ac5ba0e6b34",
/// "kind": 1,
/// "pubkey":
/// "36685fa5106b1bc03ae7bea82eded855d8f56c41db4c8bdef8099e1e0f2b2afa",
/// "created_at": 1674403511,
/// "content":
/// "Block 773103 was just confirmed. The total value of all the non-coinbase outputs was 61,549,183,849 sats, or \$14,025,828",
/// "tags": [],
/// "sig":
/// "4912a6850a711a876fd2443771f69e094041f7e832df65646a75c2c77989480cce9b41aa5ea3d055c16fe5beb7d11d3d5fa29b4c4046c150b09393c4d3d16eb4"
/// }
/// ]);
/// ```
factory Event.deserialize(String input, {bool verify = true}) {
final data = json.decode(input);
Map<String, dynamic> event;
String? subscriptionId;
if (data.length == 2) {
event = data[1] as Map<String, dynamic>;
} else if (data.length == 3) {
event = data[2] as Map<String, dynamic>;
subscriptionId = data[1] as String;
} else {
throw Exception('invalid payload');
}
final List<List<String>> tags = (event['tags'] as List<dynamic>)
.map((e) => (e as List<dynamic>).map((e) => e as String).toList())
.toList();
return Event(
event['id'],
event['pubkey'],
event['created_at'],
event['kind'],
tags,
event['content'],
event['sig'],
subscriptionId: subscriptionId,
verify: verify,
);
}
/// To obtain the event.id, we sha256 the serialized event.
/// The serialization is done over the UTF-8 JSON-serialized string (with no white space or line breaks) of the following structure:
///
///[
/// 0,
/// `pubkey`, as a (lowercase) hex string,
/// `created_at`, as a number,
/// `kind`, as a number,
/// `tags`, as an array of arrays of non-null strings,
/// `content`, as a strin>
///]
String getEventId() {
// Included for minimum breaking changes
return _processEventId(
pubkey,
createdAt,
kind,
tags,
content,
);
}
// Support for [getEventId]
static String _processEventId(
String pubkey,
int createdAt,
int kind,
List<List<String>> tags,
String content,
) {
final data = [0, pubkey.toLowerCase(), createdAt, kind, tags, content];
final serializedEvent = json.encode(data);
final hash = sha256(utf8.encode(serializedEvent));
return hex.encode(hash);
}
/// Each user has a keypair. Signatures, public key, and encodings are done according to the Schnorr signatures standard for the curve secp256k1
/// 64-bytes signature of the sha256 hash of the serialized event data, which is the same as the "id" field
String getSignature(String secretKey) => _processSignature(secretKey, id);
// Support for [getSignature]
static String _processSignature(String secretKey, String id) {
/// aux must be 32-bytes random bytes, generated at signature time.
/// https://github.com/nbd-wtf/dart-bip340/blob/master/lib/src/bip340.dart#L10
final String aux = generate64RandomHexChars();
return bip340.sign(secretKey, id, aux);
}
/// Verify if event checks such as id, signature, non-futuristic are valid
/// Performances could be a reason to disable event checks
bool isValid() {
final String verifyId = getEventId();
if (createdAt.toString().length == 10 &&
id == verifyId &&
bip340.verify(pubkey, id, sig)) {
return true;
} else {
return false;
}
}
}