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
use std::str::FromStr;
use prost::Message;
use crate::{
error::{BuilderError, SubmitError},
fabric::{
common::Payload,
discovery::{QueryResult, discovery_client::DiscoveryClient},
gateway::{
CommitStatusRequest, CommitStatusResponse, SignedCommitStatusRequest, SubmitRequest,
gateway_client::GatewayClient,
},
protos::{ChaincodeAction, ChaincodeActionPayload, ProposalResponsePayload, Transaction},
},
gateway::{
chaincode::{ChaincodeCallBuilder, PreparedChaincodeCall},
discovery::{DiscoveryCallBuilder, PreparedDiscoveryCall},
},
identity::Identity,
transaction::{generate_nonce, generate_transaction_id},
};
pub struct Client {
identity: Identity,
tonic_connection: TonicConnection,
}
struct TonicConnection {
tls_config: tonic::transport::ClientTlsConfig,
host: tonic::transport::Uri,
channel: Option<tonic::transport::Channel>,
}
impl Client {
pub async fn connect(&mut self) -> Result<(), tonic::transport::Error> {
self.tonic_connection.channel = Some(
tonic::transport::Channel::builder(self.tonic_connection.host.clone())
.tls_config(self.tonic_connection.tls_config.clone())
.expect("Invald TLS config")
.connect()
.await?,
);
Ok(())
}
/// A builder for creating `PreparedTransaction` instances, from which you can submit the transaction.
/// build() only prepares the transaction. It will not send anything to the network.
///
/// # Examples
///
/// ```rust
/// let tx_builder = client
/// .get_chaincode_builder()
/// .with_channel_name("mychannel")?
/// .with_chaincode_id("basic")?
/// .with_function_name("CreateAsset")?
/// .with_function_args(["assetCustom", "orange", "10", "Frank", "600"])?
/// .build();
/// match tx_builder {
/// Ok(prepared_transaction) => match client.submit_chaincode_call(prepared_transaction).await {
/// Ok(result) => {
/// println!("{}", String::from_utf8_lossy(result.as_slice()));
/// }
/// Err(err) => println!("{}", err),
/// },
/// Err(err) => println!("{}", err),
/// }
/// ```
pub fn get_chaincode_call_builder(&self) -> ChaincodeCallBuilder {
ChaincodeCallBuilder {
identity: self.identity.clone(),
channel_name: None,
chaincode_id: None,
contract_id: None,
function_name: None,
function_args: vec![],
proposal: None,
header: None,
nonce: None,
transaction_id: None,
}
}
pub fn get_discovery_call_builder(&self) -> DiscoveryCallBuilder {
DiscoveryCallBuilder {
identity: self.identity.clone(),
queries: vec![],
}
}
/// Submits a prepared transaction to the network. Changed will be transmitted to the orderer and the ledger will be affected from the chaincode call.
pub async fn submit_chaincode_call(
&self,
prepared_chaincode_call: PreparedChaincodeCall,
) -> Result<Vec<u8>, SubmitError> {
if self.tonic_connection.channel.is_none() {
return Err(SubmitError::NotConnected);
}
let mut gateway_client = GatewayClient::new(
self.tonic_connection
.channel
.as_ref()
.expect("Expected value is none.")
.clone(),
);
//First transaction will be endorsed to the network
let response = gateway_client
.endorse(prepared_chaincode_call.endorse_request)
.await;
match response {
Ok(response) => {
match response.into_inner().prepared_transaction {
Some(mut envelope) => {
//TODO CHECK SIGNATURES
let mut result = vec![];
if let Ok(payload) = Payload::decode(envelope.payload.as_slice())
&& let Ok(transaction) = Transaction::decode(payload.data.as_slice())
{
let mut payload_found = false;
for action in transaction.actions {
if let Ok(action) =
ChaincodeActionPayload::decode(action.payload.as_slice())
&& let Some(action) = action.action
&& let Ok(payload) = ProposalResponsePayload::decode(
action.proposal_response_payload.as_slice(),
)
&& let Ok(action) =
ChaincodeAction::decode(payload.extension.as_slice())
&& let Some(response) = action.response
{
result = response.payload;
payload_found = true;
}
}
if !payload_found {
return Err(SubmitError::NoPayload);
}
}
//Generate random bytes for transaction id and signature header
let nonce = generate_nonce();
envelope.signature = self.identity.sign_message(&envelope.payload);
//Create transaction id
let transaction_id = generate_transaction_id(
&nonce,
self.identity
.get_certificate_bytes()
.encode_to_vec()
.as_slice(),
);
let submit_request = SubmitRequest {
transaction_id: transaction_id.clone(),
channel_id: prepared_chaincode_call.channel_name.clone(),
prepared_transaction: Some(envelope),
};
match gateway_client.submit(submit_request).await {
Ok(_) => Ok(result),
Err(err) => Err(SubmitError::NodeError(
String::from_utf8_lossy(err.details()).into_owned(),
)),
}
}
None => Err(SubmitError::EmptyRespone),
}
}
Err(err) => Err(SubmitError::NodeError(
String::from_utf8_lossy(err.details()).into_owned(),
)),
}
}
/// Executes a chaincode call and does not send it to an orderer, therefore not affecting the ledger. This is good for read-only calls
pub async fn peek_chaincode_call(
&self,
prepared_chaincode_call: PreparedChaincodeCall,
) -> Result<Vec<u8>, SubmitError> {
if self.tonic_connection.channel.is_none() {
return Err(SubmitError::NotConnected);
}
let mut gateway_client = GatewayClient::new(
self.tonic_connection
.channel
.as_ref()
.expect("Expected value is none.")
.clone(),
);
//First transaction will be endorsed to the network
let response = gateway_client
.endorse(prepared_chaincode_call.endorse_request)
.await;
match response {
Ok(response) => {
match response.into_inner().prepared_transaction {
Some(envelope) => {
//TODO CHECK SIGNATURES
if let Ok(payload) = Payload::decode(envelope.payload.as_slice())
&& let Ok(transaction) = Transaction::decode(payload.data.as_slice())
{
for action in transaction.actions {
if let Ok(action) =
ChaincodeActionPayload::decode(action.payload.as_slice())
&& let Some(action) = action.action
&& let Ok(payload) = ProposalResponsePayload::decode(
action.proposal_response_payload.as_slice(),
)
&& let Ok(action) =
ChaincodeAction::decode(payload.extension.as_slice())
&& let Some(response) = action.response
{
return Ok(response.payload);
}
}
}
Err(SubmitError::NoPayload)
}
None => Err(SubmitError::EmptyRespone),
}
}
Err(err) => Err(SubmitError::NodeError(
String::from_utf8_lossy(err.details()).into_owned(),
)),
}
}
/// Discovery defines a service that serves information about the fabric network like which peers, orderers, chaincodes, etc.
pub async fn submit_discover_call(
&self,
prepared_discovery_call: PreparedDiscoveryCall,
) -> Result<Vec<QueryResult>, SubmitError> {
if self.tonic_connection.channel.is_none() {
return Err(SubmitError::NotConnected);
}
let mut discovery_client = DiscoveryClient::new(
self.tonic_connection
.channel
.as_ref()
.expect("Expected value is none.")
.clone(),
);
let response = discovery_client
.discover(prepared_discovery_call.request)
.await;
match response {
Ok(response) => {
Ok(response.into_inner().results)
}
Err(err) => Err(SubmitError::NodeError(
String::from_utf8_lossy(err.details()).into_owned(),
)),
}
}
/// Checks for the commit status of a given transaction
///
/// This method will run until the commit will occur if it hasn’t already committed. So only run this immidentialy after [`submit()`](submit).
pub async fn commit_status(
&self,
transaction_id: String,
channel_id: String,
) -> Result<CommitStatusResponse, SubmitError> {
if self.tonic_connection.channel.is_none() {
return Err(SubmitError::NotConnected);
}
let request = CommitStatusRequest {
transaction_id,
channel_id,
identity: self.identity.get_serialized_identity().encode_to_vec(),
};
let mut gateway_client = GatewayClient::new(
self.tonic_connection
.channel
.as_ref()
.expect("Expected value is none.")
.clone(),
);
let request = SignedCommitStatusRequest {
request: request.encode_to_vec(),
signature: self.identity.sign_message(&request.encode_to_vec()),
};
let response = gateway_client.commit_status(request).await;
match response {
Ok(response) => Ok(response.into_inner()),
Err(err) => Err(SubmitError::NodeError(
String::from_utf8_lossy(err.details()).into_owned(),
)),
}
}
/// Unimplemented.
/// The ChaincodeEvents service supplies a stream of responses, each containing all the events emitted by the requested chaincode for a specific block. The streamed responses are ordered by ascending block number. Responses are only returned for blocks that contain the requested events, while blocks not containing any of the requested events are skipped.
pub async fn chaincode_events(&self) {
unimplemented!()
}
}
/// The `ClientBuilder` struct is used to configure and build a `Client` instance. It provides methods to set various parameters required for creating a client, such as identity, signer, TLS configuration, scheme, and authority.
///
/// # Examples
///
/// ```rust
/// use fabric_sdk_rust::{client::ClientBuilder, identity::IdentityBuilder, signer::Signer};
///
/// let identity = IdentityBuilder::from_pem(std::fs::read(msp_signcert_path)?.as_slice())
/// .with_msp("Org1MSP")?
/// .build()?;
/// let mut client = ClientBuilder::new()
/// .with_identity(identity)?
/// .with_tls(tlsca_bytes)?
/// .with_sheme("https")?
/// .with_authority("localhost:7051")?
/// .build()?;
/// client.connect().await?;
/// ```
#[derive(Default)]
pub struct ClientBuilder {
identity: Option<Identity>,
tls: Option<Vec<u8>>,
scheme: Option<String>,
authority: Option<String>,
}
impl ClientBuilder {
pub fn new() -> ClientBuilder {
ClientBuilder::default()
}
/// Identity from the IdentityBuilder
/// # Example
/// ```rust
///use fabric_sdk_rust::{client::ClientBuilder, identity::IdentityBuilder, signer::Signer};
///
///let identity = IdentityBuilder::from_pem(pem_bytes)
/// .with_msp("Org1MSP")?
/// .build()?;
///
///let mut client = ClientBuilder::new()
/// .with_identity(identity)?;
pub fn with_identity(mut self, identity: Identity) -> Result<ClientBuilder, BuilderError> {
self.identity = Some(identity);
Ok(self)
}
/// Chooses which scheme is being used. Default value is `https`
pub fn with_scheme(mut self, scheme: impl Into<String>) -> Result<ClientBuilder, BuilderError> {
let scheme = scheme.into().trim().to_string();
if scheme.is_empty() {
return Err(BuilderError::InvalidParameter(
"scheme cannot be empty".into(),
));
}
self.scheme = Some(scheme);
Ok(self)
}
/// Tls for the grpc connection to the node.
/// The needed pem from the test network can be found here: `organizations/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem`
pub fn with_tls(mut self, bytes: impl Into<Vec<u8>>) -> Result<ClientBuilder, BuilderError> {
self.tls = Some(bytes.into());
Ok(self)
}
/// Authority for the grpc connection to the node. Default is `localhost:7051` which corresponds to the test network
pub fn with_authority(
mut self,
authority: impl Into<String>,
) -> Result<ClientBuilder, BuilderError> {
let authority = authority.into().trim().to_string();
if authority.is_empty() {
return Err(BuilderError::InvalidParameter(
"authority cannot be empty".into(),
));
}
self.authority = Some(authority);
Ok(self)
}
/// Collects and validates the values from the builder to build the client. Building does not start the connection to the node.
pub fn build(self) -> Result<Client, BuilderError> {
let identity = match self.identity {
Some(identity) => identity,
None => return Err(BuilderError::MissingParameter("identity".into())),
};
let tls = match self.tls {
Some(tls) => tls,
None => return Err(BuilderError::MissingParameter("tls".into())),
};
//TODO Allow custom tls config
let tls_config = tonic::transport::ClientTlsConfig::new()
.ca_certificate(tonic::transport::Certificate::from_pem(tls.as_slice()));
let scheme = match self.scheme {
Some(scheme) => scheme,
None => "https".to_string(),
};
let authority = match self.authority {
Some(authority) => authority,
None => "localhost:7051".to_string(),
};
let scheme =
tonic::codegen::http::uri::Scheme::from_str(scheme.as_str()).expect("Invalid scheme");
let uri_builder = tonic::transport::Uri::builder()
.scheme(scheme)
.authority(authority)
.path_and_query("/");
let uri = match uri_builder.build() {
Ok(uri) => uri,
Err(err) => return Err(BuilderError::InvalidParameter(err.to_string())),
};
let tonic_connection = TonicConnection {
tls_config,
host: uri,
channel: None,
};
Ok(Client {
identity,
tonic_connection,
})
}
}