1use std::collections::HashMap;
2use std::sync::{Arc, Mutex};
3
4use fabric_shim_protos::common as pb_common;
5use fabric_shim_protos::msp as pb_msp;
6use fabric_shim_protos::peer as pb;
7use fabric_shim_protos::peer::chaincode_message::Type as MsgType;
8use prost::Message;
9
10use crate::handler::PeerLink;
11use crate::iterators::{HistoryQueryIterator, StateQueryIterator};
12use crate::response::Response;
13use crate::{Error, Result};
14
15const COMPOSITE_KEY_NAMESPACE: char = '\u{0}';
17const MAX_UNICODE_RUNE: char = '\u{10FFFF}';
19
20pub(crate) struct StubCore {
22 pub(crate) link: PeerLink,
23 pub(crate) channel_id: String,
24 pub(crate) tx_id: String,
25 pub(crate) gate: tokio::sync::Mutex<()>,
28}
29
30impl StubCore {
31 pub(crate) async fn request(
32 &self,
33 msg_type: MsgType,
34 payload: Vec<u8>,
35 ) -> Result<pb::ChaincodeMessage> {
36 let _serialize = self.gate.lock().await;
37 self.link
38 .request(msg_type, payload, &self.channel_id, &self.tx_id)
39 .await
40 }
41}
42
43pub struct ChaincodeStub {
47 core: Arc<StubCore>,
48 args: Vec<Vec<u8>>,
49 decorations: HashMap<String, Vec<u8>>,
50 signed_proposal: Option<pb::SignedProposal>,
51 creator: Vec<u8>,
52 transient: HashMap<String, Vec<u8>>,
53 tx_timestamp: Option<prost_types::Timestamp>,
54 event: Arc<Mutex<Option<pb::ChaincodeEvent>>>,
55}
56
57impl ChaincodeStub {
58 pub(crate) fn new(
59 link: PeerLink,
60 channel_id: String,
61 tx_id: String,
62 input: pb::ChaincodeInput,
63 signed_proposal: Option<pb::SignedProposal>,
64 ) -> Result<Self> {
65 let mut creator = Vec::new();
66 let mut transient = HashMap::new();
67 let mut tx_timestamp = None;
68
69 if let Some(sp) = &signed_proposal {
70 let proposal = pb::Proposal::decode(sp.proposal_bytes.as_ref())?;
71 let header = pb_common::Header::decode(proposal.header.as_ref())?;
72
73 let channel_header = pb_common::ChannelHeader::decode(header.channel_header.as_ref())?;
74 tx_timestamp = channel_header.timestamp;
75
76 let signature_header =
77 pb_common::SignatureHeader::decode(header.signature_header.as_ref())?;
78 creator = signature_header.creator.to_vec();
79
80 let payload = pb::ChaincodeProposalPayload::decode(proposal.payload.as_ref())?;
81 transient = payload
82 .transient_map
83 .into_iter()
84 .map(|(k, v)| (k, v.to_vec()))
85 .collect();
86 }
87
88 Ok(Self {
89 core: Arc::new(StubCore {
90 link,
91 channel_id,
92 tx_id,
93 gate: tokio::sync::Mutex::new(()),
94 }),
95 args: input.args.iter().map(|a| a.to_vec()).collect(),
96 decorations: input
97 .decorations
98 .into_iter()
99 .map(|(k, v)| (k, v.to_vec()))
100 .collect(),
101 signed_proposal,
102 creator,
103 transient,
104 tx_timestamp,
105 event: Arc::new(Mutex::new(None)),
106 })
107 }
108
109 pub(crate) fn event_slot(&self) -> Arc<Mutex<Option<pb::ChaincodeEvent>>> {
110 self.event.clone()
111 }
112
113 pub fn get_tx_id(&self) -> &str {
116 &self.core.tx_id
117 }
118
119 pub fn get_channel_id(&self) -> &str {
120 &self.core.channel_id
121 }
122
123 pub fn get_tx_timestamp(&self) -> Result<prost_types::Timestamp> {
126 self.tx_timestamp
127 .ok_or_else(|| Error::Protocol("transaction has no timestamp (no proposal)".into()))
128 }
129
130 pub fn get_args(&self) -> &[Vec<u8>] {
133 &self.args
134 }
135
136 pub fn get_string_args(&self) -> Vec<String> {
137 self.args
138 .iter()
139 .map(|a| String::from_utf8_lossy(a).into_owned())
140 .collect()
141 }
142
143 pub fn get_function_and_args(&self) -> (String, Vec<String>) {
145 let mut args = self.get_string_args();
146 if args.is_empty() {
147 (String::new(), args)
148 } else {
149 let function = args.remove(0);
150 (function, args)
151 }
152 }
153
154 pub fn get_creator(&self) -> &[u8] {
158 &self.creator
159 }
160
161 pub fn get_creator_identity(&self) -> Result<pb_msp::SerializedIdentity> {
163 Ok(pb_msp::SerializedIdentity::decode(self.creator.as_slice())?)
164 }
165
166 pub fn get_transient(&self) -> &HashMap<String, Vec<u8>> {
167 &self.transient
168 }
169
170 pub fn get_decorations(&self) -> &HashMap<String, Vec<u8>> {
171 &self.decorations
172 }
173
174 pub fn get_signed_proposal(&self) -> Option<&pb::SignedProposal> {
175 self.signed_proposal.as_ref()
176 }
177
178 pub async fn get_state(&self, key: &str) -> Result<Vec<u8>> {
183 self.get_data(MsgType::GetState, key, "").await
184 }
185
186 pub async fn put_state(&self, key: &str, value: impl Into<Vec<u8>>) -> Result<()> {
187 self.put_data("", key, value.into()).await
188 }
189
190 pub async fn del_state(&self, key: &str) -> Result<()> {
191 self.del_data("", key).await
192 }
193
194 pub async fn get_state_by_range(
196 &self,
197 start_key: &str,
198 end_key: &str,
199 ) -> Result<StateQueryIterator> {
200 let (iter, _) = self.range_query("", start_key, end_key, None).await?;
201 Ok(iter)
202 }
203
204 pub async fn get_state_by_range_with_pagination(
206 &self,
207 start_key: &str,
208 end_key: &str,
209 page_size: i32,
210 bookmark: &str,
211 ) -> Result<(StateQueryIterator, pb::QueryResponseMetadata)> {
212 let meta = pb::QueryMetadata {
213 page_size,
214 bookmark: bookmark.to_string(),
215 };
216 let (iter, response_meta) = self.range_query("", start_key, end_key, Some(meta)).await?;
217 Ok((iter, response_meta.unwrap_or_default()))
218 }
219
220 pub async fn get_query_result(&self, query: &str) -> Result<StateQueryIterator> {
222 let payload = pb::GetQueryResult {
223 query: query.to_string(),
224 collection: String::new(),
225 metadata: Default::default(),
226 }
227 .encode_to_vec();
228 let reply = self.core.request(MsgType::GetQueryResult, payload).await?;
229 let resp = pb::QueryResponse::decode(reply.payload.as_ref())?;
230 Ok(StateQueryIterator::new(self.core.clone(), resp))
231 }
232
233 pub async fn get_history_for_key(&self, key: &str) -> Result<HistoryQueryIterator> {
235 let payload = pb::GetHistoryForKey {
236 key: key.to_string(),
237 }
238 .encode_to_vec();
239 let reply = self
240 .core
241 .request(MsgType::GetHistoryForKey, payload)
242 .await?;
243 let resp = pb::QueryResponse::decode(reply.payload.as_ref())?;
244 Ok(HistoryQueryIterator::new(self.core.clone(), resp))
245 }
246
247 pub fn create_composite_key(&self, object_type: &str, attributes: &[&str]) -> Result<String> {
250 create_composite_key(object_type, attributes)
251 }
252
253 pub fn split_composite_key(&self, composite_key: &str) -> Result<(String, Vec<String>)> {
254 split_composite_key(composite_key)
255 }
256
257 pub async fn get_state_by_partial_composite_key(
258 &self,
259 object_type: &str,
260 attributes: &[&str],
261 ) -> Result<StateQueryIterator> {
262 let prefix = create_composite_key(object_type, attributes)?;
263 let end = format!("{prefix}{MAX_UNICODE_RUNE}");
264 self.get_state_by_range(&prefix, &end).await
265 }
266
267 pub async fn get_private_data(&self, collection: &str, key: &str) -> Result<Vec<u8>> {
270 require_collection(collection)?;
271 self.get_data(MsgType::GetState, key, collection).await
272 }
273
274 pub async fn get_private_data_hash(&self, collection: &str, key: &str) -> Result<Vec<u8>> {
277 require_collection(collection)?;
278 self.get_data(MsgType::GetPrivateDataHash, key, collection)
279 .await
280 }
281
282 pub async fn put_private_data(
283 &self,
284 collection: &str,
285 key: &str,
286 value: impl Into<Vec<u8>>,
287 ) -> Result<()> {
288 require_collection(collection)?;
289 self.put_data(collection, key, value.into()).await
290 }
291
292 pub async fn del_private_data(&self, collection: &str, key: &str) -> Result<()> {
293 require_collection(collection)?;
294 self.del_data(collection, key).await
295 }
296
297 pub async fn purge_private_data(&self, collection: &str, key: &str) -> Result<()> {
298 require_collection(collection)?;
299 let payload = pb::PurgePrivateState {
300 key: key.to_string(),
301 collection: collection.to_string(),
302 }
303 .encode_to_vec();
304 self.core
305 .request(MsgType::PurgePrivateData, payload)
306 .await?;
307 Ok(())
308 }
309
310 pub async fn get_private_data_by_range(
311 &self,
312 collection: &str,
313 start_key: &str,
314 end_key: &str,
315 ) -> Result<StateQueryIterator> {
316 require_collection(collection)?;
317 let (iter, _) = self
318 .range_query(collection, start_key, end_key, None)
319 .await?;
320 Ok(iter)
321 }
322
323 pub fn set_event(&self, name: &str, payload: impl Into<Vec<u8>>) -> Result<()> {
328 if name.is_empty() {
329 return Err(Error::InvalidArgument(
330 "event name must not be empty".into(),
331 ));
332 }
333 *self.event.lock().unwrap() = Some(pb::ChaincodeEvent {
334 chaincode_id: String::new(), tx_id: self.core.tx_id.clone(),
336 event_name: name.to_string(),
337 payload: payload.into(),
338 });
339 Ok(())
340 }
341
342 pub async fn invoke_chaincode(
347 &self,
348 chaincode_name: &str,
349 args: Vec<Vec<u8>>,
350 channel: &str,
351 ) -> Result<Response> {
352 let name = if channel.is_empty() {
353 chaincode_name.to_string()
354 } else {
355 format!("{chaincode_name}/{channel}")
356 };
357 let payload = pb::ChaincodeSpec {
358 r#type: pb::chaincode_spec::Type::Undefined as i32,
359 chaincode_id: Some(pb::ChaincodeId {
360 name,
361 ..Default::default()
362 }),
363 input: Some(pb::ChaincodeInput {
364 args: args.into_iter().collect(),
365 decorations: HashMap::new(),
366 is_init: false,
367 }),
368 timeout: 0,
369 }
370 .encode_to_vec();
371
372 let reply = self.core.request(MsgType::InvokeChaincode, payload).await?;
373 let inner = pb::ChaincodeMessage::decode(reply.payload.as_ref())?;
375 match inner.r#type() {
376 MsgType::Completed => Ok(Response::from_proto(pb::Response::decode(
377 inner.payload.as_ref(),
378 )?)),
379 MsgType::Error => Err(Error::Peer(
380 String::from_utf8_lossy(&inner.payload).into_owned(),
381 )),
382 other => Err(Error::Protocol(format!(
383 "unexpected nested message type {other:?} from invoked chaincode"
384 ))),
385 }
386 }
387
388 async fn get_data(&self, msg_type: MsgType, key: &str, collection: &str) -> Result<Vec<u8>> {
391 let payload = pb::GetState {
392 key: key.to_string(),
393 collection: collection.to_string(),
394 }
395 .encode_to_vec();
396 let reply = self.core.request(msg_type, payload).await?;
397 Ok(reply.payload.to_vec())
398 }
399
400 async fn put_data(&self, collection: &str, key: &str, value: Vec<u8>) -> Result<()> {
401 if key.is_empty() {
402 return Err(Error::InvalidArgument("key must not be empty".into()));
403 }
404 let payload = pb::PutState {
405 key: key.to_string(),
406 value,
407 collection: collection.to_string(),
408 }
409 .encode_to_vec();
410 self.core.request(MsgType::PutState, payload).await?;
411 Ok(())
412 }
413
414 async fn del_data(&self, collection: &str, key: &str) -> Result<()> {
415 let payload = pb::DelState {
416 key: key.to_string(),
417 collection: collection.to_string(),
418 }
419 .encode_to_vec();
420 self.core.request(MsgType::DelState, payload).await?;
421 Ok(())
422 }
423
424 async fn range_query(
425 &self,
426 collection: &str,
427 start_key: &str,
428 end_key: &str,
429 metadata: Option<pb::QueryMetadata>,
430 ) -> Result<(StateQueryIterator, Option<pb::QueryResponseMetadata>)> {
431 let payload = pb::GetStateByRange {
432 start_key: start_key.to_string(),
433 end_key: end_key.to_string(),
434 collection: collection.to_string(),
435 metadata: metadata.map(|m| m.encode_to_vec()).unwrap_or_default(),
436 }
437 .encode_to_vec();
438 let reply = self.core.request(MsgType::GetStateByRange, payload).await?;
439 let resp = pb::QueryResponse::decode(reply.payload.as_ref())?;
440 let response_meta = if resp.metadata.is_empty() {
441 None
442 } else {
443 Some(pb::QueryResponseMetadata::decode(resp.metadata.as_ref())?)
444 };
445 Ok((
446 StateQueryIterator::new(self.core.clone(), resp),
447 response_meta,
448 ))
449 }
450}
451
452fn require_collection(collection: &str) -> Result<()> {
453 if collection.is_empty() {
454 return Err(Error::InvalidArgument(
455 "collection must not be empty".into(),
456 ));
457 }
458 Ok(())
459}
460
461pub fn create_composite_key(object_type: &str, attributes: &[&str]) -> Result<String> {
463 validate_composite_component(object_type)?;
464 let mut key = String::with_capacity(object_type.len() + 2);
465 key.push(COMPOSITE_KEY_NAMESPACE);
466 key.push_str(object_type);
467 key.push(COMPOSITE_KEY_NAMESPACE);
468 for attr in attributes {
469 validate_composite_component(attr)?;
470 key.push_str(attr);
471 key.push(COMPOSITE_KEY_NAMESPACE);
472 }
473 Ok(key)
474}
475
476pub fn split_composite_key(composite_key: &str) -> Result<(String, Vec<String>)> {
478 let stripped = composite_key
479 .strip_prefix(COMPOSITE_KEY_NAMESPACE)
480 .ok_or_else(|| Error::InvalidArgument("not a composite key".into()))?;
481 let mut parts = stripped
482 .split(COMPOSITE_KEY_NAMESPACE)
483 .filter(|p| !p.is_empty())
484 .map(String::from);
485 let object_type = parts
486 .next()
487 .ok_or_else(|| Error::InvalidArgument("composite key has no object type".into()))?;
488 Ok((object_type, parts.collect()))
489}
490
491fn validate_composite_component(s: &str) -> Result<()> {
492 if s.contains(COMPOSITE_KEY_NAMESPACE) || s.contains(MAX_UNICODE_RUNE) {
493 return Err(Error::InvalidArgument(format!(
494 "composite key component {s:?} contains U+0000 or U+10FFFF"
495 )));
496 }
497 Ok(())
498}