forked from tari-project/tari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase_node_grpc_server.rs
2133 lines (1963 loc) · 86.7 KB
/
base_node_grpc_server.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::{
cmp,
convert::{TryFrom, TryInto},
};
use borsh::{BorshDeserialize, BorshSerialize};
use either::Either;
use futures::{channel::mpsc, SinkExt};
use log::*;
use minotari_app_grpc::{
tari_rpc,
tari_rpc::{CalcType, Sorting},
};
use minotari_app_utilities::consts;
use tari_common_types::types::{Commitment, FixedHash, PublicKey, Signature};
use tari_comms::{Bytes, CommsNode};
use tari_core::{
base_node::{
comms_interface::CommsInterfaceError,
state_machine_service::states::StateInfo,
LocalNodeCommsInterface,
StateMachineHandle,
},
blocks::{Block, BlockHeader, NewBlockTemplate},
chain_storage::ChainStorageError,
consensus::{emission::Emission, ConsensusManager, NetworkConsensus},
iterators::NonOverlappingIntegerPairIter,
mempool::{service::LocalMempoolService, TxStorageResponse},
proof_of_work::PowAlgorithm,
transactions::transaction_components::Transaction,
};
use tari_p2p::{auto_update::SoftwareUpdaterHandle, services::liveness::LivenessHandle};
use tari_utilities::{hex::Hex, message_format::MessageFormat, ByteArray};
use tokio::task;
use tonic::{Request, Response, Status};
use crate::{
builder::BaseNodeContext,
config::GrpcMethod,
grpc::{
blocks::{block_fees, block_heights, block_size, GET_BLOCKS_MAX_HEIGHTS, GET_BLOCKS_PAGE_SIZE},
hash_rate::HashRateMovingAverage,
helpers::{mean, median},
},
BaseNodeConfig,
};
const LOG_TARGET: &str = "minotari::base_node::grpc";
const GET_TOKENS_IN_CIRCULATION_MAX_HEIGHTS: usize = 1_000_000;
const GET_TOKENS_IN_CIRCULATION_PAGE_SIZE: usize = 1_000;
// The maximum number of difficulty ints that can be requested at a time. These will be streamed to the
// client, so memory is not really a concern here, but a malicious client could request a large
// number here to keep the node busy
const GET_DIFFICULTY_MAX_HEIGHTS: u64 = 10_000;
const GET_DIFFICULTY_PAGE_SIZE: usize = 1_000;
// The maximum number of headers a client can request at a time. If the client requests more than
// this, this is the maximum that will be returned.
const LIST_HEADERS_MAX_NUM_HEADERS: u64 = 10_000;
// The number of headers to request via the local interface at a time. These are then streamed to
// client.
const LIST_HEADERS_PAGE_SIZE: usize = 10;
// The `num_headers` value if none is provided.
const LIST_HEADERS_DEFAULT_NUM_HEADERS: u64 = 10;
const BLOCK_TIMING_MAX_BLOCKS: u64 = 10_000;
pub struct BaseNodeGrpcServer {
node_service: LocalNodeCommsInterface,
mempool_service: LocalMempoolService,
network: NetworkConsensus,
state_machine_handle: StateMachineHandle,
consensus_rules: ConsensusManager,
software_updater: SoftwareUpdaterHandle,
comms: CommsNode,
liveness: LivenessHandle,
report_grpc_error: bool,
config: BaseNodeConfig,
}
impl BaseNodeGrpcServer {
pub fn from_base_node_context(ctx: &BaseNodeContext, config: BaseNodeConfig) -> Self {
Self {
node_service: ctx.local_node(),
mempool_service: ctx.local_mempool(),
network: ctx.network().into(),
state_machine_handle: ctx.state_machine(),
consensus_rules: ctx.consensus_rules().clone(),
software_updater: ctx.software_updater(),
comms: ctx.base_node_comms().clone(),
liveness: ctx.liveness(),
report_grpc_error: ctx.get_report_grpc_error(),
config,
}
}
pub fn report_error_flag(&self) -> bool {
self.report_grpc_error
}
fn is_method_enabled(&self, grpc_method: GrpcMethod) -> bool {
let mining_method = [
GrpcMethod::GetNewBlockTemplate,
GrpcMethod::GetNewBlock,
GrpcMethod::GetNewBlockBlob,
GrpcMethod::SubmitBlock,
GrpcMethod::SubmitBlockBlob,
GrpcMethod::GetTipInfo,
];
if self.config.mining_enabled && mining_method.contains(&grpc_method) {
return true;
}
!self.config.grpc_server_deny_methods.contains(&grpc_method)
}
}
pub fn obscure_error_if_true(report: bool, status: Status) -> Status {
if report {
status
} else {
warn!(target: LOG_TARGET, "Obscured status error: {}", status);
Status::new(status.code(), "Error has occurred. Details are obscured.")
}
}
pub async fn get_heights(
request: &tari_rpc::HeightRequest,
handler: LocalNodeCommsInterface,
) -> Result<(u64, u64), Status> {
block_heights(handler, request.start_height, request.end_height, request.from_tip).await
}
impl BaseNodeGrpcServer {}
#[tonic::async_trait]
impl tari_rpc::base_node_server::BaseNode for BaseNodeGrpcServer {
type FetchMatchingUtxosStream = mpsc::Receiver<Result<tari_rpc::FetchMatchingUtxosResponse, Status>>;
type GetActiveValidatorNodesStream = mpsc::Receiver<Result<tari_rpc::GetActiveValidatorNodesResponse, Status>>;
type GetBlocksStream = mpsc::Receiver<Result<tari_rpc::HistoricalBlock, Status>>;
type GetMempoolTransactionsStream = mpsc::Receiver<Result<tari_rpc::GetMempoolTransactionsResponse, Status>>;
type GetNetworkDifficultyStream = mpsc::Receiver<Result<tari_rpc::NetworkDifficultyResponse, Status>>;
type GetPeersStream = mpsc::Receiver<Result<tari_rpc::GetPeersResponse, Status>>;
type GetSideChainUtxosStream = mpsc::Receiver<Result<tari_rpc::GetSideChainUtxosResponse, Status>>;
type GetTemplateRegistrationsStream = mpsc::Receiver<Result<tari_rpc::GetTemplateRegistrationResponse, Status>>;
type GetTokensInCirculationStream = mpsc::Receiver<Result<tari_rpc::ValueAtHeightResponse, Status>>;
type ListHeadersStream = mpsc::Receiver<Result<tari_rpc::BlockHeaderResponse, Status>>;
type SearchKernelsStream = mpsc::Receiver<Result<tari_rpc::HistoricalBlock, Status>>;
type SearchUtxosStream = mpsc::Receiver<Result<tari_rpc::HistoricalBlock, Status>>;
#[allow(clippy::too_many_lines)]
async fn get_network_difficulty(
&self,
request: Request<tari_rpc::HeightRequest>,
) -> Result<Response<Self::GetNetworkDifficultyStream>, Status> {
if !self.is_method_enabled(GrpcMethod::GetNetworkDifficulty) {
return Err(Status::permission_denied(
"`GetNetworkDifficulty` method not made available",
));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
debug!(
target: LOG_TARGET,
"Incoming GRPC request for GetNetworkDifficulty: from_tip: {:?} start_height: {:?} end_height: {:?}",
request.from_tip,
request.start_height,
request.end_height
);
let mut handler = self.node_service.clone();
let (start_height, end_height) = get_heights(&request, handler.clone())
.await
.map_err(|e| obscure_error_if_true(report_error_flag, e))?;
let num_requested = end_height.checked_sub(start_height).ok_or(obscure_error_if_true(
report_error_flag,
Status::invalid_argument("Start height is more than end height"),
))?;
if num_requested > GET_DIFFICULTY_MAX_HEIGHTS {
return Err(obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!(
"Number of headers requested exceeds maximum. Expected less than {} but got {}",
GET_DIFFICULTY_MAX_HEIGHTS, num_requested
)),
));
}
let (mut tx, rx) = mpsc::channel(cmp::min(
usize::try_from(num_requested).map_err(|e| {
obscure_error_if_true(
report_error_flag,
Status::internal(format!("Error converting u64 to usize '{}'", e)),
)
})?,
GET_DIFFICULTY_PAGE_SIZE,
));
let mut sha3x_hash_rate_moving_average =
HashRateMovingAverage::new(PowAlgorithm::Sha3x, self.consensus_rules.clone());
let mut randomx_hash_rate_moving_average =
HashRateMovingAverage::new(PowAlgorithm::RandomX, self.consensus_rules.clone());
let page_iter =
NonOverlappingIntegerPairIter::new(start_height, end_height.saturating_add(1), GET_DIFFICULTY_PAGE_SIZE)
.map_err(|e| obscure_error_if_true(report_error_flag, Status::invalid_argument(e)))?;
task::spawn(async move {
for (start, end) in page_iter {
// headers are returned by height
let headers = match handler.get_headers(start..=end).await {
Ok(headers) => headers,
Err(err) => {
warn!(target: LOG_TARGET, "Base node service error: {:?}", err,);
let _ = tx
.send(Err(obscure_error_if_true(
report_error_flag,
Status::internal("Internal error when fetching blocks"),
)))
.await;
return;
},
};
if headers.is_empty() {
let _network_difficulty_response = tx.send(Err(obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("No blocks found within range {} - {}", start, end)),
)));
return;
}
for chain_header in &headers {
let current_difficulty = chain_header.accumulated_data().target_difficulty;
let current_timestamp = chain_header.header().timestamp;
let current_height = chain_header.header().height;
let pow_algo = chain_header.header().pow.pow_algo;
// update the moving average calculation with the header data
let current_hash_rate_moving_average = match pow_algo {
PowAlgorithm::RandomX => &mut randomx_hash_rate_moving_average,
PowAlgorithm::Sha3x => &mut sha3x_hash_rate_moving_average,
};
current_hash_rate_moving_average.add(current_height, current_difficulty);
let sha3x_estimated_hash_rate = sha3x_hash_rate_moving_average.average();
let randomx_estimated_hash_rate = randomx_hash_rate_moving_average.average();
let estimated_hash_rate = sha3x_estimated_hash_rate.saturating_add(randomx_estimated_hash_rate);
let difficulty = tari_rpc::NetworkDifficultyResponse {
difficulty: current_difficulty.as_u64(),
estimated_hash_rate,
sha3x_estimated_hash_rate,
randomx_estimated_hash_rate,
height: current_height,
timestamp: current_timestamp.as_u64(),
pow_algo: pow_algo.as_u64(),
};
if let Err(err) = tx.send(Ok(difficulty)).await {
warn!(target: LOG_TARGET, "Error sending difficulties via GRPC: {}", err);
return;
}
}
}
});
debug!(
target: LOG_TARGET,
"Sending GetNetworkDifficulty response stream to client"
);
Ok(Response::new(rx))
}
async fn get_mempool_transactions(
&self,
request: Request<tari_rpc::GetMempoolTransactionsRequest>,
) -> Result<Response<Self::GetMempoolTransactionsStream>, Status> {
if !self.is_method_enabled(GrpcMethod::GetMempoolTransactions) {
return Err(Status::permission_denied(
"`GetMempoolTransactions` method not made available",
));
}
let report_error_flag = self.report_error_flag();
let _request = request.into_inner();
debug!(target: LOG_TARGET, "Incoming GRPC request for GetMempoolTransactions",);
let mut mempool = self.mempool_service.clone();
let (mut tx, rx) = mpsc::channel(1000);
task::spawn(async move {
let transactions = match mempool.get_mempool_state().await {
Err(err) => {
warn!(target: LOG_TARGET, "Error communicating with base node: {}", err,);
return;
},
Ok(data) => data,
};
for transaction in transactions.unconfirmed_pool {
let transaction = match tari_rpc::Transaction::try_from(transaction) {
Ok(t) => t,
Err(e) => {
if tx
.send(Err(obscure_error_if_true(
report_error_flag,
Status::internal(format!("Error converting transaction: {}", e)),
)))
.await
.is_err()
{
// Sender has closed i.e the connection has dropped/request was abandoned
warn!(
target: LOG_TARGET,
"[get_mempool_transactions] GRPC request cancelled while sending response"
);
}
return;
},
};
if tx
.send(Ok(tari_rpc::GetMempoolTransactionsResponse {
transaction: Some(transaction),
}))
.await
.is_err()
{
// Sender has closed i.e the connection has dropped/request was abandoned
warn!(target: LOG_TARGET, "GRPC request cancelled while sending response");
}
}
});
debug!(target: LOG_TARGET, "Sending GetMempool response stream to client");
Ok(Response::new(rx))
}
// casting here is okay as a block cannot have more than u32 kernels
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::too_many_lines)]
async fn list_headers(
&self,
request: Request<tari_rpc::ListHeadersRequest>,
) -> Result<Response<Self::ListHeadersStream>, Status> {
if !self.is_method_enabled(GrpcMethod::ListHeaders) {
return Err(Status::permission_denied("`ListHeaders` method not made available"));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
debug!(
target: LOG_TARGET,
"Incoming GRPC request for ListHeaders: from_height: {}, num_headers:{}, sorting:{}",
request.from_height,
request.num_headers,
request.sorting
);
let mut handler = self.node_service.clone();
let tip = match handler.get_metadata().await {
Err(err) => {
warn!(target: LOG_TARGET, "Error communicating with base node: {}", err,);
return Err(obscure_error_if_true(
report_error_flag,
Status::internal(err.to_string()),
));
},
Ok(data) => data.best_block_height(),
};
let sorting: Sorting = request.sorting();
let num_headers = match request.num_headers {
0 => LIST_HEADERS_DEFAULT_NUM_HEADERS,
_ => request.num_headers,
};
let num_headers = cmp::min(num_headers, LIST_HEADERS_MAX_NUM_HEADERS);
let (mut tx, rx) = mpsc::channel(LIST_HEADERS_PAGE_SIZE);
let from_height = cmp::min(request.from_height, tip);
let (header_range, is_reversed) = if from_height == 0 {
match sorting {
Sorting::Desc => {
let from = match tip.overflowing_sub(num_headers) {
(_, true) => 0,
(res, false) => res + 1,
};
(from..=tip, true)
},
Sorting::Asc => (0..=num_headers.saturating_sub(1), false),
}
} else {
match sorting {
Sorting::Desc => {
let from = match from_height.overflowing_sub(num_headers) {
(_, true) => 0,
(res, false) => res + 1,
};
(from..=from_height, true)
},
Sorting::Asc => {
let to = from_height.saturating_add(num_headers).saturating_sub(1);
(from_height..=to, false)
},
}
};
let consensus_rules = self.consensus_rules.clone();
let page_iter = NonOverlappingIntegerPairIter::new(
*header_range.start(),
header_range.end().saturating_add(1),
LIST_HEADERS_PAGE_SIZE,
)
.map_err(|e| obscure_error_if_true(report_error_flag, Status::invalid_argument(e)))?;
task::spawn(async move {
debug!(
target: LOG_TARGET,
"Starting base node request {}-{}",
header_range.start(),
header_range.end()
);
let page_iter = if is_reversed {
Either::Left(page_iter.rev())
} else {
Either::Right(page_iter)
};
for (start, end) in page_iter {
debug!(target: LOG_TARGET, "Page: {}-{}", start, end);
let result_data = match handler.get_blocks(start..=end, true).await {
Err(err) => {
warn!(target: LOG_TARGET, "Internal base node service error: {}", err);
return;
},
Ok(data) => {
if is_reversed {
data.into_iter()
.map(|chain_block| {
let (block, acc_data, confirmations) = chain_block.dissolve();
match consensus_rules
.calculate_coinbase_and_fees(block.header.height, block.body.kernels())
{
Ok(total_block_reward) => Ok(tari_rpc::BlockHeaderResponse {
difficulty: acc_data.achieved_difficulty.into(),
num_transactions: block.body.kernels().len() as u32,
confirmations,
header: Some(block.header.into()),
reward: total_block_reward.into(),
}),
Err(e) => {
Err(obscure_error_if_true(report_error_flag, Status::internal(e))
.to_string())
},
}
})
.rev()
.collect::<Result<Vec<_>, String>>()
} else {
data.into_iter()
.map(|chain_block| {
let (block, acc_data, confirmations) = chain_block.dissolve();
match consensus_rules
.calculate_coinbase_and_fees(block.header.height, block.body.kernels())
{
Ok(total_block_reward) => Ok(tari_rpc::BlockHeaderResponse {
difficulty: acc_data.achieved_difficulty.into(),
num_transactions: block.body.kernels().len() as u32,
confirmations,
header: Some(block.header.into()),
reward: total_block_reward.into(),
}),
Err(e) => {
Err(obscure_error_if_true(report_error_flag, Status::internal(e))
.to_string())
},
}
})
.collect::<Result<Vec<_>, String>>()
}
},
};
match result_data {
Err(e) => {
error!(target: LOG_TARGET, "No result headers transmitted due to error: {}", e)
},
Ok(result_data) => {
let result_size = result_data.len();
debug!(target: LOG_TARGET, "Result headers: {}", result_size);
for response in result_data {
// header wont be none here as we just filled it in above
debug!(
target: LOG_TARGET,
"Sending block header: {}",
response.header.as_ref().map( | h| h.height).unwrap_or(0)
);
if tx.send(Ok(response)).await.is_err() {
// Sender has closed i.e the connection has dropped/request was abandoned
warn!(
target: LOG_TARGET,
"[list_headers] GRPC request cancelled while sending response"
);
return;
}
}
},
}
}
});
debug!(target: LOG_TARGET, "Sending ListHeaders response stream to client");
Ok(Response::new(rx))
}
async fn get_new_block_template(
&self,
request: Request<tari_rpc::NewBlockTemplateRequest>,
) -> Result<Response<tari_rpc::NewBlockTemplateResponse>, Status> {
if !self.is_method_enabled(GrpcMethod::GetNewBlockTemplate) {
return Err(Status::permission_denied(
"`GetNewBlockTemplate` method not made available",
));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
debug!(target: LOG_TARGET, "Incoming GRPC request for get new block template");
trace!(target: LOG_TARGET, "Request {:?}", request);
let algo = request
.algo
.map(|algo| u64::try_from(algo.pow_algo))
.ok_or_else(|| obscure_error_if_true(report_error_flag, Status::invalid_argument("PoW algo not provided")))?
.map_err(|e| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("Invalid PoW algo '{}'", e)),
)
})?;
let algo = PowAlgorithm::try_from(algo).map_err(|e| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("Invalid PoW algo '{}'", e)),
)
})?;
let mut handler = self.node_service.clone();
let new_template = handler
.get_new_block_template(algo, request.max_weight)
.await
.map_err(|e| {
warn!(
target: LOG_TARGET,
"Could not get new block template: {}",
e.to_string()
);
obscure_error_if_true(report_error_flag, Status::internal(e.to_string()))
})?;
let status_watch = self.state_machine_handle.get_status_info_watch();
let pow = algo as i32;
let response = tari_rpc::NewBlockTemplateResponse {
miner_data: Some(tari_rpc::MinerData {
reward: new_template.reward.into(),
target_difficulty: new_template.target_difficulty.as_u64(),
total_fees: new_template.total_fees.into(),
algo: Some(tari_rpc::PowAlgo { pow_algo: pow }),
}),
new_block_template: Some(
new_template
.try_into()
.map_err(|e| obscure_error_if_true(report_error_flag, Status::internal(e)))?,
),
initial_sync_achieved: status_watch.borrow().bootstrapped,
};
debug!(target: LOG_TARGET, "Sending GetNewBlockTemplate response to client");
Ok(Response::new(response))
}
async fn get_new_block(
&self,
request: Request<tari_rpc::NewBlockTemplate>,
) -> Result<Response<tari_rpc::GetNewBlockResult>, Status> {
if !self.is_method_enabled(GrpcMethod::GetNewBlock) {
return Err(Status::permission_denied("`GetNewBlock` method not made available"));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
debug!(target: LOG_TARGET, "Incoming GRPC request for get new block");
let block_template: NewBlockTemplate = request.try_into().map_err(|s| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("Malformed block template provided: {}", s)),
)
})?;
let mut handler = self.node_service.clone();
let new_block = match handler.get_new_block(block_template).await {
Ok(b) => b,
Err(CommsInterfaceError::ChainStorageError(ChainStorageError::InvalidArguments { message, .. })) => {
return Err(obscure_error_if_true(
report_error_flag,
Status::invalid_argument(message),
));
},
Err(CommsInterfaceError::ChainStorageError(ChainStorageError::CannotCalculateNonTipMmr(msg))) => {
let status = Status::with_details(
tonic::Code::FailedPrecondition,
msg,
Bytes::from_static(b"CannotCalculateNonTipMmr"),
);
return Err(obscure_error_if_true(report_error_flag, status));
},
Err(e) => {
return Err(obscure_error_if_true(
report_error_flag,
Status::internal(e.to_string()),
))
},
};
let gen_hash = handler
.get_header(0)
.await
.map_err(|_| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument("Tari genesis block not found".to_string()),
)
})?
.ok_or_else(|| {
obscure_error_if_true(
report_error_flag,
Status::not_found("Tari genesis block not found".to_string()),
)
})?
.hash()
.to_vec();
// construct response
let block_hash = new_block.hash().to_vec();
let mining_hash = match new_block.header.pow.pow_algo {
PowAlgorithm::Sha3x => new_block.header.mining_hash().to_vec(),
PowAlgorithm::RandomX => new_block.header.merge_mining_hash().to_vec(),
};
let block: Option<tari_rpc::Block> = Some(
new_block
.try_into()
.map_err(|e| obscure_error_if_true(report_error_flag, Status::internal(e)))?,
);
let response = tari_rpc::GetNewBlockResult {
block_hash,
block,
merge_mining_hash: mining_hash,
tari_unique_id: gen_hash,
};
debug!(target: LOG_TARGET, "Sending GetNewBlock response to client");
Ok(Response::new(response))
}
async fn get_new_block_blob(
&self,
request: Request<tari_rpc::NewBlockTemplate>,
) -> Result<Response<tari_rpc::GetNewBlockBlobResult>, Status> {
if !self.is_method_enabled(GrpcMethod::GetNewBlockBlob) {
return Err(Status::permission_denied("`GetNewBlockBlob` method not made available"));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
debug!(target: LOG_TARGET, "Incoming GRPC request for get new block blob");
let block_template: NewBlockTemplate = request.try_into().map_err(|s| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("Invalid block template: {}", s)),
)
})?;
let mut handler = self.node_service.clone();
let new_block = match handler.get_new_block(block_template).await {
Ok(b) => b,
Err(CommsInterfaceError::ChainStorageError(ChainStorageError::InvalidArguments { message, .. })) => {
return Err(obscure_error_if_true(
report_error_flag,
Status::invalid_argument(message),
));
},
Err(CommsInterfaceError::ChainStorageError(ChainStorageError::CannotCalculateNonTipMmr(msg))) => {
let status = Status::with_details(
tonic::Code::FailedPrecondition,
msg,
Bytes::from_static(b"CannotCalculateNonTipMmr"),
);
return Err(obscure_error_if_true(report_error_flag, status));
},
Err(e) => {
return Err(obscure_error_if_true(
report_error_flag,
Status::internal(e.to_string()),
))
},
};
// construct response
let block_hash = new_block.hash().to_vec();
let mining_hash = match new_block.header.pow.pow_algo {
PowAlgorithm::Sha3x => new_block.header.mining_hash().to_vec(),
PowAlgorithm::RandomX => new_block.header.merge_mining_hash().to_vec(),
};
let gen_hash = handler
.get_header(0)
.await
.map_err(|_| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument("Tari genesis block not found".to_string()),
)
})?
.ok_or_else(|| {
obscure_error_if_true(
report_error_flag,
Status::not_found("Tari genesis block not found".to_string()),
)
})?
.hash()
.to_vec();
let (header, block_body) = new_block.into_header_body();
let mut header_bytes = Vec::new();
BorshSerialize::serialize(&header, &mut header_bytes)
.map_err(|err| obscure_error_if_true(report_error_flag, Status::internal(err.to_string())))?;
let mut block_body_bytes = Vec::new();
BorshSerialize::serialize(&block_body, &mut block_body_bytes)
.map_err(|err| obscure_error_if_true(report_error_flag, Status::internal(err.to_string())))?;
let response = tari_rpc::GetNewBlockBlobResult {
block_hash,
header: header_bytes,
block_body: block_body_bytes,
merge_mining_hash: mining_hash,
utxo_mr: header.output_mr.to_vec(),
tari_unique_id: gen_hash,
};
debug!(target: LOG_TARGET, "Sending GetNewBlockBlob response to client");
Ok(Response::new(response))
}
async fn submit_block(
&self,
request: Request<tari_rpc::Block>,
) -> Result<Response<tari_rpc::SubmitBlockResponse>, Status> {
if !self.is_method_enabled(GrpcMethod::SubmitBlock) {
return Err(Status::permission_denied("`SubmitBlock` method not made available"));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
let block = Block::try_from(request).map_err(|e| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("Invalid block provided: {}", e)),
)
})?;
let block_height = block.header.height;
debug!(target: LOG_TARGET, "Miner submitted block: {}", block);
info!(
target: LOG_TARGET,
"Received SubmitBlock #{} request from client", block_height
);
let mut handler = self.node_service.clone();
let block_hash = handler
.submit_block(block)
.await
.map_err(|e| obscure_error_if_true(report_error_flag, Status::internal(e.to_string())))?
.to_vec();
debug!(
target: LOG_TARGET,
"Sending SubmitBlock #{} response to client", block_height
);
Ok(Response::new(tari_rpc::SubmitBlockResponse { block_hash }))
}
async fn submit_block_blob(
&self,
request: Request<tari_rpc::BlockBlobRequest>,
) -> Result<Response<tari_rpc::SubmitBlockResponse>, Status> {
if !self.is_method_enabled(GrpcMethod::SubmitBlockBlob) {
return Err(Status::permission_denied("`SubmitBlockBlob` method not made available"));
}
let report_error_flag = self.report_error_flag();
debug!(target: LOG_TARGET, "Received block blob from miner: {:?}", request);
let request = request.into_inner();
debug!(target: LOG_TARGET, "request: {:?}", request);
let mut header_bytes = request.header_blob.as_slice();
let mut body_bytes = request.body_blob.as_slice();
debug!(target: LOG_TARGET, "doing header");
let header = BorshDeserialize::deserialize(&mut header_bytes)
.map_err(|e| obscure_error_if_true(report_error_flag, Status::internal(e.to_string())))?;
debug!(target: LOG_TARGET, "doing body");
let body = BorshDeserialize::deserialize(&mut body_bytes)
.map_err(|e| obscure_error_if_true(report_error_flag, Status::internal(e.to_string())))?;
let block = Block::new(header, body);
let block_height = block.header.height;
debug!(target: LOG_TARGET, "Miner submitted block: {}", block);
info!(
target: LOG_TARGET,
"Received SubmitBlock #{} request from client", block_height
);
let mut handler = self.node_service.clone();
let block_hash = handler
.submit_block(block)
.await
.map_err(|e| obscure_error_if_true(report_error_flag, Status::internal(e.to_string())))?
.to_vec();
debug!(
target: LOG_TARGET,
"Sending SubmitBlock #{} response to client", block_height
);
Ok(Response::new(tari_rpc::SubmitBlockResponse { block_hash }))
}
async fn submit_transaction(
&self,
request: Request<tari_rpc::SubmitTransactionRequest>,
) -> Result<Response<tari_rpc::SubmitTransactionResponse>, Status> {
if !self.is_method_enabled(GrpcMethod::SubmitTransaction) {
return Err(Status::permission_denied(
"`SubmitTransaction` method not made available",
));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
let txn: Transaction = request
.transaction
.ok_or_else(|| obscure_error_if_true(report_error_flag, Status::invalid_argument("Transaction is empty")))?
.try_into()
.map_err(|e| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("Invalid transaction provided: {}", e)),
)
})?;
debug!(
target: LOG_TARGET,
"Received SubmitTransaction request from client ({} kernels, {} outputs, {} inputs)",
txn.body.kernels().len(),
txn.body.outputs().len(),
txn.body.inputs().len()
);
let mut handler = self.mempool_service.clone();
let res = handler.submit_transaction(txn).await.map_err(|e| {
error!(target: LOG_TARGET, "Error submitting:{}", e);
obscure_error_if_true(report_error_flag, Status::internal(e.to_string()))
})?;
let response = match res {
TxStorageResponse::UnconfirmedPool => tari_rpc::SubmitTransactionResponse {
result: tari_rpc::SubmitTransactionResult::Accepted.into(),
},
TxStorageResponse::ReorgPool |
TxStorageResponse::NotStoredAlreadySpent |
TxStorageResponse::NotStoredAlreadyMined => tari_rpc::SubmitTransactionResponse {
result: tari_rpc::SubmitTransactionResult::AlreadyMined.into(),
},
TxStorageResponse::NotStored |
TxStorageResponse::NotStoredOrphan |
TxStorageResponse::NotStoredConsensus |
TxStorageResponse::NotStoredFeeTooLow |
TxStorageResponse::NotStoredTimeLocked => tari_rpc::SubmitTransactionResponse {
result: tari_rpc::SubmitTransactionResult::Rejected.into(),
},
};
debug!(target: LOG_TARGET, "Sending SubmitTransaction response to client");
Ok(Response::new(response))
}
async fn transaction_state(
&self,
request: Request<tari_rpc::TransactionStateRequest>,
) -> Result<Response<tari_rpc::TransactionStateResponse>, Status> {
if !self.is_method_enabled(GrpcMethod::TransactionState) {
return Err(Status::permission_denied(
"`TransactionState` method not made available",
));
}
let report_error_flag = self.report_error_flag();
let request = request.into_inner();
let excess_sig: Signature = request
.excess_sig
.ok_or_else(|| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument("excess_sig not provided".to_string()),
)
})?
.try_into()
.map_err(|e| {
obscure_error_if_true(
report_error_flag,
Status::invalid_argument(format!("excess_sig could not be converted '{}'", e)),
)
})?;
debug!(
target: LOG_TARGET,
"Received TransactionState request from client ({} excess_sig)",
excess_sig
.to_json()
.unwrap_or_else(|e| format!("Failed to serialize signature '{}'", e)),
);
let mut node_handler = self.node_service.clone();
let mut mem_handler = self.mempool_service.clone();
let base_node_response = node_handler
.get_kernel_by_excess_sig(excess_sig.clone())
.await
.map_err(|e| {
error!(target: LOG_TARGET, "Error submitting query:{}", e);
obscure_error_if_true(report_error_flag, Status::internal(e.to_string()))
})?;
if !base_node_response.is_empty() {
let response = tari_rpc::TransactionStateResponse {
result: tari_rpc::TransactionLocation::Mined.into(),
};
debug!(
target: LOG_TARGET,
"Sending Transaction state response to client {:?}", response
);
return Ok(Response::new(response));
}
// Base node does not yet know of kernel excess sig, lets ask the mempool
let res = mem_handler
.get_transaction_state_by_excess_sig(excess_sig.clone())
.await
.map_err(|e| {
error!(target: LOG_TARGET, "Error submitting query:{}", e);
obscure_error_if_true(report_error_flag, Status::internal(e.to_string()))
})?;
let response = match res {
TxStorageResponse::UnconfirmedPool => tari_rpc::TransactionStateResponse {
result: tari_rpc::TransactionLocation::Mempool.into(),
},
TxStorageResponse::ReorgPool | TxStorageResponse::NotStoredAlreadySpent => {
tari_rpc::TransactionStateResponse {
result: tari_rpc::TransactionLocation::Unknown.into(), /* We return Unknown here as the mempool
* should not think its mined, but the
* node does not think it is. */
}
},
TxStorageResponse::NotStored |
TxStorageResponse::NotStoredConsensus |
TxStorageResponse::NotStoredOrphan |
TxStorageResponse::NotStoredFeeTooLow |
TxStorageResponse::NotStoredTimeLocked |
TxStorageResponse::NotStoredAlreadyMined => tari_rpc::TransactionStateResponse {
result: tari_rpc::TransactionLocation::NotStored.into(),
},
};
debug!(
target: LOG_TARGET,
"Sending Transaction state response to client {:?}", response
);
Ok(Response::new(response))
}
async fn get_peers(
&self,
_request: Request<tari_rpc::GetPeersRequest>,
) -> Result<Response<Self::GetPeersStream>, Status> {
if !self.is_method_enabled(GrpcMethod::GetPeers) {
return Err(Status::permission_denied("`GetPeers` method not made available"));
}
let report_error_flag = self.report_error_flag();
debug!(target: LOG_TARGET, "Incoming GRPC request for get all peers");
let peers = self
.comms
.peer_manager()