fuel_core/schema/
dap.rs

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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
use crate::{
    database::{
        database_description::on_chain::OnChain,
        Database,
        OnChainIterableKeyValueView,
    },
    fuel_core_graphql_api::api_service::ConsensusProvider,
    schema::scalars::{
        U32,
        U64,
    },
};
use anyhow::anyhow;
use async_graphql::{
    Context,
    Object,
    SchemaBuilder,
    ID,
};
use fuel_core_storage::{
    not_found,
    transactional::{
        AtomicView,
        IntoTransaction,
        StorageTransaction,
    },
    vm_storage::VmStorage,
    InterpreterStorage,
};
use fuel_core_types::{
    fuel_asm::{
        Instruction,
        RegisterId,
        Word,
    },
    fuel_tx::{
        field::{
            Policies,
            ScriptGasLimit,
            Witnesses,
        },
        policies::PolicyType,
        ConsensusParameters,
        Executable,
        Script,
        Transaction,
    },
    fuel_vm::{
        checked_transaction::{
            CheckedTransaction,
            IntoChecked,
        },
        interpreter::{
            InterpreterParams,
            MemoryInstance,
        },
        state::DebugEval,
        Interpreter,
        InterpreterError,
    },
};
use futures::lock::Mutex;
use std::{
    collections::HashMap,
    io,
    sync,
    sync::Arc,
};
use tracing::{
    debug,
    trace,
};
use uuid::Uuid;

pub struct Config {
    /// `true` means that debugger functionality is enabled.
    debug_enabled: bool,
}

type FrozenDatabase = VmStorage<StorageTransaction<OnChainIterableKeyValueView>>;

#[derive(Default, Debug)]
pub struct ConcreteStorage {
    vm: HashMap<ID, Interpreter<MemoryInstance, FrozenDatabase, Script>>,
    tx: HashMap<ID, Vec<Script>>,
}

/// The gas price used for transactions in the debugger. It is set to 0 because
/// the debugger does not actually execute transactions, but only simulates
/// their execution.
const GAS_PRICE: u64 = 0;

impl ConcreteStorage {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn register(&self, id: &ID, register: RegisterId) -> Option<Word> {
        self.vm
            .get(id)
            .and_then(|vm| vm.registers().get(register).copied())
    }

    pub fn memory(&self, id: &ID, start: usize, size: usize) -> Option<&[u8]> {
        self.vm
            .get(id)
            .and_then(|vm| vm.memory().read(start, size).ok())
    }

    pub fn init(
        &mut self,
        txs: &[Script],
        params: Arc<ConsensusParameters>,
        storage: &Database<OnChain>,
    ) -> anyhow::Result<ID> {
        let id = Uuid::new_v4();
        let id = ID::from(id);

        let vm_database = Self::vm_database(storage)?;
        let tx = Self::dummy_tx(params.tx_params().max_gas_per_tx() / 2);
        let checked_tx = tx
            .into_checked_basic(vm_database.block_height()?, &params)
            .map_err(|e| anyhow::anyhow!("{:?}", e))?;
        self.tx
            .get_mut(&id)
            .map(|tx| tx.extend_from_slice(txs))
            .unwrap_or_else(|| {
                self.tx.insert(id.clone(), txs.to_owned());
            });

        let gas_costs = params.gas_costs();
        let fee_params = params.fee_params();

        let ready_tx = checked_tx
            .into_ready(GAS_PRICE, gas_costs, fee_params)
            .map_err(|e| {
                anyhow!("Failed to apply dynamic values to checked tx: {:?}", e)
            })?;

        let interpreter_params = InterpreterParams::new(GAS_PRICE, params.as_ref());
        let mut vm = Interpreter::with_storage(
            MemoryInstance::new(),
            vm_database,
            interpreter_params,
        );
        vm.transact(ready_tx).map_err(|e| anyhow::anyhow!(e))?;
        self.vm.insert(id.clone(), vm);

        Ok(id)
    }

    pub fn kill(&mut self, id: &ID) -> bool {
        self.tx.remove(id);
        self.vm.remove(id).is_some()
    }

    pub fn reset(
        &mut self,
        id: &ID,
        params: Arc<ConsensusParameters>,
        storage: &Database<OnChain>,
    ) -> anyhow::Result<()> {
        let vm_database = Self::vm_database(storage)?;
        let tx = self
            .tx
            .get(id)
            .and_then(|tx| tx.first())
            .cloned()
            .unwrap_or(Self::dummy_tx(params.tx_params().max_gas_per_tx() / 2));

        let checked_tx = tx
            .into_checked_basic(vm_database.block_height()?, &params)
            .map_err(|e| anyhow::anyhow!("{:?}", e))?;

        let gas_costs = params.gas_costs();
        let fee_params = params.fee_params();

        let ready_tx = checked_tx
            .into_ready(GAS_PRICE, gas_costs, fee_params)
            .map_err(|e| {
                anyhow!("Failed to apply dynamic values to checked tx: {:?}", e)
            })?;

        let interpreter_params = InterpreterParams::new(GAS_PRICE, params.as_ref());
        let mut vm = Interpreter::with_storage(
            MemoryInstance::new(),
            vm_database,
            interpreter_params,
        );
        vm.transact(ready_tx).map_err(|e| anyhow::anyhow!(e))?;
        self.vm.insert(id.clone(), vm).ok_or_else(|| {
            io::Error::new(io::ErrorKind::NotFound, "The VM instance was not found")
        })?;
        Ok(())
    }

    pub fn exec(&mut self, id: &ID, op: Instruction) -> anyhow::Result<()> {
        self.vm
            .get_mut(id)
            .map(|vm| vm.instruction(op))
            .transpose()
            .map_err(|e| anyhow::anyhow!(e))?
            .map(|_| ())
            .ok_or_else(|| anyhow::anyhow!("The VM instance was not found"))
    }

    fn vm_database(storage: &Database<OnChain>) -> anyhow::Result<FrozenDatabase> {
        let view = storage.latest_view()?;
        let block = view
            .get_current_block()?
            .ok_or(not_found!("Block for VMDatabase"))?;

        let vm_database = VmStorage::new(
            view.into_transaction(),
            block.header().consensus(),
            block.header().application(),
            // TODO: Use a real coinbase address
            Default::default(),
        );

        Ok(vm_database)
    }

    fn dummy_tx(gas_limit: u64) -> Script {
        // Create `Script` transaction with dummy coin
        let mut tx = Script::default();
        *tx.script_gas_limit_mut() = gas_limit;
        tx.add_unsigned_coin_input(
            Default::default(),
            &Default::default(),
            Default::default(),
            Default::default(),
            Default::default(),
            Default::default(),
        );
        tx.witnesses_mut().push(vec![].into());
        tx.policies_mut().set(PolicyType::MaxFee, Some(0));
        tx
    }
}

pub type GraphStorage = sync::Arc<Mutex<ConcreteStorage>>;

#[derive(Default)]
pub struct DapQuery;
#[derive(Default)]
pub struct DapMutation;

pub fn init<Q, M, S>(
    schema: SchemaBuilder<Q, M, S>,
    debug_enabled: bool,
) -> SchemaBuilder<Q, M, S> {
    schema
        .data(GraphStorage::new(Mutex::new(ConcreteStorage::new())))
        .data(Config { debug_enabled })
}

fn require_debug(ctx: &Context<'_>) -> async_graphql::Result<()> {
    let config = ctx.data_unchecked::<Config>();

    if config.debug_enabled {
        Ok(())
    } else {
        Err(async_graphql::Error::new("The 'debug' feature is disabled"))
    }
}

#[Object]
impl DapQuery {
    /// Read register value by index.
    async fn register(
        &self,
        ctx: &Context<'_>,
        id: ID,
        register: U32,
    ) -> async_graphql::Result<U64> {
        require_debug(ctx)?;
        ctx.data_unchecked::<GraphStorage>()
            .lock()
            .await
            .register(&id, register.0 as RegisterId)
            .ok_or_else(|| async_graphql::Error::new("Invalid register identifier"))
            .map(|val| val.into())
    }

    /// Read read a range of memory bytes.
    async fn memory(
        &self,
        ctx: &Context<'_>,
        id: ID,
        start: U32,
        size: U32,
    ) -> async_graphql::Result<String> {
        require_debug(ctx)?;
        ctx.data_unchecked::<GraphStorage>()
            .lock()
            .await
            .memory(&id, start.0 as usize, size.0 as usize)
            .ok_or_else(|| async_graphql::Error::new("Invalid memory range"))
            .and_then(|mem| Ok(serde_json::to_string(mem)?))
    }
}

#[Object]
impl DapMutation {
    /// Initialize a new debugger session, returning its ID.
    /// A new VM instance is spawned for each session.
    /// The session is run in a separate database transaction,
    /// on top of the most recent node state.
    async fn start_session(&self, ctx: &Context<'_>) -> async_graphql::Result<ID> {
        require_debug(ctx)?;
        trace!("Initializing new interpreter");

        let db = ctx.data_unchecked::<Database>();
        let params = ctx
            .data_unchecked::<ConsensusProvider>()
            .latest_consensus_params();

        let id =
            ctx.data_unchecked::<GraphStorage>()
                .lock()
                .await
                .init(&[], params, db)?;

        debug!("Session {:?} initialized", id);

        Ok(id)
    }

