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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// This file is part of Gear.

// Copyright (C) 2021-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::{
    common::{
        ActorExecutionErrorReplyReason, DispatchOutcome, DispatchResult, DispatchResultKind,
        ExecutionError, JournalNote, SystemExecutionError, WasmExecutionContext,
    },
    configs::{BlockConfig, ExecutionSettings},
    context::*,
    executor,
    ext::ProcessorExternalities,
    precharge::SuccessfulDispatchResultKind,
};
use alloc::{
    format,
    string::{String, ToString},
    vec::Vec,
};
use gear_core::{
    env::Externalities,
    ids::{prelude::*, MessageId, ProgramId},
    message::{ContextSettings, DispatchKind, IncomingDispatch, ReplyMessage, StoredDispatch},
    reservation::GasReservationState,
};
use gear_core_backend::{
    error::{BackendAllocSyscallError, BackendSyscallError, RunFallibleError},
    BackendExternalities,
};
use gear_core_errors::{ErrorReplyReason, SignalCode};

/// Process program & dispatch for it and return journal for updates.
pub fn process<Ext>(
    block_config: &BlockConfig,
    execution_context: ProcessExecutionContext,
    random_data: (Vec<u8>, u32),
) -> Result<Vec<JournalNote>, SystemExecutionError>
where
    Ext: ProcessorExternalities + BackendExternalities + Send + 'static,
    <Ext as Externalities>::AllocError:
        BackendAllocSyscallError<ExtError = Ext::UnrecoverableError>,
    RunFallibleError: From<Ext::FallibleError>,
    <Ext as Externalities>::UnrecoverableError: BackendSyscallError,
{
    use crate::precharge::SuccessfulDispatchResultKind::*;

    let BlockConfig {
        block_info,
        performance_multiplier,
        forbidden_funcs,
        reserve_for,
        gas_multiplier,
        costs,
        existential_deposit,
        mailbox_threshold,
        max_pages,
        outgoing_limit,
        outgoing_bytes_limit,
        ..
    } = block_config.clone();

    let execution_settings = ExecutionSettings {
        block_info,
        performance_multiplier,
        existential_deposit,
        mailbox_threshold,
        max_pages,
        ext_costs: costs.ext,
        lazy_pages_costs: costs.lazy_pages,
        forbidden_funcs,
        reserve_for,
        random_data,
        gas_multiplier,
    };

    let dispatch = execution_context.dispatch;
    let balance = execution_context.balance;
    let program_id = execution_context.program.id;
    let initial_reservations_amount = execution_context.gas_reserver.states().len();

    let execution_context = WasmExecutionContext {
        gas_counter: execution_context.gas_counter,
        gas_allowance_counter: execution_context.gas_allowance_counter,
        gas_reserver: execution_context.gas_reserver,
        program: execution_context.program,
        memory_size: execution_context.memory_size,
    };

    // Sending fee: double write cost for addition and removal some time soon
    // from queue.
    //
    // Scheduled sending fee: double write cost for addition and removal some time soon
    // from queue and double write cost (addition and removal) for dispatch stash.
    //
    // Waiting fee: triple write cost for addition and removal some time soon
    // from waitlist and enqueuing / sending error reply afterward.
    //
    // Waking fee: double write cost for removal from waitlist
    // and further enqueueing.
    let msg_ctx_settings = ContextSettings {
        sending_fee: costs.write.cost_for(2.into()),
        scheduled_sending_fee: costs.write.cost_for(4.into()),
        waiting_fee: costs.write.cost_for(3.into()),
        waking_fee: costs.write.cost_for(2.into()),
        reservation_fee: costs.write.cost_for(2.into()),
        outgoing_limit,
        outgoing_bytes_limit,
    };

    // TODO: add tests that system reservation is successfully unreserved after
    // actor execution error #3756.

    // Get system reservation context in order to use it if actor execution error occurs.
    let system_reservation_ctx = SystemReservationContext::from_dispatch(&dispatch);

    let exec_result = executor::execute_wasm::<Ext>(
        balance,
        dispatch.clone(),
        execution_context,
        execution_settings,
        msg_ctx_settings,
    )
    .map_err(|err| {
        log::debug!("Wasm execution error: {}", err);
        err
    });

    match exec_result {
        Ok(res) => {
            match res.kind {
                DispatchResultKind::Success
                | DispatchResultKind::Wait(_, _)
                | DispatchResultKind::Exit(_) => {
                    // assert that after processing the initial reservation is less or equal to the current one.
                    // during execution reservation amount might increase due to `system_reserve_gas` calls
                    // thus making initial reservation less than current one.
                    debug_assert!(
                        res.context_store.system_reservation()
                            >= system_reservation_ctx.previous_reservation
                    );
                    debug_assert!(
                        system_reservation_ctx.previous_reservation
                            == res.system_reservation_context.previous_reservation
                    );
                    debug_assert!(res
                        .gas_reserver
                        .as_ref()
                        .map(|reserver| initial_reservations_amount <= reserver.states().len())
                        .unwrap_or(true));
                }
                // reservation does not change in case of failure
                _ => (),
            }
            Ok(match res.kind {
                DispatchResultKind::Trap(reason) => process_execution_error(
                    res.dispatch,
                    program_id,
                    res.gas_amount.burned(),
                    res.system_reservation_context,
                    ActorExecutionErrorReplyReason::Trap(reason),
                ),

                DispatchResultKind::Success => process_success(Success, res),
                DispatchResultKind::Wait(duration, ref waited_type) => {
                    process_success(Wait(duration, waited_type.clone()), res)
                }
                DispatchResultKind::Exit(value_destination) => {
                    process_success(Exit(value_destination), res)
                }
                DispatchResultKind::GasAllowanceExceed => {
                    process_allowance_exceed(dispatch, program_id, res.gas_amount.burned())
                }
            })
        }
        Err(ExecutionError::Actor(e)) => Ok(process_execution_error(
            dispatch,
            program_id,
            e.gas_amount.burned(),
            system_reservation_ctx,
            e.reason,
        )),
        Err(ExecutionError::System(e)) => Err(e),
    }
}

