utils.rs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 darkfi::{error::TxVerifyFailed, tx::Transaction, Result};
  19. use darkfi_consensus_contract::{
  20. model::ConsensusGenesisStakeParamsV1, ConsensusFunction::GenesisStakeV1,
  21. };
  22. use darkfi_money_contract::{model::MoneyTokenMintParamsV1, MoneyFunction::GenesisMintV1};
  23. use darkfi_sdk::crypto::{CONSENSUS_CONTRACT_ID, MONEY_CONTRACT_ID};
  24. use darkfi_serial::deserialize;
  25. /// Auxiliary function to calculate the total amount of minted tokens in provided
  26. /// genesis transactions set. This includes both staked and normal tokens.
  27. /// If a non-genesis transaction is found, execution fails.
  28. pub fn genesis_txs_total(txs: &[Transaction]) -> Result<u64> {
  29. let mut total = 0;
  30. for tx in txs {
  31. // Transaction must contain a single Consensus::GenesisStake or Money::GenesisMint call
  32. if tx.calls.len() != 1 {
  33. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  34. }
  35. let call = &tx.calls[0];
  36. let function = call.data[0];
  37. if !(call.contract_id == *CONSENSUS_CONTRACT_ID || call.contract_id == *MONEY_CONTRACT_ID) ||
  38. (call.contract_id == *CONSENSUS_CONTRACT_ID && function != GenesisStakeV1 as u8) ||
  39. (call.contract_id == *MONEY_CONTRACT_ID && function != GenesisMintV1 as u8)
  40. {
  41. return Err(TxVerifyFailed::ErroneousTxs(vec![tx.clone()]).into())
  42. }
  43. let value = if function == GenesisStakeV1 as u8 {
  44. let params: ConsensusGenesisStakeParamsV1 = deserialize(&call.data[1..])?;
  45. params.input.value
  46. } else {
  47. let params: MoneyTokenMintParamsV1 = deserialize(&call.data[1..])?;
  48. params.input.value
  49. };
  50. total += value;
  51. }
  52. Ok(total)
  53. }