Skip to main content

fabric_gateway/
events.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 fabric-gateway-rs contributors
3
4//! Chaincode event listening. Ports `chaincodeevents.go`,
5//! `chaincodeeventsbuilder.go` and `eventsbuilder.go`.
6
7use crate::client::GrpcClient;
8use crate::error::GatewayError;
9use crate::pb::common::{
10    Block, ChannelHeader, Envelope, Header, HeaderType, Payload, SignatureHeader,
11};
12use crate::pb::gateway::SignedChaincodeEventsRequest;
13use crate::pb::gateway::{ChaincodeEventsRequest as PbCcEventsRequest, ChaincodeEventsResponse};
14use crate::pb::orderer::{
15    seek_position::Type as SeekType, SeekInfo, SeekNextCommit, SeekPosition, SeekSpecified,
16};
17use crate::pb::protos::FilteredBlock;
18use crate::signing::SigningIdentity;
19use crate::util::now_timestamp;
20use prost::Message;
21use std::pin::Pin;
22use tokio_stream::{Stream, StreamExt};
23
24/// A chaincode event emitted by a transaction function.
25#[derive(Debug, Clone)]
26pub struct ChaincodeEvent {
27    pub block_number: u64,
28    pub transaction_id: String,
29    pub chaincode_name: String,
30    pub event_name: String,
31    pub payload: Vec<u8>,
32}
33
34/// Builder for a chaincode-events request, supporting a custom start position.
35pub struct ChaincodeEventsBuilder {
36    client: GrpcClient,
37    signing_id: SigningIdentity,
38    channel_name: String,
39    chaincode_name: String,
40    start_position: Option<SeekPosition>,
41    after_transaction_id: String,
42}
43
44impl ChaincodeEventsBuilder {
45    pub(crate) fn new(
46        client: GrpcClient,
47        signing_id: SigningIdentity,
48        channel_name: String,
49        chaincode_name: String,
50    ) -> Self {
51        Self {
52            client,
53            signing_id,
54            channel_name,
55            chaincode_name,
56            start_position: None,
57            after_transaction_id: String::new(),
58        }
59    }
60
61    /// Read events starting at the specified block number.
62    pub fn with_start_block(mut self, block_number: u64) -> Self {
63        self.start_position = Some(SeekPosition {
64            r#type: Some(SeekType::Specified(SeekSpecified {
65                number: block_number,
66            })),
67        });
68        self
69    }
70
71    /// Resume after a specific transaction within the start block.
72    pub fn with_after_transaction_id(mut self, transaction_id: impl Into<String>) -> Self {
73        self.after_transaction_id = transaction_id.into();
74        self
75    }
76
77    fn start_position(&self) -> SeekPosition {
78        self.start_position.unwrap_or(SeekPosition {
79            r#type: Some(SeekType::NextCommit(SeekNextCommit {})),
80        })
81    }
82
83    /// Build the request (supports off-line signing via
84    /// [`ChaincodeEventsRequest::bytes`] / [`ChaincodeEventsRequest::digest`]).
85    pub fn build(self) -> ChaincodeEventsRequest {
86        let creator = self.signing_id.creator();
87        let start_position = Some(self.start_position());
88        let request = PbCcEventsRequest {
89            channel_id: self.channel_name,
90            chaincode_id: self.chaincode_name,
91            identity: creator,
92            start_position,
93            after_transaction_id: self.after_transaction_id,
94        };
95        let signed = SignedChaincodeEventsRequest {
96            request: request.encode_to_vec(),
97            signature: Vec::new(),
98        };
99        ChaincodeEventsRequest {
100            client: self.client,
101            signing_id: self.signing_id,
102            signed_request: signed,
103        }
104    }
105}
106
107/// A signed request that streams chaincode events.
108pub struct ChaincodeEventsRequest {
109    client: GrpcClient,
110    signing_id: SigningIdentity,
111    signed_request: SignedChaincodeEventsRequest,
112}
113
114impl ChaincodeEventsRequest {
115    /// Serialised request bytes (off-line signing).
116    pub fn bytes(&self) -> Vec<u8> {
117        self.signed_request.encode_to_vec()
118    }
119
120    /// Digest of the request, for off-line signing.
121    pub fn digest(&self) -> Vec<u8> {
122        self.signing_id.hash(&self.signed_request.request)
123    }
124
125    fn sign(&mut self) -> Result<(), GatewayError> {
126        if !self.signed_request.signature.is_empty() {
127            return Ok(());
128        }
129        let digest = self.digest();
130        self.signed_request.signature = self.signing_id.sign(&digest)?;
131        Ok(())
132    }
133
134    /// Open the event stream. Yields [`ChaincodeEvent`]s in ledger order. A
135    /// background task reads the gRPC stream and forwards flattened events,
136    /// mirroring the goroutine in fabric-gateway-go's `Events`.
137    pub async fn events(
138        mut self,
139    ) -> Result<Pin<Box<dyn Stream<Item = ChaincodeEvent> + Send>>, GatewayError> {
140        self.sign()?;
141        let mut stream = self.client.chaincode_events(self.signed_request).await?;
142
143        let (tx, rx) = tokio::sync::mpsc::channel::<ChaincodeEvent>(16);
144        tokio::spawn(async move {
145            while let Some(Ok(response)) = stream.next().await {
146                for event in flatten_events(response) {
147                    if tx.send(event).await.is_err() {
148                        return;
149                    }
150                }
151            }
152        });
153
154        Ok(Box::pin(tokio_stream::wrappers::ReceiverStream::new(rx)))
155    }
156}
157
158fn flatten_events(response: ChaincodeEventsResponse) -> Vec<ChaincodeEvent> {
159    let block_number = response.block_number;
160    response
161        .events
162        .into_iter()
163        .map(move |e| ChaincodeEvent {
164            block_number,
165            transaction_id: e.tx_id,
166            chaincode_name: e.chaincode_id,
167            event_name: e.event_name,
168            payload: e.payload,
169        })
170        .collect()
171}
172
173/// Builder for block / filtered-block event requests. Ports the
174/// `baseBlockEventsBuilder` seek-envelope construction.
175pub struct BlockEventsBuilder {
176    client: GrpcClient,
177    signing_id: SigningIdentity,
178    channel_name: String,
179    tls_certificate_hash: Vec<u8>,
180    start_position: Option<SeekPosition>,
181}
182
183impl BlockEventsBuilder {
184    pub(crate) fn new(
185        client: GrpcClient,
186        signing_id: SigningIdentity,
187        channel_name: String,
188        tls_certificate_hash: Vec<u8>,
189    ) -> Self {
190        Self {
191            client,
192            signing_id,
193            channel_name,
194            tls_certificate_hash,
195            start_position: None,
196        }
197    }
198
199    /// Read events starting at the specified block number.
200    pub fn with_start_block(mut self, block_number: u64) -> Self {
201        self.start_position = Some(SeekPosition {
202            r#type: Some(SeekType::Specified(SeekSpecified {
203                number: block_number,
204            })),
205        });
206        self
207    }
208
209    fn start_position(&self) -> SeekPosition {
210        self.start_position.unwrap_or(SeekPosition {
211            r#type: Some(SeekType::NextCommit(SeekNextCommit {})),
212        })
213    }
214
215    fn payload_bytes(&self) -> Vec<u8> {
216        let channel_header = ChannelHeader {
217            r#type: HeaderType::DeliverSeekInfo as i32,
218            version: 0,
219            timestamp: Some(now_timestamp()),
220            channel_id: self.channel_name.clone(),
221            tx_id: String::new(),
222            epoch: 0,
223            extension: Vec::new(),
224            tls_cert_hash: self.tls_certificate_hash.clone(),
225        };
226        let signature_header = SignatureHeader {
227            creator: self.signing_id.creator(),
228            nonce: Vec::new(),
229        };
230        // Seek from start position to the largest possible block number, so the
231        // stream continues indefinitely as blocks are committed.
232        let seek_info = SeekInfo {
233            start: Some(self.start_position()),
234            stop: Some(SeekPosition {
235                r#type: Some(SeekType::Specified(SeekSpecified { number: u64::MAX })),
236            }),
237            behavior: 0,
238            error_response: 0,
239            content_type: 0,
240        };
241        let payload = Payload {
242            header: Some(Header {
243                channel_header: channel_header.encode_to_vec(),
244                signature_header: signature_header.encode_to_vec(),
245            }),
246            data: seek_info.encode_to_vec(),
247        };
248        payload.encode_to_vec()
249    }
250
251    fn build_envelope(&self) -> Envelope {
252        Envelope {
253            payload: self.payload_bytes(),
254            signature: Vec::new(),
255        }
256    }
257
258    /// Build a request for full block events.
259    pub fn build_block(self) -> BlockEventsRequest {
260        let envelope = self.build_envelope();
261        BlockEventsRequest {
262            client: self.client,
263            signing_id: self.signing_id,
264            envelope,
265        }
266    }
267
268    /// Build a request for filtered block events.
269    pub fn build_filtered(self) -> FilteredBlockEventsRequest {
270        let envelope = self.build_envelope();
271        FilteredBlockEventsRequest {
272            client: self.client,
273            signing_id: self.signing_id,
274            envelope,
275        }
276    }
277}
278
279macro_rules! block_events_request {
280    ($name:ident, $item:ty, $open:ident, $extract:expr, $doc:literal) => {
281        #[doc = $doc]
282        pub struct $name {
283            client: GrpcClient,
284            signing_id: SigningIdentity,
285            envelope: Envelope,
286        }
287
288        impl $name {
289            /// Serialised seek envelope bytes (off-line signing).
290            pub fn bytes(&self) -> Vec<u8> {
291                self.envelope.encode_to_vec()
292            }
293
294            /// Digest of the seek envelope payload, for off-line signing.
295            pub fn digest(&self) -> Vec<u8> {
296                self.signing_id.hash(&self.envelope.payload)
297            }
298
299            fn sign(&mut self) -> Result<(), GatewayError> {
300                if !self.envelope.signature.is_empty() {
301                    return Ok(());
302                }
303                let digest = self.digest();
304                self.envelope.signature = self.signing_id.sign(&digest)?;
305                Ok(())
306            }
307
308            /// Open the event stream.
309            pub async fn events(
310                mut self,
311            ) -> Result<Pin<Box<dyn Stream<Item = $item> + Send>>, GatewayError> {
312                self.sign()?;
313                let mut stream = self.client.$open(self.envelope).await?;
314                let (tx, rx) = tokio::sync::mpsc::channel::<$item>(16);
315                tokio::spawn(async move {
316                    while let Some(Ok(response)) = stream.next().await {
317                        #[allow(clippy::redundant_closure_call)]
318                        if let Some(item) = ($extract)(response) {
319                            if tx.send(item).await.is_err() {
320                                return;
321                            }
322                        }
323                    }
324                });
325                Ok(Box::pin(tokio_stream::wrappers::ReceiverStream::new(rx)))
326            }
327        }
328    };
329}
330
331block_events_request!(
332    BlockEventsRequest,
333    Block,
334    block_events,
335    |r: crate::pb::protos::DeliverResponse| match r.r#type {
336        Some(crate::pb::protos::deliver_response::Type::Block(b)) => Some(b),
337        _ => None,
338    },
339    "Streams full block events from the peer's Deliver service."
340);
341
342block_events_request!(
343    FilteredBlockEventsRequest,
344    FilteredBlock,
345    filtered_block_events,
346    |r: crate::pb::protos::DeliverResponse| match r.r#type {
347        Some(crate::pb::protos::deliver_response::Type::FilteredBlock(b)) => Some(b),
348        _ => None,
349    },
350    "Streams filtered block events from the peer's Deliver service."
351);