enum ProcessErrorCase {
    /// Message is not executable error.
    NonExecutable,
    /// Error is considered as an execution failure.
    ExecutionFailed(ActorExecutionErrorReplyReason),
    /// Message is executable, but it's execution failed due to re-instrumentation.
    ReinstrumentationFailed,
}

impl ProcessErrorCase {
    pub fn to_reason_and_payload(&self) -> (ErrorReplyReason, String) {
        match self {
            ProcessErrorCase::NonExecutable => {
                let reason = ErrorReplyReason::InactiveActor;
                (reason, reason.to_string())
            }
            ProcessErrorCase::ExecutionFailed(reason) => {
                (reason.as_simple().into(), reason.to_string())
            }
            ProcessErrorCase::ReinstrumentationFailed => {
                let err = ErrorReplyReason::ReinstrumentationFailure;
                (err, err.to_string())
            }
        }
    }
}

fn process_error(
    dispatch: IncomingDispatch,
    program_id: ProgramId,
    gas_burned: u64,
    system_reservation_ctx: SystemReservationContext,
    case: ProcessErrorCase,
) -> Vec<JournalNote> {
    let mut journal = Vec::new();

    let message_id = dispatch.id();
    let origin = dispatch.source();
    let value = dispatch.value();

    journal.push(JournalNote::GasBurned {
        message_id,
        amount: gas_burned,
    });

    // We check if value is greater than zero to don't provide
    // no-op journal note.
    //
    // We also check if dispatch had context of previous executions:
    // it's existence shows that we have processed message after
    // being waken, so the value were already transferred in
    // execution, where `gr_wait` was called.
    if dispatch.context().is_none() && value != 0 {
        // Send back value
        journal.push(JournalNote::SendValue {
            from: origin,
            to: None,
            value,
        });
    }

    if let Some(amount) = system_reservation_ctx.current_reservation {
        journal.push(JournalNote::SystemReserveGas { message_id, amount });
    }

    if let ProcessErrorCase::ExecutionFailed(reason) = &case {
        // TODO: consider to handle error reply and init #3701
        if system_reservation_ctx.has_any()
            && !dispatch.is_error_reply()
            && !matches!(dispatch.kind(), DispatchKind::Signal | DispatchKind::Init)
        {
            journal.push(JournalNote::SendSignal {
                message_id,
                destination: program_id,
                code: SignalCode::Execution(reason.as_simple()),
            });
        }
    }

    if system_reservation_ctx.has_any() {
        journal.push(JournalNote::SystemUnreserveGas { message_id });
    }

    if !dispatch.is_reply() && dispatch.kind() != DispatchKind::Signal {
        let (err, err_payload) = case.to_reason_and_payload();

        // Panic is impossible, unless error message is too large or [Payload] max size is too small.
        let err_payload = err_payload.into_bytes().try_into().unwrap_or_else(|_| {
            let (_, err_payload) = case.to_reason_and_payload();
            let err_msg =
                format!("process_error: Error message is too big. Message id - {message_id}, error payload - {err_payload}",
            );

            log::error!("{err_msg}");
            unreachable!("{err_msg}")
        });

        // # Safety
        //
        // 1. The dispatch.id() has already been checked
        // 2. This reply message is generated by our system
        //
        // So, the message id of this reply message will not be duplicated.
        let dispatch = ReplyMessage::system(dispatch.id(), err_payload, err).into_dispatch(
            program_id,
            dispatch.source(),
            dispatch.id(),
        );

        journal.push(JournalNote::SendDispatch {
            message_id,
            dispatch,
            delay: 0,
            reservation: None,
        });
    }

    let outcome = match case {
        ProcessErrorCase::ExecutionFailed { .. } | ProcessErrorCase::ReinstrumentationFailed => {
            let (_, err_payload) = case.to_reason_and_payload();
            match dispatch.kind() {
                DispatchKind::Init => DispatchOutcome::InitFailure {
                    program_id,
                    origin,
                    reason: err_payload,
                },
                _ => DispatchOutcome::MessageTrap {
                    program_id,
                    trap: err_payload,
                },
            }
        }
        ProcessErrorCase::NonExecutable => DispatchOutcome::NoExecution,
    };

    journal.push(JournalNote::MessageDispatched {
        message_id,
        source: origin,
        outcome,
    });
    journal.push(JournalNote::MessageConsumed(message_id));

    journal
}

