massa_grpc/stream/new_slot_transfers.rs
1use std::pin::Pin;
2
3#[cfg(feature = "execution-trace")]
4use crate::{error::GrpcError, server::MassaPublicGrpc};
5#[cfg(feature = "execution-trace")]
6use tonic::{Request, Streaming};
7
8/// Type declaration for NewSlotTransfers
9pub type NewSlotTransfersStreamType = Pin<
10 Box<
11 dyn futures_util::Stream<
12 Item = Result<
13 massa_proto_rs::massa::api::v1::NewSlotTransfersResponse,
14 tonic::Status,
15 >,
16 > + Send
17 + 'static,
18 >,
19>;
20
21#[cfg(feature = "execution-trace")]
22/// Creates a new stream of new slots transfers
23pub(crate) async fn new_slot_transfers(
24 grpc: &MassaPublicGrpc,
25 request: Request<Streaming<massa_proto_rs::massa::api::v1::NewSlotTransfersRequest>>,
26) -> Result<NewSlotTransfersStreamType, GrpcError> {
27 use crate::error::match_for_io_error;
28 use futures_util::StreamExt;
29 use massa_proto_rs::massa::api::v1::{self as grpc_api, FinalityLevel, TransferInfo};
30 use tokio::select;
31 use tracing::{error, warn};
32
33 let (tx, rx) = tokio::sync::mpsc::channel(grpc.grpc_config.max_channel_size);
34 // Extract the incoming stream of abi call stacks messages
35 let mut in_stream = request.into_inner();
36
37 // Subscribe to the new slot execution events channel
38 let mut subscriber = grpc
39 .execution_channels
40 .slot_execution_traces_sender
41 .subscribe();
42
43 tokio::spawn({
44 async move {
45 // Issue #5066: standardize startup with `new_slot_execution_outputs` by waiting
46 // for the client's first request before emitting anything, so the default filter
47 // is applied only once the client has had a chance to configure it and this stream
48 // never emits data under an implicit default.
49 let mut finality = match in_stream.next().await {
50 Some(Ok(first)) => first.finality_level(),
51 // No usable initial request (error or client disconnected): stream nothing.
52 _ => {
53 error!("empty request");
54 return;
55 }
56 };
57 loop {
58 select! {
59 // Receive a new slot execution traces from the subscriber
60 event = subscriber.recv() => {
61 match event {
62 Ok((massa_slot_execution_trace, slot_transfers, is_final)) => {
63 // A `FinalityLevel::Unspecified` finality level (the default,
64 // e.g. when the client sends no explicit level) accepts BOTH
65 // candidate and final transfers, matching the default filter of
66 // `FilterNewSlotExec` used by `new_slot_execution_outputs`.
67 if (finality == FinalityLevel::Final && !is_final) ||
68 (finality == FinalityLevel::Candidate && is_final) {
69 continue;
70 }
71 let mut ret_transfers = Vec::new();
72 // flatten & filter transfer trace in asc_call_stacks
73
74 let abi_transfer_1 = "assembly_script_transfer_coins".to_string();
75 let abi_transfer_2 = "assembly_script_transfer_coins_for".to_string();
76 let transfer_abi_names = vec![abi_transfer_1, abi_transfer_2];
77 for (i, asc_call_stack) in massa_slot_execution_trace.asc_call_stacks.iter().enumerate() {
78 for abi_trace in asc_call_stack {
79 let only_transfer = abi_trace.flatten_filter(&transfer_abi_names);
80 for transfer in only_transfer {
81 let (t_from, t_to, t_amount) = transfer.parse_transfer();
82 ret_transfers.push(TransferInfo {
83 from: t_from.clone(),
84 to: t_to.clone(),
85 amount: t_amount,
86 operation_id_or_asc_index: Some(
87 grpc_api::transfer_info::OperationIdOrAscIndex::AscIndex(i as u64),
88 ),
89 });
90 }
91 }
92 }
93
94 for deferred_call_call_stack in massa_slot_execution_trace.deferred_call_stacks {
95 let deferred_call_id = deferred_call_call_stack.0;
96 let deferred_call_call_stack = deferred_call_call_stack.1;
97 for abi_trace in deferred_call_call_stack {
98 let only_transfer = abi_trace.flatten_filter(&transfer_abi_names);
99 for transfer in only_transfer {
100 let (t_from, t_to, t_amount) = transfer.parse_transfer();
101 ret_transfers.push(TransferInfo {
102 from: t_from.clone(),
103 to: t_to.clone(),
104 amount: t_amount,
105 operation_id_or_asc_index: Some(
106 grpc_api::transfer_info::OperationIdOrAscIndex::DeferredCallId(deferred_call_id.to_string()),
107 ),
108 });
109 }
110 }
111 }
112
113 for op_call_stack in massa_slot_execution_trace.operation_call_stacks {
114 let op_id = op_call_stack.0;
115 let op_call_stack = op_call_stack.1;
116 for abi_trace in op_call_stack {
117 let only_transfer = abi_trace.flatten_filter(&transfer_abi_names);
118 for transfer in only_transfer {
119 let (t_from, t_to, t_amount) = transfer.parse_transfer();
120 ret_transfers.push(TransferInfo {
121 from: t_from.clone(),
122 to: t_to.clone(),
123 amount: t_amount,
124 operation_id_or_asc_index: Some(
125 grpc_api::transfer_info::OperationIdOrAscIndex::OperationId(op_id.to_string()),
126 ),
127 });
128 }
129 }
130 }
131 // Transfers are carried in the event itself, bound to the same
132 // execution instance as the abi call stacks above. This avoids a
133 // separate slot-keyed lookup, which could return transfers from a
134 // re-execution of the same slot and yield a hybrid response.
135 for transfer in slot_transfers {
136 ret_transfers.push(TransferInfo {
137 from: transfer.from.to_string(),
138 to: transfer.to.to_string(),
139 amount: transfer.amount.to_raw(),
140 operation_id_or_asc_index: Some(
141 grpc_api::transfer_info::OperationIdOrAscIndex::OperationId(
142 transfer.op_id.to_string(),
143 ),
144 ),
145 });
146 }
147 let ret = grpc_api::NewSlotTransfersResponse {
148 slot: Some(massa_slot_execution_trace.slot.into()),
149 transfers: ret_transfers,
150 };
151
152 if let Err(e) = tx.send(Ok(ret)).await {
153 error!("failed to send new slot execution trace: {}", e);
154 break;
155 }
156 }
157 Err(e) => {
158 error!("error on receive new slot execution trace : {}", e)
159 }
160 }
161 }
162 // Receive a new message from the in_stream
163 res = in_stream.next() => {
164 match res {
165 Some(res) => {
166 match res {
167 Ok(message) => {
168 finality = message.finality_level();
169 },
170 Err(e) => {
171 // Any io error -> break
172 if let Some(io_err) = match_for_io_error(&e) {
173 warn!("client disconnected, broken pipe: {}", io_err);
174 break;
175 }
176 error!("{}", e);
177 if let Err(e2) = tx.send(Err(e)).await {
178 error!("failed to send back error response: {}", e2);
179 break;
180 }
181 }
182 }
183 }
184 None => {
185 // the client has disconnected
186 break;
187 }
188 }
189 }
190 }
191 }
192 }
193 });
194 let out_stream = tokio_stream::wrappers::ReceiverStream::new(rx);
195 Ok(Box::pin(out_stream) as NewSlotTransfersStreamType)
196}