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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use crate::{
account_config::{
AdminTransactionEvent, BaseUrlRotationEvent, BurnEvent, CancelBurnEvent,
ComplianceKeyRotationEvent, CreateAccountEvent, MintEvent, NewBlockEvent, NewEpochEvent,
PreburnEvent, ReceivedMintEvent, ReceivedPaymentEvent, SentPaymentEvent,
ToXDXExchangeRateUpdateEvent, VASPDomainEvent,
},
event::EventKey,
ledger_info::LedgerInfo,
proof::EventProof,
transaction::Version,
};
use anyhow::{ensure, Context, Error, Result};
use diem_crypto::hash::CryptoHash;
use diem_crypto_derive::{BCSCryptoHash, CryptoHasher};
use move_core_types::{language_storage::TypeTag, move_resource::MoveStructType};
#[cfg(any(test, feature = "fuzzing"))]
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};
use std::{convert::TryFrom, ops::Deref};
#[derive(Hash, Clone, Eq, PartialEq, Serialize, Deserialize, CryptoHasher, BCSCryptoHash)]
pub enum ContractEvent {
V0(ContractEventV0),
}
impl ContractEvent {
pub fn new(
key: EventKey,
sequence_number: u64,
type_tag: TypeTag,
event_data: Vec<u8>,
) -> Self {
ContractEvent::V0(ContractEventV0::new(
key,
sequence_number,
type_tag,
event_data,
))
}
}
impl Deref for ContractEvent {
type Target = ContractEventV0;
fn deref(&self) -> &Self::Target {
match self {
ContractEvent::V0(event) => event,
}
}
}
#[derive(Hash, Clone, Eq, PartialEq, Serialize, Deserialize, CryptoHasher)]
pub struct ContractEventV0 {
key: EventKey,
sequence_number: u64,
type_tag: TypeTag,
#[serde(with = "serde_bytes")]
event_data: Vec<u8>,
}
impl ContractEventV0 {
pub fn new(
key: EventKey,
sequence_number: u64,
type_tag: TypeTag,
event_data: Vec<u8>,
) -> Self {
Self {
key,
sequence_number,
type_tag,
event_data,
}
}
pub fn key(&self) -> &EventKey {
&self.key
}
pub fn sequence_number(&self) -> u64 {
self.sequence_number
}
pub fn event_data(&self) -> &[u8] {
&self.event_data
}
pub fn type_tag(&self) -> &TypeTag {
&self.type_tag
}
}
impl TryFrom<&ContractEvent> for SentPaymentEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(SentPaymentEvent::struct_tag()) {
anyhow::bail!("Expected Sent Payment")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for ReceivedPaymentEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(ReceivedPaymentEvent::struct_tag()) {
anyhow::bail!("Expected Received Payment")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for ToXDXExchangeRateUpdateEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(ToXDXExchangeRateUpdateEvent::struct_tag()) {
anyhow::bail!("Expected ToXDXExchangeRateUpdateEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for MintEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(MintEvent::struct_tag()) {
anyhow::bail!("Expected MintEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for ReceivedMintEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(ReceivedMintEvent::struct_tag()) {
anyhow::bail!("Expected ReceivedMintEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for BurnEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(BurnEvent::struct_tag()) {
anyhow::bail!("Expected BurnEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for PreburnEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(PreburnEvent::struct_tag()) {
anyhow::bail!("Expected PreburnEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for CancelBurnEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(CancelBurnEvent::struct_tag()) {
anyhow::bail!("Expected CancelBurnEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for AdminTransactionEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(Self::struct_tag()) {
anyhow::bail!("Expected AdminTransactionEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for NewBlockEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(Self::struct_tag()) {
anyhow::bail!("Expected NewBlockEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for NewEpochEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(Self::struct_tag()) {
anyhow::bail!("Expected NewEpochEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for ComplianceKeyRotationEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(Self::struct_tag()) {
anyhow::bail!("Expected ComplianceKeyRotationEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for BaseUrlRotationEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(Self::struct_tag()) {
anyhow::bail!("Expected BaseUrlRotationEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for CreateAccountEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(Self::struct_tag()) {
anyhow::bail!("Expected CreateAccountEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl TryFrom<&ContractEvent> for VASPDomainEvent {
type Error = Error;
fn try_from(event: &ContractEvent) -> Result<Self> {
if event.type_tag != TypeTag::Struct(Self::struct_tag()) {
anyhow::bail!("Expected VASPDomainEvent")
}
Self::try_from_bytes(&event.event_data)
}
}
impl std::fmt::Debug for ContractEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"ContractEvent {{ key: {:?}, index: {:?}, type: {:?}, event_data: {:?} }}",
self.key,
self.sequence_number,
self.type_tag,
hex::encode(&self.event_data)
)
}
}
impl std::fmt::Display for ContractEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Ok(payload) = SentPaymentEvent::try_from(self) {
write!(
f,
"ContractEvent {{ key: {}, index: {:?}, type: {:?}, event_data: {:?} }}",
self.key, self.sequence_number, self.type_tag, payload,
)
} else if let Ok(payload) = ReceivedPaymentEvent::try_from(self) {
write!(
f,
"ContractEvent {{ key: {}, index: {:?}, type: {:?}, event_data: {:?} }}",
self.key, self.sequence_number, self.type_tag, payload,
)
} else {
write!(f, "{:?}", self)
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
pub struct EventWithProof {
pub transaction_version: u64, pub event_index: u64,
pub event: ContractEvent,
pub proof: EventProof,
}
impl std::fmt::Display for EventWithProof {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"EventWithProof {{ \n\ttransaction_version: {}, \n\tevent_index: {}, \
\n\tevent: {}, \n\tproof: {:?} \n}}",
self.transaction_version, self.event_index, self.event, self.proof
)
}
}
impl EventWithProof {
pub fn new(
transaction_version: Version,
event_index: u64,
event: ContractEvent,
proof: EventProof,
) -> Self {
Self {
transaction_version,
event_index,
event,
proof,
}
}
pub fn verify(
&self,
ledger_info: &LedgerInfo,
event_key: &EventKey,
sequence_number: u64,
transaction_version: Version,
event_index: u64,
) -> Result<()> {
ensure!(
self.event.key() == event_key,
"Event key ({}) not expected ({}).",
self.event.key(),
*event_key,
);
ensure!(
self.event.sequence_number == sequence_number,
"Sequence number ({}) not expected ({}).",
self.event.sequence_number(),
sequence_number,
);
ensure!(
self.transaction_version == transaction_version,
"Transaction version ({}) not expected ({}).",
self.transaction_version,
transaction_version,
);
ensure!(
self.event_index == event_index,
"Event index ({}) not expected ({}).",
self.event_index,
event_index,
);
self.proof.verify(
ledger_info,
self.event.hash(),
transaction_version,
event_index,
)?;
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))]
pub struct EventByVersionWithProof {
pub lower_bound_incl: Option<EventWithProof>,
pub upper_bound_excl: Option<EventWithProof>,
}
impl EventByVersionWithProof {
pub fn new(
lower_bound_incl: Option<EventWithProof>,
upper_bound_excl: Option<EventWithProof>,
) -> Self {
Self {
lower_bound_incl,
upper_bound_excl,
}
}
pub fn verify(
&self,
ledger_info: &LedgerInfo,
event_key: &EventKey,
latest_event_count: Option<u64>,
event_version: Version,
) -> Result<()> {
ensure!(
event_version <= ledger_info.version(),
"request event_version {} must be <= LedgerInfo version {}",
event_version,
ledger_info.version(),
);
let latest_event_count = latest_event_count.unwrap_or_else(|| {
let upper = self.upper_bound_excl.as_ref();
let lower = self.lower_bound_incl.as_ref();
upper .or(lower) .map(|proof| proof.event.sequence_number.saturating_add(1))
.unwrap_or(0) });
match (&self.lower_bound_incl, &self.upper_bound_excl) {
(None, None) => {
ensure!(latest_event_count == 0);
}
(None, Some(first_event)) => {
let txn_version = first_event.transaction_version;
let seq_num = first_event.event.sequence_number;
ensure!(event_version < txn_version);
ensure!(seq_num == 0);
ensure!(latest_event_count > 0);
first_event
.verify(
ledger_info,
event_key,
seq_num,
first_event.transaction_version,
first_event.event_index,
)
.context("failed to verify first event")?;
}
(Some(lower_bound_incl), Some(upper_bound_excl)) => {
ensure!(lower_bound_incl.transaction_version <= event_version);
ensure!(event_version < upper_bound_excl.transaction_version);
let start_seq_num = lower_bound_incl.event.sequence_number;
let end_seq_num = upper_bound_excl.event.sequence_number;
ensure!(start_seq_num.saturating_add(1) == end_seq_num);
ensure!(latest_event_count > end_seq_num);
lower_bound_incl
.verify(
ledger_info,
event_key,
start_seq_num,
lower_bound_incl.transaction_version,
lower_bound_incl.event_index,
)
.context("failed to verify lower bound event")?;
upper_bound_excl
.verify(
ledger_info,
event_key,
end_seq_num,
upper_bound_excl.transaction_version,
upper_bound_excl.event_index,
)
.context("failed to verify upper bound event")?;
}
(Some(latest_event), None) => {
let txn_version = latest_event.transaction_version;
let seq_num = latest_event.event.sequence_number;
ensure!(txn_version <= event_version);
ensure!(seq_num.saturating_add(1) == latest_event_count);
latest_event
.verify(
ledger_info,
event_key,
seq_num,
txn_version,
latest_event.event_index,
)
.context("failed to verify latest event")?;
}
}
Ok(())
}
}