/// Helper function for journal creation in trap/error case.
pub fn process_execution_error(
    dispatch: IncomingDispatch,
    program_id: ProgramId,
    gas_burned: u64,
    system_reservation_ctx: SystemReservationContext,
    err: impl Into<ActorExecutionErrorReplyReason>,
) -> Vec<JournalNote> {
    process_error(
        dispatch,
        program_id,
        gas_burned,
        system_reservation_ctx,
        ProcessErrorCase::ExecutionFailed(err.into()),
    )
}

/// Helper function for journal creation in case of re-instrumentation error.
pub fn process_reinstrumentation_error(
    context: ContextChargedForInstrumentation,
) -> Vec<JournalNote> {
    let dispatch = context.data.dispatch;
    let program_id = context.data.destination_id;
    let gas_burned = context.data.gas_counter.burned();
    let system_reservation_ctx = SystemReservationContext::from_dispatch(&dispatch);

    process_error(
        dispatch,
        program_id,
        gas_burned,
        system_reservation_ctx,
        ProcessErrorCase::ReinstrumentationFailed,
    )
}

/// Helper function for journal creation in message no execution case.
pub fn process_non_executable(context: ContextChargedForProgram) -> Vec<JournalNote> {
    let ContextChargedForProgram {
        dispatch,
        gas_counter,
        destination_id,
        ..
    } = context;

    let system_reservation_ctx = SystemReservationContext::from_dispatch(&dispatch);

    process_error(
        dispatch,
        destination_id,
        gas_counter.burned(),
        system_reservation_ctx,
        ProcessErrorCase::NonExecutable,
    )
}