    /// End debugger session.
    async fn end_session(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> async_graphql::Result<bool> {
        require_debug(ctx)?;
        let existed = ctx.data_unchecked::<GraphStorage>().lock().await.kill(&id);

        debug!("Session {:?} dropped with result {}", id, existed);

        Ok(existed)
    }

    /// Reset the VM instance to the initial state.
    async fn reset(&self, ctx: &Context<'_>, id: ID) -> async_graphql::Result<bool> {
        require_debug(ctx)?;
        let db = ctx.data_unchecked::<Database>();
        let params = ctx
            .data_unchecked::<ConsensusProvider>()
            .latest_consensus_params();

        ctx.data_unchecked::<GraphStorage>()
            .lock()
            .await
            .reset(&id, params, db)?;

        debug!("Session {:?} was reset", id);

        Ok(true)
    }

    /// Execute a single fuel-asm instruction.
    async fn execute(
        &self,
        ctx: &Context<'_>,
        id: ID,
        op: String,
    ) -> async_graphql::Result<bool> {
        require_debug(ctx)?;
        trace!("Execute encoded op {}", op);

        let op: Instruction = serde_json::from_str(op.as_str())?;

        trace!("Op decoded to {:?}", op);

        let storage = ctx.data_unchecked::<GraphStorage>().clone();
        let result = storage.lock().await.exec(&id, op).is_ok();

        debug!("Op {:?} executed with result {}", op, result);

        Ok(result)
    }

    /// Set single-stepping mode for the VM instance.
    async fn set_single_stepping(
        &self,
        ctx: &Context<'_>,
        id: ID,
        enable: bool,
    ) -> async_graphql::Result<bool> {
        require_debug(ctx)?;
        trace!("Set single stepping to {} for VM {:?}", enable, id);

        let mut locked = ctx.data_unchecked::<GraphStorage>().lock().await;
        let vm = locked
            .vm
            .get_mut(&id)
            .ok_or_else(|| async_graphql::Error::new("VM not found"))?;

        vm.set_single_stepping(enable);
        Ok(enable)
    }

    /// Set a breakpoint for a VM instance.
    async fn set_breakpoint(
        &self,
        ctx: &Context<'_>,
        id: ID,
        breakpoint: gql_types::Breakpoint,
    ) -> async_graphql::Result<bool> {
        require_debug(ctx)?;
        trace!("Set breakpoint for VM {:?}", id);

        let mut locked = ctx.data_unchecked::<GraphStorage>().lock().await;
        let vm = locked
            .vm
            .get_mut(&id)
            .ok_or_else(|| async_graphql::Error::new("VM not found"))?;

        vm.set_breakpoint(breakpoint.into());
        Ok(true)
    }

    /// Run a single transaction in given session until it
    /// hits a breakpoint or completes.
    async fn start_tx(
        &self,
        ctx: &Context<'_>,
        id: ID,
        tx_json: String,
    ) -> async_graphql::Result<gql_types::RunResult> {
        require_debug(ctx)?;
        trace!("Spawning a new VM instance");

        let tx: Transaction = serde_json::from_str(&tx_json)
            .map_err(|_| async_graphql::Error::new("Invalid transaction JSON"))?;

        let mut locked = ctx.data_unchecked::<GraphStorage>().lock().await;
        let params = ctx
            .data_unchecked::<ConsensusProvider>()
            .latest_consensus_params();

        let vm = locked
            .vm
            .get_mut(&id)
            .ok_or_else(|| async_graphql::Error::new("VM not found"))?;

        let checked_tx = tx
            .into_checked_basic(vm.as_ref().block_height()?, &params)
            .map_err(|err| anyhow::anyhow!("{:?}", err))?
            .into();

        let gas_costs = params.gas_costs();
        let fee_params = params.fee_params();

        match checked_tx {
            CheckedTransaction::Script(script) => {
                let ready_tx = script
                    .into_ready(GAS_PRICE, gas_costs, fee_params)
                    .map_err(|e| {
                        anyhow!("Failed to apply dynamic values to checked tx: {:?}", e)
                    })?;
                let state_ref = vm.transact(ready_tx).map_err(|err| {
                    async_graphql::Error::new(format!("Transaction failed: {err:?}"))
                })?;

                let json_receipts = state_ref
                    .receipts()
                    .iter()
                    .map(|r| {
                        serde_json::to_string(&r).expect("JSON serialization failed")
                    })
                    .collect();

                let dbgref = state_ref.state().debug_ref();
                Ok(gql_types::RunResult {
                    state: match dbgref {
                        Some(_) => gql_types::RunState::Breakpoint,
                        None => gql_types::RunState::Completed,
                    },
                    breakpoint: dbgref.and_then(|d| match d {
                        DebugEval::Continue => None,
                        DebugEval::Breakpoint(bp) => Some(bp.into()),
                    }),
                    json_receipts,
                })
            }
            CheckedTransaction::Create(_) => {
                Err(async_graphql::Error::new("`Create` is not supported"))
            }
            CheckedTransaction::Mint(_) => {
                Err(async_graphql::Error::new("`Mint` is not supported"))
            }
            CheckedTransaction::Upgrade(_) => {
                Err(async_graphql::Error::new("`Upgrade` is not supported"))
            }
            CheckedTransaction::Upload(_) => {
                Err(async_graphql::Error::new("`Upload` is not supported"))
            }
            CheckedTransaction::Blob(_) => {
                Err(async_graphql::Error::new("`Blob` is not supported"))
            }
        }
    }

    /// Resume execution of the VM instance after a breakpoint.
    /// Runs until the next breakpoint or until the transaction completes.
    async fn continue_tx(
        &self,
        ctx: &Context<'_>,
        id: ID,
    ) -> async_graphql::Result<gql_types::RunResult> {
        require_debug(ctx)?;
        trace!("Continue execution of VM {:?}", id);

        let mut locked = ctx.data_unchecked::<GraphStorage>().lock().await;
        let vm = locked
            .vm
            .get_mut(&id)
            .ok_or_else(|| async_graphql::Error::new("VM not found"))?;

        let receipt_count_before = vm.receipts().len();

        let state = match vm.resume() {
            Ok(state) => state,
            // The transaction was already completed earlier, so it cannot be resumed
            Err(InterpreterError::DebugStateNotInitialized) => {
                return Ok(gql_types::RunResult {
                    state: gql_types::RunState::Completed,
                    breakpoint: None,
                    json_receipts: Vec::new(),
                })
            }
            // The transaction was already completed earlier, so it cannot be resumed
            Err(err) => {
                return Err(async_graphql::Error::new(format!("VM error: {err:?}")))
            }
        };

        let json_receipts = vm
            .receipts()
            .iter()
            .skip(receipt_count_before)
            .map(|r| serde_json::to_string(&r).expect("JSON serialization failed"))
            .collect();

        let dbgref = state.debug_ref();

        Ok(gql_types::RunResult {
            state: match dbgref {
                Some(_) => gql_types::RunState::Breakpoint,
                None => gql_types::RunState::Completed,
            },
            breakpoint: dbgref.and_then(|d| match d {
                DebugEval::Continue => None,
                DebugEval::Breakpoint(bp) => Some(bp.into()),
            }),
            json_receipts,
        })
    }
}

mod gql_types {
    //! GraphQL type wrappers
    use async_graphql::*;

