utils.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{collections::HashMap, sync::Arc};
  19. use log::info;
  20. use smol::Executor;
  21. use darkfi::{
  22. error::TxVerifyFailed,
  23. net::{P2p, P2pPtr, Settings, SESSION_ALL},
  24. rpc::jsonrpc::JsonSubscriber,
  25. tx::Transaction,
  26. validator::ValidatorPtr,
  27. Result,
  28. };
  29. use darkfi_consensus_contract::{
  30. model::ConsensusGenesisStakeParamsV1, ConsensusFunction::GenesisStakeV1,
  31. };
  32. use darkfi_money_contract::{model::MoneyTokenMintParamsV1, MoneyFunction::GenesisMintV1};
  33. use darkfi_sdk::crypto::{CONSENSUS_CONTRACT_ID, MONEY_CONTRACT_ID};
  34. use darkfi_serial::deserialize;
  35. use crate::proto::{ProtocolBlock, ProtocolProposal, ProtocolSync, ProtocolTx};
  36. /// Auxiliary function to calculate the total amount of minted tokens in provided
  37. /// genesis transactions set. This includes both staked and normal tokens.
  38. /// If a non-genesis transaction is found, execution fails.
  39. /// Set must also include the genesis transaction(empty) at last position.
  40. pub fn genesis_txs_total(txs: &[Transaction]) -> Result<u64> {
  41. let mut total = 0;
  42. if txs.is_empty() {
  43. return Ok(total)
  44. }
  45. // Iterate transactions, exluding producer(last) one
  46. for tx in &txs[..txs.len() - 1] {
  47. // Transaction must contain a single Consensus::GenesisStake or Money::GenesisMint call
  48. if tx.calls.len() != 1 {
  49. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  50. }
  51. let call = &tx.calls[0];
  52. let function = call.data[0];
  53. if !(call.contract_id == *CONSENSUS_CONTRACT_ID || call.contract_id == *MONEY_CONTRACT_ID) ||
  54. (call.contract_id == *CONSENSUS_CONTRACT_ID && function != GenesisStakeV1 as u8) ||
  55. (call.contract_id == *MONEY_CONTRACT_ID && function != GenesisMintV1 as u8)
  56. {
  57. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  58. }
  59. let value = if function == GenesisStakeV1 as u8 {
  60. let params: ConsensusGenesisStakeParamsV1 = deserialize(&call.data[1..])?;
  61. params.input.value
  62. } else {
  63. let params: MoneyTokenMintParamsV1 = deserialize(&call.data[1..])?;
  64. params.input.value
  65. };
  66. total += value;
  67. }
  68. let tx = txs.last().unwrap();
  69. if tx != &Transaction::default() {
  70. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  71. }
  72. Ok(total)
  73. }
  74. /// Auxiliary function to generate the sync P2P network and register all its protocols.
  75. pub async fn spawn_sync_p2p(
  76. settings: &Settings,
  77. validator: &ValidatorPtr,
  78. subscribers: &HashMap<&'static str, JsonSubscriber>,
  79. executor: Arc<Executor<'static>>,
  80. ) -> P2pPtr {
  81. info!(target: "darkfid", "Registering sync network P2P protocols...");
  82. let p2p = P2p::new(settings.clone(), executor.clone()).await;
  83. let registry = p2p.protocol_registry();
  84. let _validator = validator.clone();
  85. let _subscriber = subscribers.get("blocks").unwrap().clone();
  86. registry
  87. .register(SESSION_ALL, move |channel, p2p| {
  88. let validator = _validator.clone();
  89. let subscriber = _subscriber.clone();
  90. async move { ProtocolBlock::init(channel, validator, p2p, subscriber).await.unwrap() }
  91. })
  92. .await;
  93. let _validator = validator.clone();
  94. registry
  95. .register(SESSION_ALL, move |channel, _p2p| {
  96. let validator = _validator.clone();
  97. async move { ProtocolSync::init(channel, validator).await.unwrap() }
  98. })
  99. .await;
  100. let _validator = validator.clone();
  101. let _subscriber = subscribers.get("txs").unwrap().clone();
  102. registry
  103. .register(SESSION_ALL, move |channel, p2p| {
  104. let validator = _validator.clone();
  105. let subscriber = _subscriber.clone();
  106. async move { ProtocolTx::init(channel, validator, p2p, subscriber).await.unwrap() }
  107. })
  108. .await;
  109. p2p
  110. }
  111. /// Auxiliary function to generate the consensus P2P network and register all its protocols.
  112. pub async fn spawn_consensus_p2p(
  113. settings: &Settings,
  114. validator: &ValidatorPtr,
  115. subscribers: &HashMap<&'static str, JsonSubscriber>,
  116. executor: Arc<Executor<'static>>,
  117. ) -> P2pPtr {
  118. info!(target: "darkfid", "Registering consensus network P2P protocols...");
  119. let p2p = P2p::new(settings.clone(), executor.clone()).await;
  120. let registry = p2p.protocol_registry();
  121. let _validator = validator.clone();
  122. let _subscriber = subscribers.get("proposals").unwrap().clone();
  123. registry
  124. .register(SESSION_ALL, move |channel, p2p| {
  125. let validator = _validator.clone();
  126. let subscriber = _subscriber.clone();
  127. async move { ProtocolProposal::init(channel, validator, p2p, subscriber).await.unwrap() }
  128. })
  129. .await;
  130. p2p
  131. }