/// Helper function for journal creation in success case
pub fn process_success(
    kind: SuccessfulDispatchResultKind,
    dispatch_result: DispatchResult,
) -> Vec<JournalNote> {
    use crate::precharge::SuccessfulDispatchResultKind::*;

    let DispatchResult {
        dispatch,
        generated_dispatches,
        awakening,
        program_candidates,
        gas_amount,
        gas_reserver,
        system_reservation_context,
        page_update,
        program_id,
        context_store,
        allocations,
        reply_deposits,
        reply_sent,
        ..
    } = dispatch_result;

    let mut journal = Vec::new();

    let message_id = dispatch.id();
    let origin = dispatch.source();
    let value = dispatch.value();

    journal.push(JournalNote::GasBurned {
        message_id,
        amount: gas_amount.burned(),
    });

    if let Some(gas_reserver) = gas_reserver {
        journal.extend(gas_reserver.states().iter().flat_map(
            |(&reservation_id, &state)| match state {
                GasReservationState::Exists { .. } => None,
                GasReservationState::Created {
                    amount, duration, ..
                } => Some(JournalNote::ReserveGas {
                    message_id,
                    reservation_id,
                    program_id,
                    amount,
                    duration,
                }),
                GasReservationState::Removed { expiration } => Some(JournalNote::UnreserveGas {
                    reservation_id,
                    program_id,
                    expiration,
                }),
            },
        ));

        journal.push(JournalNote::UpdateGasReservations {
            program_id,
            reserver: gas_reserver,
        });
    }

    if let Some(amount) = system_reservation_context.current_reservation {
        journal.push(JournalNote::SystemReserveGas { message_id, amount });
    }

    // We check if value is greater than zero to don't provide
    // no-op journal note.
    //
    // We also check if dispatch had context of previous executions:
    // it's existence shows that we have processed message after
    // being waken, so the value were already transferred in
    // execution, where `gr_wait` was called.
    if dispatch.context().is_none() && value != 0 {
        // Send value further
        journal.push(JournalNote::SendValue {
            from: origin,
            to: Some(program_id),
            value,
        });
    }

    // Must be handled before handling generated dispatches.
    for (code_id, candidates) in program_candidates {
        journal.push(JournalNote::StoreNewPrograms {
            program_id,
            code_id,
            candidates,
        });
    }

    // Sending auto-generated reply about success execution.
    if matches!(kind, SuccessfulDispatchResultKind::Success)
        && !reply_sent
        && !dispatch.is_reply()
        && dispatch.kind() != DispatchKind::Signal
    {
        let auto_reply = ReplyMessage::auto(dispatch.id()).into_dispatch(
            program_id,
            dispatch.source(),
            dispatch.id(),
        );

        journal.push(JournalNote::SendDispatch {
            message_id,
            dispatch: auto_reply,
            delay: 0,
            reservation: None,
        });
    }

    for (message_id_sent, amount) in reply_deposits {
        journal.push(JournalNote::ReplyDeposit {
            message_id,
            future_reply_id: MessageId::generate_reply(message_id_sent),
            amount,
        });
    }

    for (dispatch, delay, reservation) in generated_dispatches {
        journal.push(JournalNote::SendDispatch {
            message_id,
            dispatch,
            delay,
            reservation,
        });
    }

    for (awakening_id, delay) in awakening {
        journal.push(JournalNote::WakeMessage {
            message_id,
            program_id,
            awakening_id,
            delay,
        });
    }

    for (page_number, data) in page_update {
        journal.push(JournalNote::UpdatePage {
            program_id,
            page_number,
            data,
        })
    }

    if let Some(allocations) = allocations {
        journal.push(JournalNote::UpdateAllocations {
            program_id,
            allocations,
        });
    }

    let outcome = match kind {
        Wait(duration, waited_type) => {
            journal.push(JournalNote::WaitDispatch {
                dispatch: dispatch.into_stored(program_id, context_store),
                duration,
                waited_type,
            });

            return journal;
        }
        Success => match dispatch.kind() {
            DispatchKind::Init => DispatchOutcome::InitSuccess { program_id },
            _ => DispatchOutcome::Success,
        },
        Exit(value_destination) => {
            journal.push(JournalNote::ExitDispatch {
                id_exited: program_id,
                value_destination,
            });

            DispatchOutcome::Exit { program_id }
        }
    };

    if system_reservation_context.has_any() {
        journal.push(JournalNote::SystemUnreserveGas { message_id });
    }

    journal.push(JournalNote::MessageDispatched {
        message_id,
        source: origin,
        outcome,
    });
    journal.push(JournalNote::MessageConsumed(message_id));
    journal
}

pub fn process_allowance_exceed(
    dispatch: IncomingDispatch,
    program_id: ProgramId,
    gas_burned: u64,
) -> Vec<JournalNote> {
    let mut journal = Vec::with_capacity(1);

    let (kind, message, opt_context) = dispatch.into_parts();

    let dispatch = StoredDispatch::new(kind, message.into_stored(program_id), opt_context);

    journal.push(JournalNote::StopProcessing {
        dispatch,
        gas_burned,
    });

    journal
}