    use crate::schema::scalars::{
        ContractId,
        U64,
    };

    use fuel_core_types::fuel_vm::Breakpoint as FuelBreakpoint;

    /// Breakpoint, defined as a tuple of contract ID and relative PC offset inside it
    #[derive(Debug, Clone, Copy, InputObject)]
    pub struct Breakpoint {
        contract: ContractId,
        pc: U64,
    }

    impl From<&FuelBreakpoint> for Breakpoint {
        fn from(bp: &FuelBreakpoint) -> Self {
            Self {
                contract: (*bp.contract()).into(),
                pc: U64(bp.pc()),
            }
        }
    }

    impl From<Breakpoint> for FuelBreakpoint {
        fn from(bp: Breakpoint) -> Self {
            Self::new(bp.contract.into(), bp.pc.0)
        }
    }

    /// A separate `Breakpoint` type to be used as an output, as a single
    /// type cannot act as both input and output type in async-graphql
    #[derive(Debug, Clone, Copy, SimpleObject)]
    pub struct OutputBreakpoint {
        contract: ContractId,
        pc: U64,
    }

    impl From<&FuelBreakpoint> for OutputBreakpoint {
        fn from(bp: &FuelBreakpoint) -> Self {
            Self {
                contract: (*bp.contract()).into(),
                pc: U64(bp.pc()),
            }
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Enum)]
    pub enum RunState {
        /// All breakpoints have been processed, and the program has terminated
        Completed,
        /// Stopped on a breakpoint
        Breakpoint,
    }

    #[derive(Debug, Clone, SimpleObject)]
    pub struct RunResult {
        pub state: RunState,
        pub breakpoint: Option<OutputBreakpoint>,
        pub json_receipts: Vec<String>,
    }
}