diff --git a/blockchain/apply_valid_block.rs b/blockchain/apply_valid_block.rs index f3b8c713dc3fd2e0eb7867beee976aff9d05aae2..23e781dffa3435ba91acb69e17685071ae1a7f63 100644 --- a/blockchain/apply_valid_block.rs +++ b/blockchain/apply_valid_block.rs @@ -205,7 +205,7 @@ pub fn apply_valid_block<W: WebOfTrust, B: Backend + Debug>( members_pubkeys.push(*pubkey); } } - currency_dbs_requests.push(CurrencyDBsWriteQuery::CreateDU( + currency_dbs_requests.push(CurrencyDBsWriteQuery::CreateUD( SourceAmount(TxAmount(du_amount as isize), TxBase(block.unit_base)), block.number, members_pubkeys, diff --git a/blockchain/revert_block.rs b/blockchain/revert_block.rs index d4298de416109b3ca7921c4340ceb28715223524..497b5320f982d7d6293f4dd1978fe1039b5a099a 100644 --- a/blockchain/revert_block.rs +++ b/blockchain/revert_block.rs @@ -80,7 +80,7 @@ pub fn revert_block<W: WebOfTrust, B: Backend + Debug>( for dal_tx in dal_txs.iter().rev() { currency_dbs_requests.push(CurrencyDBsWriteQuery::RevertTx(Box::new(dal_tx.clone()))); } - // Revert DU + // Revert UD if let Some(du_amount) = block.dividend { if du_amount > 0 { let members_wot_ids = wot_db @@ -92,7 +92,7 @@ pub fn revert_block<W: WebOfTrust, B: Backend + Debug>( members_pubkeys.push(*pubkey); } } - currency_dbs_requests.push(CurrencyDBsWriteQuery::RevertDU( + currency_dbs_requests.push(CurrencyDBsWriteQuery::RevertUD( SourceAmount(TxAmount(du_amount as isize), TxBase(block.unit_base)), block.number, members_pubkeys, diff --git a/dal/balance.rs b/dal/balance.rs index 4e751dfc1ea2680d9bc90bba4c39821a9ec41db6..242fe2817709404d14099192b2d61e06ba4274f2 100644 --- a/dal/balance.rs +++ b/dal/balance.rs @@ -16,6 +16,7 @@ use sources::*; use *; +/// Get address balance pub fn get_address_balance( balances_db: &BinFileDB<BalancesV10Datas>, address: &UTXOConditionsGroup, diff --git a/dal/block.rs b/dal/block.rs index 68a6db36a4acf7341bfe8c1e3e66c11949f348fb..42a5f756893b20b07d13ea757ed25115af640b36 100644 --- a/dal/block.rs +++ b/dal/block.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + extern crate rustbreak; extern crate serde; @@ -11,9 +26,13 @@ use std::collections::HashMap; use *; #[derive(Clone, Debug, Deserialize, Serialize)] +/// A block as it is saved in a database pub struct DALBlock { + /// Fork id pub fork_id: ForkId, + /// True only if the block is on an isolated fork pub isolate: bool, + /// Block document pub block: BlockDocument, /// List of certifications that expire in this block. /// Warning : BlockId contain the emission block, not the written block ! @@ -22,11 +41,13 @@ pub struct DALBlock { } impl DALBlock { + /// Get blockstamp pub fn blockstamp(&self) -> Blockstamp { self.block.blockstamp() } } +///Get forks status pub fn get_forks( forks_db: &BinFileDB<ForksV10Datas>, current_blockstamp: Blockstamp, @@ -82,7 +103,7 @@ pub fn get_forks( forks })?) } - +/// get current blockstamp pub fn get_current_blockstamp(blocks_db: &BlocksV10DBs) -> Result<Option<Blockstamp>, DALError> { let current_previous_blockstamp = blocks_db.blockchain_db.read(|db| { let blockchain_len = db.len() as u32; @@ -137,6 +158,7 @@ pub fn get_fork_id_of_blockstamp( } impl DALBlock { + /// Delete fork pub fn delete_fork( forks_db: &BinFileDB<ForksV10Datas>, forks_blocks_db: &BinFileDB<ForksBlocksV10Datas>, @@ -161,6 +183,7 @@ impl DALBlock { })?; Ok(()) } + /// Assign fork id to new block pub fn assign_fork_to_new_block( forks_db: &BinFileDB<ForksV10Datas>, new_block_previous_blockstamp: &PreviousBlockstamp, @@ -207,6 +230,7 @@ impl DALBlock { })?; Ok((Some(new_fork_id), true)) } + /// Get fork block pub fn get_block_fork( forks_db: &BinFileDB<ForksV10Datas>, previous_blockstamp: &PreviousBlockstamp, @@ -220,6 +244,7 @@ impl DALBlock { None })?) } + /// Get block hash pub fn get_block_hash( db: &BinFileDB<LocalBlockchainV10Datas>, block_number: BlockId, @@ -232,7 +257,7 @@ impl DALBlock { } })?) } - + /// Return true if the node already knows this block pub fn already_have_block( blockchain_db: &BinFileDB<LocalBlockchainV10Datas>, forks_blocks_db: &BinFileDB<ForksBlocksV10Datas>, @@ -252,7 +277,7 @@ impl DALBlock { Ok(true) } } - + /// Get stackables blocks pub fn get_stackables_blocks( forks_db: &BinFileDB<ForksV10Datas>, forks_blocks_db: &BinFileDB<ForksBlocksV10Datas>, @@ -282,6 +307,7 @@ impl DALBlock { })?; Ok(stackables_blocks) } + /// Get stackables forks pub fn get_stackables_forks( db: &BinFileDB<ForksV10Datas>, current_blockstamp: &Blockstamp, @@ -298,6 +324,7 @@ impl DALBlock { stackables_forks })?) } + /// Get block pub fn get_block( blockchain_db: &BinFileDB<LocalBlockchainV10Datas>, forks_blocks_db: Option<&BinFileDB<ForksBlocksV10Datas>>, @@ -312,7 +339,7 @@ impl DALBlock { Ok(dal_block) } } - + /// Get block in local blockchain pub fn get_block_in_local_blockchain( db: &BinFileDB<LocalBlockchainV10Datas>, block_id: BlockId, @@ -325,7 +352,7 @@ impl DALBlock { } })?) } - + /// Get current frame of calculating members pub fn get_current_frame( &self, db: &BinFileDB<LocalBlockchainV10Datas>, @@ -350,7 +377,7 @@ impl DALBlock { current_frame })?) } - + /// Compute median issuers frame pub fn compute_median_issuers_frame(&mut self, db: &BinFileDB<LocalBlockchainV10Datas>) -> () { let current_frame = self .get_current_frame(db) diff --git a/dal/constants.rs b/dal/constants.rs index 5e210fef37fb7cff9d3bfc33f6b46738617d0194..8536e6232c487fc6364be16ffdb37366a08af12d 100644 --- a/dal/constants.rs +++ b/dal/constants.rs @@ -1,4 +1,23 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +/// Default value for sig_renew_period parameter pub static DEFAULT_SIG_RENEW_PERIOD: &'static u64 = &5_259_600; +/// Default value for ms_period parameter pub static DEFAULT_MS_PERIOD: &'static u64 = &5_259_600; +/// Default value for tx_window parameter pub static DEFAULT_TX_WINDOW: &'static u64 = &604_800; +/// Maximum number of forks that can be registered pub static MAX_FORKS: &'static usize = &100; diff --git a/dal/currency_params.rs b/dal/currency_params.rs index 6bf742e3fcea053bf02ca97ab5c9843d91b7e6ef..daf0332aa9e509a02e3457138dc6afa198f5f0b3 100644 --- a/dal/currency_params.rs +++ b/dal/currency_params.rs @@ -1,32 +1,74 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + use constants::*; use duniter_documents::blockchain::v10::documents::block::{BlockV10Parameters, CurrencyName}; use *; #[derive(Debug, Copy, Clone)] +/// Curerncy parameters pub struct CurrencyParameters { + /// Protocol version pub protocol_version: usize, + /// UD target growth rate (see Relative Theorie of Money) pub c: f64, + /// Duration between the creation of two UD (in seconds) pub dt: u64, + /// Amount of the initial UD pub ud0: usize, + /// Minimum duration between the writing of 2 certifications from the same issuer (in seconds) pub sig_period: u64, + /// Minimum duration between two renewals of the same certification pub sig_renew_period: u64, + /// Maximum number of active certifications at the same time (for the same issuer) pub sig_stock: usize, + /// Maximum retention period of a pending certification pub sig_window: u64, + /// Time to expiry of written certification pub sig_validity: u64, + /// Minimum number of certifications required to become a member pub sig_qty: usize, + /// Maximum retention period of a pending identity pub idty_window: u64, + /// Maximum retention period of a pending membership pub ms_window: u64, + /// Maximum retention period of a pending transaction pub tx_window: u64, + /// Percentage of referring members who must be within step_max steps of each member pub x_percent: f64, + /// Time to expiry of written membership pub ms_validity: u64, + /// Minimum duration between the writing of 2 memberships from the same issuer (in seconds) pub ms_period: u64, + /// For a member to respect the distance rule, + /// there must exist for more than x_percent % of the referring members + /// a path of less than step_max steps from the referring member to the evaluated member. pub step_max: usize, + /// Number of blocks used for calculating median time. pub median_time_blocks: usize, + /// The average time for writing 1 block (wished time) pub avg_gen_time: u64, + /// The number of blocks required to evaluate again PoWMin value pub dt_diff_eval: usize, + /// The percent of previous issuers to reach for personalized difficulty pub percent_rot: f64, + /// Time of first UD. pub ud_time0: u64, + /// Time of first reevaluation of the UD. pub ud_reeval_time0: u64, + /// Time period between two re-evaluation of the UD. pub dt_reeval: u64, } diff --git a/dal/dal_event.rs b/dal/dal_event.rs index 954be790e19b14af4c563391b3cccf93a2281a95..cdc27e5e97d70bfdd6ae6b275b49a78797409bd6 100644 --- a/dal/dal_event.rs +++ b/dal/dal_event.rs @@ -1,11 +1,31 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + use duniter_documents::blockchain::v10::documents::BlockDocument; use duniter_documents::blockchain::BlockchainProtocol; use duniter_documents::Blockstamp; #[derive(Debug, Clone)] +/// Event to be transmitted to the other modules pub enum DALEvent { + /// Stack up new valid block in local blockchain StackUpValidBlock(Box<BlockDocument>, Blockstamp), + /// Revert blocks in local blockchain RevertBlocks(Vec<Box<BlockDocument>>), + /// Receive new valid pending document NewValidPendingDoc(BlockchainProtocol), + /// Receive new refused pending document RefusedPendingDoc(BlockchainProtocol), } diff --git a/dal/dal_requests.rs b/dal/dal_requests.rs index eb1f30a990d43567e2719b0e5e3284d954cc7cec..366a5cb570da1c818ff3ef8648c3d52f6a6f78a5 100644 --- a/dal/dal_requests.rs +++ b/dal/dal_requests.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + extern crate duniter_module; extern crate serde; @@ -10,52 +25,82 @@ use duniter_documents::{Blockstamp, Hash}; use std::collections::HashMap; #[derive(Debug, Clone)] +/// Inter-module DAL request for pool data pub enum DALReqPendings { - AllPendingIdentyties(ModuleReqFullId, usize), - AllPendingIdentytiesWithoutCerts(ModuleReqFullId, usize), + /// All pending identities with their pending certifications + AllPendingIdentities(ModuleReqFullId, usize), + /// All pending identities without their pending certifications + AllPendingIdentitiesWithoutCerts(ModuleReqFullId, usize), + /// All pending datas for given pubkey PendingWotDatasForPubkey(ModuleReqFullId, PubKey), } #[derive(Debug, Clone, PartialEq)] +/// Inter-module DAL request for blockchain data pub enum DALReqBlockchain { + /// Current block CurrentBlock(ModuleReqFullId), + /// Block by number BlockByNumber(ModuleReqFullId, u64), + /// Chunk (block pack) Chunk(ModuleReqFullId, u64, usize), + /// Usernames corresponding to the public keys in parameter UIDs(Vec<PubKey>), } #[derive(Debug, Clone)] +/// Inter-module DAL request pub enum DALRequest { + /// Inter-module DAL request for blockchain data BlockchainRequest(DALReqBlockchain), + /// Inter-module DAL request for pool data PendingsRequest(DALReqPendings), } #[derive(Debug, Clone)] +/// Pending identity datas pub struct PendingIdtyDatas { + /// Identity document pub idty: IdentityDocument, + /// Membership document pub memberships: Vec<MembershipDocument>, + /// Number of certifications received pub certs_count: usize, + /// Certifications documents pub certs: Vec<CertificationDocument>, + /// Revocation document (None if identity has not been revoked) pub revocation: Option<RevocationDocument>, } #[derive(Debug, Clone)] +/// Response to a DALReqPendings request pub enum DALResPendings { - AllPendingIdentyties(HashMap<Hash, PendingIdtyDatas>), - AllPendingIdentytiesWithoutCerts(HashMap<Hash, PendingIdtyDatas>), - PendingWotDatasForPubkey(Vec<PendingIdtyDatas>), + /// All pending identities with their pending certifications + AllPendingIdentities(HashMap<Hash, PendingIdtyDatas>), + /// All pending identities without their pending certifications + AllPendingIdentitiesWithoutCerts(HashMap<Hash, PendingIdtyDatas>), + /// All pending datas for given pubkey + PendingWotDatasForPubkey(PendingIdtyDatas), } #[derive(Debug, Clone)] +/// Response to a DALReqBlockchain request pub enum DALResBlockchain { + /// Current block CurrentBlock(ModuleReqFullId, Box<BlockDocument>, Blockstamp), + /// Block by number BlockByNumber(ModuleReqFullId, Box<BlockDocument>), + /// Chunk (block pack) Chunk(ModuleReqFullId, Vec<BlockDocument>), + /// Usernames corresponding to the public keys in parameter UIDs(HashMap<PubKey, Option<String>>), } #[derive(Debug, Clone)] +/// Response to a DAL request pub enum DALResponse { + /// Response to a DALReqBlockchain request Blockchain(Box<DALResBlockchain>), + /// Response to a DALReqPendings request Pendings(ModuleReqFullId, DALResPendings), } diff --git a/dal/identity.rs b/dal/identity.rs index ee35e4c3bec9660eb847b7e024ed4b81fd922006..268fd90df0543445a474b3ef5c651ea76df60b65 100644 --- a/dal/identity.rs +++ b/dal/identity.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + use currency_params::CurrencyParameters; use duniter_crypto::keys::*; use duniter_documents::blockchain::v10::documents::IdentityDocument; @@ -9,28 +24,46 @@ use std::fmt::Debug; use {BinDB, DALError, IdentitiesV10Datas, MsExpirV10Datas}; #[derive(Clone, Debug, Deserialize, Serialize)] +/// Identity state pub enum DALIdentityState { + /// Member Member(Vec<usize>), + /// Expire Member ExpireMember(Vec<usize>), + /// Explicit Revoked ExplicitRevoked(Vec<usize>), + /// Explicit Revoked after expire ExplicitExpireRevoked(Vec<usize>), + /// Implicit revoked ImplicitRevoked(Vec<usize>), } #[derive(Clone, Debug, Deserialize, Serialize)] +/// Identity in database pub struct DALIdentity { + /// Identity hash pub hash: String, + /// Identity state pub state: DALIdentityState, + /// Blockstamp the identity was written pub joined_on: Blockstamp, + /// Blockstamp the identity was expired pub expired_on: Option<Blockstamp>, + /// Blockstamp the identity was revoked pub revoked_on: Option<Blockstamp>, + /// Identity document pub idty_doc: IdentityDocument, + /// Identity wot id pub wot_id: NodeId, + /// Membership created block number pub ms_created_block_id: BlockId, + /// Timestamp from which membership can be renewed pub ms_chainable_on: Vec<u64>, + /// Timestamp from which the identity can write a new certification pub cert_chainable_on: Vec<u64>, } +/// Get uid from pubkey pub fn get_uid<B: Backend + Debug>( identities_db: &BinDB<IdentitiesV10Datas, B>, pubkey: PubKey, @@ -44,6 +77,7 @@ pub fn get_uid<B: Backend + Debug>( })?) } +/// Get pubkey from uid pub fn get_pubkey_from_uid<B: Backend + Debug>( identities_db: &BinDB<IdentitiesV10Datas, B>, uid: &str, @@ -59,6 +93,7 @@ pub fn get_pubkey_from_uid<B: Backend + Debug>( } impl DALIdentity { + /// Apply "exclude identity" event pub fn exclude_identity<B: Backend + Debug>( identities_db: &BinDB<IdentitiesV10Datas, B>, pubkey: &PubKey, @@ -95,6 +130,7 @@ impl DALIdentity { Ok(()) } + /// Get wot_id index pub fn get_wotb_index<B: Backend + Debug>( identities_db: &BinDB<IdentitiesV10Datas, B>, ) -> Result<HashMap<PubKey, NodeId>, DALError> { @@ -108,6 +144,7 @@ impl DALIdentity { })?) } + /// Apply "revoke identity" event pub fn revoke_identity<B: Backend + Debug>( identities_db: &BinDB<IdentitiesV10Datas, B>, pubkey: &PubKey, @@ -155,6 +192,7 @@ impl DALIdentity { Ok(()) } + /// Apply "renewal identity" event in databases pub fn renewal_identity<B: Backend + Debug>( &mut self, currency_params: &CurrencyParameters, @@ -220,6 +258,7 @@ impl DALIdentity { Ok(()) } + /// Remove identity from databases pub fn remove_identity<B: Backend + Debug>( db: &BinDB<IdentitiesV10Datas, B>, pubkey: PubKey, @@ -230,6 +269,7 @@ impl DALIdentity { Ok(()) } + /// Get identity in databases pub fn get_identity<B: Backend + Debug>( db: &BinDB<IdentitiesV10Datas, B>, pubkey: &PubKey, diff --git a/dal/lib.rs b/dal/lib.rs index 5887c633cf26d4837119c4e3c63180a4e56fe4ef..b43899a7ea47df048a07c61eb9cb1c6e0f131cd4 100644 --- a/dal/lib.rs +++ b/dal/lib.rs @@ -19,7 +19,7 @@ #![cfg_attr(feature = "cargo-clippy", allow(implicit_hasher))] #![cfg_attr(feature = "exp", allow(warnings))] #![deny( - missing_debug_implementations, missing_copy_implementations, trivial_casts, + missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces )] @@ -36,17 +36,40 @@ extern crate duniter_wotb; extern crate rustbreak; extern crate serde; +/// Define balance operations pub mod balance; + +/// Blocks operations pub mod block; + +/// Certifications operations pub mod certs; + +/// Define crate constants pub mod constants; + +/// Currency parameters operations pub mod currency_params; + +/// Define DAL events to be transmitted to other modules pub mod dal_event; + +/// Defined module requests for DAL pub mod dal_requests; + +/// Identity operations pub mod identity; + +/// Parsers pub mod parsers; + +/// Define currency sources types pub mod sources; + +/// Tools pub mod tools; + +/// Contains all write databases functions pub mod writers; use duniter_crypto::keys::*; @@ -74,20 +97,34 @@ use writers::transaction::DALTxV10; /// Each fork has a unique identifier. The local blockchain (also called local branch) has ForkId equal to zero. pub struct ForkId(pub usize); +/// Currency parameters (Protocol V10) pub type CurrencyParamsV10Datas = (CurrencyName, BlockV10Parameters); +/// All blocks of local blockchain indexed by block number pub type LocalBlockchainV10Datas = HashMap<BlockId, DALBlock>; +/// Forks meta datas (block hash and previous hash only) pub type ForksV10Datas = HashMap<ForkId, HashMap<PreviousBlockstamp, BlockHash>>; +/// Forks blocks indexed by their blockstamp pub type ForksBlocksV10Datas = HashMap<Blockstamp, DALBlock>; +/// V10 Identities indexed by public key pub type IdentitiesV10Datas = HashMap<PubKey, DALIdentity>; +/// Memberships sorted by created block pub type MsExpirV10Datas = HashMap<BlockId, HashSet<NodeId>>; +/// Certifications sorted by created block pub type CertsExpirV10Datas = HashMap<BlockId, HashSet<(NodeId, NodeId)>>; +/// V10 Transactions indexed by their hashs pub type TxV10Datas = HashMap<Hash, DALTxV10>; +/// V10 Unused Transaction Output (=sources) pub type UTXOsV10Datas = HashMap<UTXOIndexV10, UTXOContentV10>; -pub type DUsV10Datas = HashMap<PubKey, HashSet<BlockId>>; +/// V10 UDs sources +pub type UDsV10Datas = HashMap<PubKey, HashSet<BlockId>>; +/// V10 Balances accounts pub type BalancesV10Datas = HashMap<UTXOConditionsGroup, (SourceAmount, HashSet<UTXOIndexV10>)>; +/// Binary Database pub type BinDB<D, B> = Database<D, B, Bincode>; +/// Binary File Database pub type BinFileDB<D> = FileDatabase<D, Bincode>; +/// Binary Memory Database pub type BinMemDB<D> = MemoryDatabase<D, Bincode>; #[derive(Debug)] @@ -167,8 +204,8 @@ impl WotsV10DBs { #[derive(Debug)] /// Set of databases storing currency information pub struct CurrencyV10DBs<B: Backend + Debug> { - /// Store all DU sources - pub du_db: BinDB<DUsV10Datas, B>, + /// Store all UD sources + pub du_db: BinDB<UDsV10Datas, B>, /// Store all Transactions pub tx_db: BinDB<TxV10Datas, B>, /// Store all UTXOs @@ -178,9 +215,10 @@ pub struct CurrencyV10DBs<B: Backend + Debug> { } impl CurrencyV10DBs<MemoryBackend> { + /// Open currency databases in memory mode pub fn open_memory_mode() -> CurrencyV10DBs<MemoryBackend> { CurrencyV10DBs { - du_db: open_memory_db::<DUsV10Datas>().expect("Fail to open DUsV10DB"), + du_db: open_memory_db::<UDsV10Datas>().expect("Fail to open UDsV10DB"), tx_db: open_memory_db::<TxV10Datas>().expect("Fail to open TxV10DB"), utxos_db: open_memory_db::<UTXOsV10Datas>().expect("Fail to open UTXOsV10DB"), balances_db: open_memory_db::<BalancesV10Datas>().expect("Fail to open BalancesV10DB"), @@ -192,7 +230,7 @@ impl CurrencyV10DBs<FileBackend> { /// Open currency databases from their respective files pub fn open(db_path: &PathBuf) -> CurrencyV10DBs<FileBackend> { CurrencyV10DBs { - du_db: open_db::<DUsV10Datas>(&db_path, "du.db").expect("Fail to open DUsV10DB"), + du_db: open_db::<UDsV10Datas>(&db_path, "du.db").expect("Fail to open UDsV10DB"), tx_db: open_db::<TxV10Datas>(&db_path, "tx.db") .unwrap_or_else(|_| panic!("Fail to open TxV10DB : {:?} ", db_path.as_path())), utxos_db: open_db::<UTXOsV10Datas>(&db_path, "sources.db") @@ -217,7 +255,7 @@ impl CurrencyV10DBs<FileBackend> { if du { self.du_db .save() - .expect("Fatal error : fail to save DUsV10DB !"); + .expect("Fatal error : fail to save UDsV10DB !"); } } } diff --git a/dal/parsers/certifications.rs b/dal/parsers/certifications.rs index 02f0a6d810d439a9acd2b18b05cc1e36ebe775f4..675894f56f4e211e49d4902b98e6ed217d04545c 100644 --- a/dal/parsers/certifications.rs +++ b/dal/parsers/certifications.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + extern crate serde; extern crate serde_json; @@ -6,6 +21,7 @@ use duniter_documents::blockchain::v10::documents::certification::CompactCertifi use duniter_documents::blockchain::v10::documents::{CertificationDocument, TextDocumentFormat}; use duniter_documents::BlockId; +/// Parse array of certification json documents into vector of `CompactCertificationDocument` pub fn parse_certifications_into_compact( json_certs: &[serde_json::Value], ) -> Vec<TextDocumentFormat<CertificationDocument>> { diff --git a/dal/parsers/mod.rs b/dal/parsers/mod.rs index 92d83a2bdc2ea9ed7781782cce34957c5b97a466..8da75d900cba69452d9633aafc01f34f5961a148 100644 --- a/dal/parsers/mod.rs +++ b/dal/parsers/mod.rs @@ -13,5 +13,8 @@ // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. +/// Parsers for certifications event pub mod certifications; + +/// Parsers for revoked event pub mod revoked; diff --git a/dal/parsers/revoked.rs b/dal/parsers/revoked.rs index 2bea8150fba51e0b6c38ce6e69729035e218b3cc..03779cdfc6cdd98e47f9407cd86bd549f6a1947a 100644 --- a/dal/parsers/revoked.rs +++ b/dal/parsers/revoked.rs @@ -1,9 +1,25 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + extern crate serde_json; use duniter_crypto::keys::*; use duniter_documents::blockchain::v10::documents::revocation::CompactRevocationDocument; use duniter_documents::blockchain::v10::documents::{RevocationDocument, TextDocumentFormat}; +/// Parse array of revocations json documents into vector of `CompactRevocationDocument` pub fn parse_revocations_into_compact( json_recocations: &[serde_json::Value], ) -> Vec<TextDocumentFormat<RevocationDocument>> { diff --git a/dal/sources.rs b/dal/sources.rs index 4a42ef2b3a8a3673d96cc758ef41005c2493c98b..7148a819a31f2b2bd73b47ca6e907cf3fed2735a 100644 --- a/dal/sources.rs +++ b/dal/sources.rs @@ -23,6 +23,7 @@ use std::cmp::Ordering; use std::ops::{Add, Sub}; #[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Serialize)] +/// Source amount pub struct SourceAmount(pub TxAmount, pub TxBase); impl Default for SourceAmount { @@ -64,35 +65,45 @@ impl Sub for SourceAmount { } #[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] +/// UTXOIndexV10 pub struct UTXOIndexV10(pub Hash, pub TxIndex); +/// UTXO content V10 pub type UTXOContentV10 = TransactionOutput; #[derive(Debug, Clone, Deserialize, Serialize)] +/// V10 Unused Transaction Output pub struct UTXOV10(pub UTXOIndexV10, pub UTXOContentV10); impl UTXOV10 { + /// UTXO conditions pub fn get_conditions(&self) -> UTXOConditionsGroup { self.1.conditions.conditions.clone() } + /// UTXO amount pub fn get_amount(&self) -> SourceAmount { SourceAmount(self.1.amount, self.1.base) } } #[derive(Debug, Clone, Deserialize, Serialize)] +/// Unused Transaction Output pub enum UTXO { + /// V10 V10(UTXOV10), + /// V11 V11(), } impl UTXO { + /// UTXO conditions pub fn get_conditions(&self) -> UTXOConditionsGroup { match *self { UTXO::V10(ref utxo_v10) => utxo_v10.get_conditions(), _ => panic!("UTXO version not supported !"), } } + /// UTXO amount pub fn get_amount(&self) -> SourceAmount { match *self { UTXO::V10(ref utxo_v10) => utxo_v10.get_amount(), @@ -102,7 +113,10 @@ impl UTXO { } #[derive(Copy, Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] +/// Index of a V10 source pub enum SourceIndexV10 { + /// unused Transaction Output UTXO(UTXOIndexV10), - DU(PubKey, BlockId), + /// universal Dividend + UD(PubKey, BlockId), } diff --git a/dal/tools.rs b/dal/tools.rs index 8112525189ebc1c5fc53a77db3ad424c8a0d23dd..bc65497aeb210ae1cfda804fa03433ce1658309e 100644 --- a/dal/tools.rs +++ b/dal/tools.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + extern crate duniter_wotb; use duniter_wotb::operations::centrality::{ @@ -6,14 +21,16 @@ use duniter_wotb::operations::centrality::{ use duniter_wotb::operations::distance::{ DistanceCalculator, RustyDistanceCalculator, WotDistance, WotDistanceParameters, }; -use duniter_wotb::operations::path::{PathFinder, RustyPathFinder}; use duniter_wotb::{NodeId, WebOfTrust}; +/// CENTRALITY_CALCULATOR pub static CENTRALITY_CALCULATOR: UlrikBrandesCentralityCalculator = UlrikBrandesCentralityCalculator {}; + +/// DISTANCE_CALCULATOR pub static DISTANCE_CALCULATOR: RustyDistanceCalculator = RustyDistanceCalculator {}; -pub static PATH_FINDER: RustyPathFinder = RustyPathFinder {}; +/// Get sentry requirement pub fn get_sentry_requirement(members_count: usize, step_max: u32) -> u32 { match step_max { 5 => { @@ -21,20 +38,49 @@ pub fn get_sentry_requirement(members_count: usize, step_max: u32) -> u32 { 2 } else if members_count < 244 { 3 - } else if members_count < 1025 { + } else if members_count < 1_025 { 4 - } else if members_count < 3126 { + } else if members_count < 3_126 { 5 - } else if members_count < 7777 { + } else if members_count < 7_777 { 6 + } else if members_count < 16_808 { + 7 + } else if members_count < 32_769 { + 8 + } else if members_count < 59_050 { + 9 + } else if members_count < 100_001 { + 10 + } else if members_count < 100_001 { + 11 + } else if members_count < 161_052 { + 12 + } else if members_count < 248_833 { + 13 + } else if members_count < 371_294 { + 14 + } else if members_count < 537_825 { + 15 + } else if members_count < 759_376 { + 16 + } else if members_count < 1_048_577 { + 17 + } else if members_count < 1_419_858 { + 18 + } else if members_count < 1_889_569 { + 19 } else { - panic!("get_sentry_requirement not define for members_count greater than 7777 !"); + panic!( + "get_sentry_requirement not define for members_count greater than 1_889_569 !" + ); } } _ => panic!("get_sentry_requirement not define for step_max != 5 !"), } } +/// Compute average density pub fn calculate_average_density<T: WebOfTrust>(wot: &T) -> usize { let enabled_members = wot.get_enabled(); let enabled_members_count = enabled_members.len(); @@ -47,6 +93,7 @@ pub fn calculate_average_density<T: WebOfTrust>(wot: &T) -> usize { ((count_actives_links as f32 / enabled_members_count as f32) * 1_000.0) as usize } +/// Compute distances pub fn compute_distances<T: WebOfTrust + Sync>( wot: &T, sentry_requirement: u32, @@ -91,49 +138,7 @@ pub fn compute_distances<T: WebOfTrust + Sync>( ) } +/// Compute distance stress centralities pub fn calculate_distance_stress_centralities<T: WebOfTrust>(wot: &T, step_max: u32) -> Vec<u64> { CENTRALITY_CALCULATOR.distance_stress_centralities(wot, step_max as usize) } - -pub fn calculate_centralities_degree<T: WebOfTrust>(wot: &T, step_max: u32) -> Vec<usize> { - let wot_size = wot.size(); - let members_count = wot.get_enabled().len() as u64; - let oriented_couples_count: u64 = members_count * (members_count - 1); - let mut centralities: Vec<u64> = vec![0; wot_size]; - for i in 0..wot_size { - for j in 0..wot_size { - let mut paths = PATH_FINDER.find_paths(wot, NodeId(i), NodeId(j), step_max); - if paths.is_empty() { - break; - } - //paths.sort_unstable_by(|a, b| a.len().cmp(&b.len())); - let shortest_path_len = paths[0].len(); - let mut intermediate_members: Vec<NodeId> = Vec::new(); - if shortest_path_len > 2 { - for path in paths { - //if path.len() == shortest_path_len { - for node_id in &path { - if !intermediate_members.contains(node_id) { - intermediate_members.push(*node_id); - } - } - /*} else { - break; - }*/ - } - } - let centralities_copy = centralities.clone(); - for node_id in intermediate_members { - let centrality = ¢ralities_copy[node_id.0]; - if let Some(tmp) = centralities.get_mut(node_id.0) { - *tmp = *centrality + 1; - } - } - } - } - let mut relative_centralities = Vec::with_capacity(wot_size); - for centrality in centralities { - relative_centralities.push((centrality * 100_000 / oriented_couples_count) as usize); - } - relative_centralities -} diff --git a/dal/writers/block.rs b/dal/writers/block.rs index 053146d4bb2bca5f2798d2c29f6681071c39226f..5ad567c1be3922b0cf5aaa04d72f365ce1c302dd 100644 --- a/dal/writers/block.rs +++ b/dal/writers/block.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + use block::DALBlock; use duniter_documents::blockchain::Document; use duniter_documents::{BlockHash, BlockId, PreviousBlockstamp}; diff --git a/dal/writers/certification.rs b/dal/writers/certification.rs index fd2d7341e599e4fe2b2e32601a1ddce33e99b122..2f8ebf5882fdefb77b36776118f1077d45e979a0 100644 --- a/dal/writers/certification.rs +++ b/dal/writers/certification.rs @@ -23,6 +23,7 @@ use duniter_documents::BlockId; use duniter_wotb::NodeId; use {BinFileDB, CertsExpirV10Datas, DALError, IdentitiesV10Datas}; +/// Apply "certification" event in databases pub fn write_certification( currency_params: &CurrencyParameters, identities_db: &BinFileDB<IdentitiesV10Datas>, @@ -83,6 +84,7 @@ pub fn revert_write_cert( Ok(()) } +/// Revert "certification expiry" event in databases pub fn revert_expire_cert( certs_db: &BinFileDB<CertsExpirV10Datas>, source: NodeId, @@ -98,6 +100,7 @@ pub fn revert_expire_cert( Ok(()) } +/// Apply "certification expiry" event in databases pub fn expire_certs( certs_db: &BinFileDB<CertsExpirV10Datas>, created_block_id: BlockId, diff --git a/dal/writers/dividend.rs b/dal/writers/dividend.rs index cdeac04d8edc9eabf86f5dc71b2bd517a65c3808..a0add7d7417298b27345706c1866412c13ca9908 100644 --- a/dal/writers/dividend.rs +++ b/dal/writers/dividend.rs @@ -22,15 +22,16 @@ use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use *; +/// Apply UD creation in databases pub fn create_du<B: Backend + Debug>( - du_db: &BinDB<DUsV10Datas, B>, + du_db: &BinDB<UDsV10Datas, B>, balances_db: &BinDB<BalancesV10Datas, B>, du_amount: &SourceAmount, du_block_id: BlockId, members: &[PubKey], revert: bool, ) -> Result<(), DALError> { - // Insert/Remove DU sources in DUsV10DB + // Insert/Remove UD sources in UDsV10DB du_db.write(|db| { for pubkey in members { let mut pubkey_dus = db.get(&pubkey).cloned().unwrap_or_default(); diff --git a/dal/writers/identity.rs b/dal/writers/identity.rs index 8426edf30340ee82163eebd9cc559f83eab1646d..e22d3001d42ae4e77a702c3ed3180d9f2eb12c88 100644 --- a/dal/writers/identity.rs +++ b/dal/writers/identity.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + use currency_params::CurrencyParameters; use duniter_crypto::keys::PubKey; use duniter_documents::blockchain::v10::documents::IdentityDocument; @@ -7,6 +22,7 @@ use duniter_wotb::NodeId; use identity::{DALIdentity, DALIdentityState}; use {BinFileDB, DALError, IdentitiesV10Datas, MsExpirV10Datas}; +/// Remove identity from databases pub fn revert_create_identity( identities_db: &BinFileDB<IdentitiesV10Datas>, ms_db: &BinFileDB<MsExpirV10Datas>, @@ -33,6 +49,7 @@ pub fn revert_create_identity( Ok(()) } +/// Write identity in databases pub fn create_identity( currency_params: &CurrencyParameters, identities_db: &BinFileDB<IdentitiesV10Datas>, diff --git a/dal/writers/mod.rs b/dal/writers/mod.rs index e7310d3caab4e139439f13839035b652dbf7c39e..e27c72a0623a9331478ed68e40db9df821f249c3 100644 --- a/dal/writers/mod.rs +++ b/dal/writers/mod.rs @@ -1,6 +1,32 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +/// Block writer functions pub mod block; + +/// Certification apply functions pub mod certification; + +/// Dividend apply functions pub mod dividend; + +/// Identities writer functions pub mod identity; + +/// Databases write requests pub mod requests; + +/// Transaction apply functions pub mod transaction; diff --git a/dal/writers/requests.rs b/dal/writers/requests.rs index 1f2428fdf1e02099c08888a984d68602255326c5..7ec4413d9ff8a39ded40e9eb781cb6db81457132 100644 --- a/dal/writers/requests.rs +++ b/dal/writers/requests.rs @@ -1,3 +1,18 @@ +// Copyright (C) 2018 The Duniter Project Developers. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + extern crate serde; extern crate serde_json; @@ -37,6 +52,7 @@ pub enum BlocksDBsWriteQuery { } impl BlocksDBsWriteQuery { + /// BlocksDBsWriteQuery pub fn apply(&self, databases: &BlocksV10DBs, sync: bool) -> Result<(), DALError> { match *self { BlocksDBsWriteQuery::WriteBlock(ref dal_block, ref old_fork_id, _, _) => { @@ -102,6 +118,7 @@ pub enum WotsDBsWriteQuery { } impl WotsDBsWriteQuery { + /// Apply WotsDBsWriteQuery pub fn apply( &self, databases: &WotsV10DBs, @@ -252,12 +269,13 @@ pub enum CurrencyDBsWriteQuery { /// Revert transaction RevertTx(Box<DALTxV10>), /// Create dividend - CreateDU(SourceAmount, BlockId, Vec<PubKey>), + CreateUD(SourceAmount, BlockId, Vec<PubKey>), /// Revert dividend - RevertDU(SourceAmount, BlockId, Vec<PubKey>), + RevertUD(SourceAmount, BlockId, Vec<PubKey>), } impl CurrencyDBsWriteQuery { + /// Apply CurrencyDBsWriteQuery pub fn apply<B: Backend + Debug>(&self, databases: &CurrencyV10DBs<B>) -> Result<(), DALError> { match *self { CurrencyDBsWriteQuery::WriteTx(ref tx_doc) => { @@ -266,7 +284,7 @@ impl CurrencyDBsWriteQuery { CurrencyDBsWriteQuery::RevertTx(ref dal_tx) => { super::transaction::revert_tx::<B>(&databases, dal_tx.deref())?; } - CurrencyDBsWriteQuery::CreateDU(ref du_amount, ref block_id, ref members) => { + CurrencyDBsWriteQuery::CreateUD(ref du_amount, ref block_id, ref members) => { super::dividend::create_du::<B>( &databases.du_db, &databases.balances_db, @@ -276,7 +294,7 @@ impl CurrencyDBsWriteQuery { false, )?; } - CurrencyDBsWriteQuery::RevertDU(ref du_amount, ref block_id, ref members) => { + CurrencyDBsWriteQuery::RevertUD(ref du_amount, ref block_id, ref members) => { super::dividend::create_du::<B>( &databases.du_db, &databases.balances_db, diff --git a/dal/writers/transaction.rs b/dal/writers/transaction.rs index 11382952b770b1385397783dd6e42aaccaf6402e..a1ffc32dcf612709ce76665d3767d6f3f993d5e7 100644 --- a/dal/writers/transaction.rs +++ b/dal/writers/transaction.rs @@ -20,8 +20,11 @@ use std::fmt::Debug; use *; #[derive(Debug, Copy, Clone)] +/// Transaction error pub enum TxError { + /// UnkonwError UnkonwError(), + /// DALError DALError(DALError), } @@ -32,11 +35,15 @@ impl From<DALError> for TxError { } #[derive(Debug, Clone, Deserialize, Serialize)] +/// DAL Transaction V10 pub struct DALTxV10 { + /// Transaction document pub tx_doc: TransactionDocument, + /// Index of sources destroyed by this transaction pub sources_destroyed: HashSet<UTXOIndexV10>, } +/// Apply transaction backwards pub fn revert_tx<B: Backend + Debug>( dbs: &CurrencyV10DBs<B>, dal_tx: &DALTxV10, @@ -132,7 +139,7 @@ pub fn revert_tx<B: Backend + Debug>( .iter() .map(|input| match *input { TransactionInput::D(tx_amout, tx_amout_base, pubkey, block_id) => ( - SourceIndexV10::DU(pubkey, block_id), + SourceIndexV10::UD(pubkey, block_id), SourceAmount(tx_amout, tx_amout_base), ), TransactionInput::T(tx_amout, tx_amout_base, hash, tx_index) => ( @@ -165,7 +172,7 @@ pub fn revert_tx<B: Backend + Debug>( utxos_index.insert(*utxo_index); // Write new balances datas for "conditions" address recreated_adress.insert(conditions.clone(), (balance, utxos_index)); - } else if let SourceIndexV10::DU(pubkey, _block_id) = source_index { + } else if let SourceIndexV10::UD(pubkey, _block_id) = source_index { let address = UTXOConditionsGroup::Single(TransactionOutputCondition::Sig(*pubkey)); let (mut balance, utxos_index) = @@ -221,7 +228,7 @@ pub fn revert_tx<B: Backend + Debug>( dbs.utxos_db.write(|db| { db.insert(*utxo_index, utxo_content); })?; - } else if let SourceIndexV10::DU(pubkey, block_id) = s_index { + } else if let SourceIndexV10::UD(pubkey, block_id) = s_index { let mut pubkey_dus: HashSet<BlockId> = dbs .du_db .read(|db| db.get(&pubkey).cloned().unwrap_or_default())?; @@ -234,6 +241,7 @@ pub fn revert_tx<B: Backend + Debug>( Ok(()) } +/// Apply and write transaction in databases pub fn apply_and_write_tx<B: Backend + Debug>( dbs: &CurrencyV10DBs<B>, tx_doc: &TransactionDocument, @@ -247,7 +255,7 @@ pub fn apply_and_write_tx<B: Backend + Debug>( .iter() .map(|input| match *input { TransactionInput::D(tx_amout, tx_amout_base, pubkey, block_id) => ( - SourceIndexV10::DU(pubkey, block_id), + SourceIndexV10::UD(pubkey, block_id), SourceAmount(tx_amout, tx_amout_base), ), TransactionInput::T(tx_amout, tx_amout_base, hash, tx_index) => ( @@ -281,7 +289,7 @@ pub fn apply_and_write_tx<B: Backend + Debug>( utxos_index.insert(*utxo_index); // Write new balances datas for "conditions" address consumed_adress.insert(conditions.clone(), (balance, utxos_index)); - } else if let SourceIndexV10::DU(pubkey, _block_id) = source_index { + } else if let SourceIndexV10::UD(pubkey, _block_id) = source_index { let address = UTXOConditionsGroup::Single(TransactionOutputCondition::Sig(*pubkey)); let (mut balance, utxos_index) = @@ -326,7 +334,7 @@ pub fn apply_and_write_tx<B: Backend + Debug>( dbs.utxos_db.write(|db| { db.remove(utxo_index); })?; - } else if let SourceIndexV10::DU(pubkey, block_id) = source_index { + } else if let SourceIndexV10::UD(pubkey, block_id) = source_index { let mut pubkey_dus: HashSet<BlockId> = dbs .du_db .read(|db| db.get(&pubkey).cloned().unwrap_or_default())?; @@ -463,7 +471,7 @@ mod tests { ); // Open currencys_db in memory mode let currency_dbs = CurrencyV10DBs::open_memory_mode(); - // Create first g1 DU for cgeek and tortue + // Create first g1 UD for cgeek and tortue writers::dividend::create_du( ¤cy_dbs.du_db, ¤cy_dbs.balances_db, @@ -471,7 +479,7 @@ mod tests { BlockId(1), &vec![tx_doc.issuers()[0], tortue_pubkey], false, - ).expect("Fail to create first g1 DU !"); + ).expect("Fail to create first g1 UD !"); // Check members balance let cgeek_new_balance = currency_dbs .balances_db diff --git a/documents/blockchain/v10/documents/block.rs b/documents/blockchain/v10/documents/block.rs index 786a5439dc77f7a326ff42327f877b4d163df21c..5ddc7b51c7c96d0de67b19db1f49814c5a657a42 100644 --- a/documents/blockchain/v10/documents/block.rs +++ b/documents/blockchain/v10/documents/block.rs @@ -72,7 +72,7 @@ impl From<::std::num::ParseFloatError> for ParseParamsError { pub struct BlockV10Parameters { /// UD target growth rate (see Relative Theorie of Money) pub c: f64, - /// Duration between the creation of two DU (in seconds) + /// Duration between the creation of two UD (in seconds) pub dt: u64, /// Amount of the initial UD pub ud0: usize,