Skip to content

Rrp 745 2 block rpc confirm#43

Open
AkulovOleg wants to merge 2 commits intonomium-developfrom
RRP-745-2-Block-RPC-Confirm
Open

Rrp 745 2 block rpc confirm#43
AkulovOleg wants to merge 2 commits intonomium-developfrom
RRP-745-2-Block-RPC-Confirm

Conversation

@AkulovOleg
Copy link
Copy Markdown

No description provided.

SETTINGS.bitcoin_rpc.user);

if block_hash.len() != 64 {
error!(target: "shares", "Invalid block hash format: {}, expected 32-byte hex string (64 characters)", block_hash);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Information security] Отсутствует валидация формата хеша блока (проверяется только длина), возможна обработка некорректных/вредоносных данных

pub async fn is_block_in_blockchain(&self, block_hash: &str) -> Result<bool, RpcError> {
info!(target: "shares", "Checking existence of block {} in blockchain", block_hash);
info!(target: "shares", "Using RPC connection: URL={}, User={}",
format!("{}:{}", SETTINGS.bitcoin_rpc.url, SETTINGS.bitcoin_rpc.port),
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Information security] Логирование URL и пользователя Bitcoin RPC может помочь злоумышленнику в подборе учетных данных

error!(target: "shares", "Failed to initialize Bitcoin RPC service: {:?}", e);
match &e {
RpcError::Other(msg) => {
error!(target: "shares", "Configuration error: {}", msg);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Information security] Детальное сообщение об ошибке конфигурации раскрывает структуру настроек, что помогает злоумышленнику в атаке

SHARES_LOGGER__BITCOIN_RPC__URL=http://127.0.0.1
SHARES_LOGGER__BITCOIN_RPC__PORT=28554
SHARES_LOGGER__BITCOIN_RPC__USER=user
SHARES_LOGGER__BITCOIN_RPC__PASSWORD=pass
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Information security] Пример файла окружения содержит захардкоженные учетные данные (user/pass), что провоцирует их использование в продакшене

match self.client.send_json_rpc_request("getblockheader", serde_json::json!([block_hash])).await {
Ok(response) => {
info!(target: "shares", "Received response from RPC server for block {}", block_hash);
info!(target: "shares", "Full response: {}", response);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Information security] Логирование полного ответа от RPC-сервера может привести к утечке конфиденциальных данных (токенов, секретов) через логи

url = ""
port = 0
user = ""
password = ""
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Information security] Хранение пароля в конфигурационном файле в открытом виде повышает риск утечки учетных данных

match self.client.send_json_rpc_request("getblockheader", serde_json::json!([block_hash])).await {
Ok(response) => {
info!(target: "shares", "Received response from RPC server for block {}", block_hash);
info!(target: "shares", "Full response: {}", response);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Code quality] Избыточное логирование полного ответа RPC-сервера в production-среде создаёт ненужную нагрузку и потенциальные утечки данных


async fn store_share(&mut self, block: BlockFound) -> Result<(), ClickhouseError> {
self.batch.push(block);
let block_hash_hex = hex::encode(&block.block_hash);
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Code quality] Нарушение принципа единственной ответственности: логика проверки блока через RPC внедрена в класс хранилища, связывая уровни приложения

info!(target: "shares", "Processing block {} for storage in DB", block_hash_hex);
let max_retries = SETTINGS.processing.block_verification_max_retries;
let retry_delay_ms = SETTINGS.processing.block_verification_retry_delay_ms;
let rpc_service = match crate::services::bitcoin_rpc_service::BitcoinRpcService::new() {
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Code quality] При ошибке инициализации RPC-клиента блок немедленно отбрасывается без механизма повторной обработки или уведомления, что ведёт к потере данных

Ok(Self { client })
}

pub async fn is_block_in_blockchain(&self, block_hash: &str) -> Result<bool, RpcError> {
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Code quality] Отсутствуют unit-тесты для обработки ошибок RPC и крайних случаев валидации блоков, снижая надёжность критической логики

Ok(Self { client })
}

pub async fn is_block_in_blockchain(&self, block_hash: &str) -> Result<bool, RpcError> {
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Code quality] Метод is_block_in_blockchain превышает 80 строк и содержит вложенную обработку ошибок, что снижает читаемость и усложняет тестирование

info!(target: "shares", "Processing block {} for storage in DB", block_hash_hex);
let max_retries = SETTINGS.processing.block_verification_max_retries;
let retry_delay_ms = SETTINGS.processing.block_verification_retry_delay_ms;
let rpc_service = match crate::services::bitcoin_rpc_service::BitcoinRpcService::new() {
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Code quality] Для каждого блока создаётся новый экземпляр BitcoinRpcService вместо переиспользования, что приводит к лишним аллокациям и накладным расходам на установку соединения

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants