x 3 лет назад
Родитель
Сommit
5702976798
65 измененных файлов с 881 добавлено и 819 удалено
  1. 4 4
      src/blockchain/contractstore.rs
  2. 4 4
      src/blockchain/mod.rs
  3. 11 10
      src/consensus/clock.rs
  4. 1 1
      src/consensus/lead_info.rs
  5. 5 5
      src/consensus/leadcoin.rs
  6. 9 7
      src/consensus/proto/protocol_proposal.rs
  7. 29 21
      src/consensus/proto/protocol_sync.rs
  8. 9 8
      src/consensus/proto/protocol_sync_consensus.rs
  9. 5 5
      src/consensus/proto/protocol_tx.rs
  10. 19 18
      src/consensus/state.rs
  11. 9 9
      src/consensus/task/block_sync.rs
  12. 12 12
      src/consensus/task/consensus_sync.rs
  13. 42 30
      src/consensus/task/proposal.rs
  14. 3 3
      src/consensus/utils.rs
  15. 112 86
      src/consensus/validator.rs
  16. 1 1
      src/consensus/wallet.rs
  17. 1 1
      src/contract/dao/Cargo.toml
  18. 1 1
      src/contract/dao/src/dao_client.rs
  19. 1 1
      src/contract/dao/src/dao_exec_client.rs
  20. 3 3
      src/contract/dao/src/dao_vote_client.rs
  21. 2 2
      src/contract/dao/tests/dao_harness.rs
  22. 35 35
      src/contract/dao/tests/integration.rs
  23. 13 13
      src/contract/money/src/client.rs
  24. 112 112
      src/contract/money/tests/drop_pay_swap.rs
  25. 3 3
      src/contract/money/tests/harness.rs
  26. 11 11
      src/contract/money/tests/verification_bench.rs
  27. 12 12
      src/dht/mod.rs
  28. 28 24
      src/dht/protocol.rs
  29. 4 4
      src/net/acceptor.rs
  30. 17 17
      src/net/channel.rs
  31. 2 2
      src/net/connector.rs
  32. 25 25
      src/net/hosts.rs
  33. 8 8
      src/net/message.rs
  34. 4 4
      src/net/message_subscriber.rs
  35. 13 12
      src/net/p2p.rs
  36. 9 9
      src/net/protocol/protocol_address.rs
  37. 1 1
      src/net/protocol/protocol_jobs_manager.rs
  38. 8 8
      src/net/protocol/protocol_ping.rs
  39. 2 2
      src/net/protocol/protocol_registry.rs
  40. 3 3
      src/net/protocol/protocol_seed.rs
  41. 12 11
      src/net/protocol/protocol_version.rs
  42. 4 4
      src/net/session/inbound_session.rs
  43. 5 5
      src/net/session/manual_session.rs
  44. 17 15
      src/net/session/outbound_session.rs
  45. 13 13
      src/net/session/seedsync_session.rs
  46. 5 5
      src/net/transport/tcp.rs
  47. 3 3
      src/net/transport/unix.rs
  48. 6 6
      src/raft/consensus.rs
  49. 2 2
      src/raft/consensus_candidate.rs
  50. 2 2
      src/raft/consensus_follower.rs
  51. 1 1
      src/raft/datastore.rs
  52. 4 4
      src/raft/protocol_raft.rs
  53. 14 14
      src/rpc/client.rs
  54. 6 6
      src/rpc/clock_sync.rs
  55. 20 20
      src/rpc/server.rs
  56. 32 32
      src/runtime/import/db.rs
  57. 17 17
      src/runtime/import/merkle.rs
  58. 12 12
      src/runtime/import/util.rs
  59. 17 17
      src/runtime/vm_runtime.rs
  60. 1 0
      src/sdk/src/crypto/constants/load.rs
  61. 2 2
      src/system/subscriber.rs
  62. 10 9
      src/tx/mod.rs
  63. 24 23
      src/wallet/cashierdb.rs
  64. 5 5
      src/wallet/walletdb.rs
  65. 54 54
      src/zk/vm.rs

+ 4 - 4
src/blockchain/contractstore.rs

@@ -60,7 +60,7 @@ impl WasmStore {
     /// Inserts or replaces the bincode for a given ContractId
     pub fn insert(&self, contract_id: ContractId, bincode: &[u8]) -> Result<()> {
         if let Err(e) = self.0.insert(&serialize(&contract_id), bincode) {
-            error!("Failed to insert bincode to WasmStore: {}", e);
+            error!(target: "blockchain::contractstore", "Failed to insert bincode to WasmStore: {}", e);
             return Err(e.into())
         }
 
@@ -104,7 +104,7 @@ impl ContractStateStore {
         contract_id: &ContractId,
         tree_name: &str,
     ) -> Result<sled::Tree> {
-        debug!(target: CS_TGT_INIT, "Initializing state tree for {}:{}", contract_id, tree_name);
+        debug!(target: "blockchain::contractstore", "Initializing state tree for {}:{}", contract_id, tree_name);
 
         let contract_id_bytes = serialize(contract_id);
         let ptr = contract_id.hash_state_id(tree_name);
@@ -150,7 +150,7 @@ impl ContractStateStore {
         contract_id: &ContractId,
         tree_name: &str,
     ) -> Result<sled::Tree> {
-        debug!(target: CS_TGT_LKUP, "Looking up state tree for {}:{}", contract_id, tree_name);
+        debug!(target: "blockchain::contractstore", "Looking up state tree for {}:{}", contract_id, tree_name);
 
         let contract_id_bytes = serialize(contract_id);
         let ptr = contract_id.hash_state_id(tree_name);
@@ -180,7 +180,7 @@ impl ContractStateStore {
     /// will be removed from the main `ContractStateStore`. If anything is not
     /// found as initialized, an error is returned.
     pub fn remove(&self, db: &sled::Db, contract_id: &ContractId, tree_name: &str) -> Result<()> {
-        debug!(target: CS_TGT_DROP, "Removing state tree for {}:{}", contract_id, tree_name);
+        debug!(target: "blockchain::contractstore", "Removing state tree for {}:{}", contract_id, tree_name);
 
         let contract_id_bytes = serialize(contract_id);
         let ptr = contract_id.hash_state_id(tree_name);

+ 4 - 4
src/blockchain/mod.rs

@@ -161,7 +161,7 @@ impl Blockchain {
 
     /// Retrieve [`BlockInfo`]s by given slots. Does not fail if any of them are not found.
     pub fn get_blocks_by_slot(&self, slots: &[u64]) -> Result<Vec<BlockInfo>> {
-        debug!("get_blocks_by_slot(): {:?}", slots);
+        debug!(target: "blockchain", "get_blocks_by_slot(): {:?}", slots);
         let blockhashes = self.order.get(slots, false)?;
 
         let mut hashes = vec![];
@@ -174,7 +174,7 @@ impl Blockchain {
 
     /// Retrieve n blocks after given start slot.
     pub fn get_blocks_after(&self, slot: u64, n: u64) -> Result<Vec<BlockInfo>> {
-        debug!("get_blocks_after(): {} -> {}", slot, n);
+        debug!(target: "blockchain", "get_blocks_after(): {} -> {}", slot, n);
         let hashes = self.order.get_after(slot, n)?;
         self.get_blocks_by_hash(&hashes)
     }
@@ -230,7 +230,7 @@ impl Blockchain {
 
     /// Retrieve n checkpoints after given start slot.
     pub fn get_slot_checkpoints_after(&self, slot: u64, n: u64) -> Result<Vec<SlotCheckpoint>> {
-        debug!("get_slot_checkpoints_after(): {} -> {}", slot, n);
+        debug!(target: "blockchain", "get_slot_checkpoints_after(): {} -> {}", slot, n);
         self.slot_checkpoints.get_after(slot, n)
     }
 
@@ -244,7 +244,7 @@ impl Blockchain {
         &self,
         slots: &[u64],
     ) -> Result<Vec<Option<SlotCheckpoint>>> {
-        debug!("get_slot_checkpoints_by_slot(): {:?}", slots);
+        debug!(target: "blockchain", "get_slot_checkpoints_by_slot(): {:?}", slots);
         self.slot_checkpoints.get(slots, true)
     }
 

+ 11 - 10
src/consensus/clock.rs

@@ -95,7 +95,7 @@ impl Clock {
     /// return true if the clock is at the begining (before 2/3 of the slot).
     async fn ticking(&self) -> bool {
         let (abs, rel, _) = self.tick_time().await;
-        debug!("abs time to genesis ticks: {}, rel ticks: {}", abs, rel);
+        debug!(target: "consensus::clock", "abs time to genesis ticks: {}, rel ticks: {}", abs, rel);
         rel < (self.tick_len) * 2 / 3
     }
 
@@ -110,21 +110,21 @@ impl Clock {
     /// returns absolute zero based slot index
     async fn slot_abs(&self) -> u64 {
         let sl_abs = self.tick_time().await.0 / self.sl_len;
-        debug!("[slot_abs] slot len: {} - slot abs: {}", self.sl_len, sl_abs);
+        debug!(target: "consensus::clock", "[slot_abs] slot len: {} - slot abs: {}", self.sl_len, sl_abs);
         sl_abs
     }
 
     /// returns relative zero based slot index
     async fn slot_relative(&self) -> u64 {
         let e_abs = self.slot_abs().await % self.e_len;
-        debug!("[slot_relative] slot len: {} - slot relative: {}", self.sl_len, e_abs);
+        debug!(target: "consensus::clock", "[slot_relative] slot len: {} - slot relative: {}", self.sl_len, e_abs);
         e_abs
     }
 
     /// returns absolute zero based epoch index.
     async fn epoch_abs(&self) -> u64 {
         let res = self.slot_abs().await / self.e_len;
-        debug!("[epoch_abs] epoch len: {} - epoch abs: {}", self.e_len, res);
+        debug!(target: "consensus::clock", "[epoch_abs] epoch len: {} - epoch abs: {}", self.e_len, res);
         res
     }
 
@@ -137,34 +137,35 @@ impl Clock {
         let sl = self.slot_relative().await;
         if self.ticking().await {
             debug!(
+                target: "consensus::clock",
                 "e/e`: {}/{} sl/sl`: {}/{}, BB_E/BB_SL: {}/{}",
                 e, self.e, sl, self.sl, BB_E, BB_SL
             );
             if e == self.e && e == BB_E && self.sl == BB_SL {
                 self.sl = sl + 1; // 0
                 self.e = e; // 0
-                debug!("new genesis");
+                debug!(target: "consensus::clock", "new genesis");
                 Ticks::GENESIS { e, sl }
             } else if e == self.e && sl == self.sl + 1 {
                 self.sl = sl;
-                debug!("new slot");
+                debug!(target: "consensus::clock", "new slot");
                 Ticks::NEWSLOT { e, sl }
             } else if e == self.e + 1 && sl == 0 {
                 self.e = e;
                 self.sl = sl;
-                debug!("new epoch");
+                debug!(target: "consensus::clock", "new epoch");
                 Ticks::NEWEPOCH { e, sl }
             } else if e == self.e && sl == self.sl {
-                debug!("clock is idle");
+                debug!(target: "consensus::clock", "clock is idle");
                 thread::sleep(Duration::from_millis(100));
                 Ticks::IDLE
             } else {
-                debug!("clock is out of sync");
+                debug!(target: "consensus::clock", "clock is out of sync");
                 //clock is out of sync
                 Ticks::OUTOFSYNC
             }
         } else {
-            debug!("tocks");
+            debug!(target: "consensus::clock", "tocks");
             Ticks::TOCKS
         }
     }

+ 1 - 1
src/consensus/lead_info.rs

@@ -101,7 +101,7 @@ pub struct LeadProof {
 impl LeadProof {
     pub fn verify(&self, vk: &VerifyingKey, public_inputs: &[pallas::Base]) -> Result<()> {
         if let Err(e) = self.proof.verify(vk, public_inputs) {
-            error!("Verification of consensus lead proof failed: {}", e);
+            error!(target: "consensus::lead_info", "Verification of consensus lead proof failed: {}", e);
             return Err(e.into())
         }
 

+ 5 - 5
src/consensus/leadcoin.rs

@@ -122,7 +122,7 @@ impl LeadCoin {
         let pk = Self::util_pk(coin1_sk_root, slot);
         // Derive the nonce for coin2
         let coin2_seed = Self::util_derived_rho(coin1_sk_root, seed);
-        info!("coin2_seed[{}]: {:?}", slot, coin2_seed);
+        info!(target: "consensus::leadcoin", "coin2_seed[{}]: {:?}", slot, coin2_seed);
         let coin1_commitment = Self::commitment(pk, pallas::Base::from(value), seed, coin1_blind);
         // Hash its coordinates to get a base field element
         let c1_cm_coords = coin1_commitment.to_affine().coordinates().unwrap();
@@ -177,7 +177,7 @@ impl LeadCoin {
 
     /// Derive election seeds from given parameters
     pub fn election_seeds(eta: pallas::Base, slot: pallas::Base) -> (pallas::Base, pallas::Base) {
-        info!("election_seeds: eta: {:?}, slot: {:?}", eta, slot);
+        info!(target: "consensus::leadcoin", "election_seeds: eta: {:?}, slot: {:?}", eta, slot);
         let election_seed_nonce = pallas::Base::from(3);
         let election_seed_lead = pallas::Base::from(22);
 
@@ -266,8 +266,8 @@ impl LeadCoin {
         let value = pallas::Base::from(self.value);
         let target = sigma1 * value + sigma2 * value * value;
 
-        info!("is_leader(): y = {:?}", y);
-        info!("is_leader(): T = {:?}", target);
+        info!(target: "consensus::leadcoin", "is_leader(): y = {:?}", y);
+        info!(target: "consensus::leadcoin", "is_leader(): T = {:?}", target);
 
         y < target
     }
@@ -296,7 +296,7 @@ impl LeadCoin {
         &self,
         coin_commitment_tree: &mut BridgeTree<MerkleNode, MERKLE_DEPTH>,
     ) -> LeadCoin {
-        info!("derive_coin(): Deriving new coin!");
+        info!(target: "consensus::leadcoin", "derive_coin(): Deriving new coin!");
         let derived_c1_rho = self.derived_rho();
         let blind = pallas::Scalar::random(&mut OsRng);
         let derived_c2_cm = Self::commitment(

+ 9 - 7
src/consensus/proto/protocol_proposal.rs

@@ -63,27 +63,27 @@ impl ProtocolProposal {
     }
 
     async fn handle_receive_proposal(self: Arc<Self>) -> Result<()> {
-        debug!("ProtocolProposal::handle_receive_proposal() [START]");
+        debug!(target: "consensus::protocol_proposal::init()", "ProtocolProposal::handle_receive_proposal() [START]");
 
         let exclude_list = vec![self.channel_address.clone()];
         loop {
             let proposal = match self.proposal_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    debug!("ProtocolProposal::handle_receive_proposal(): recv fail: {}", e);
+                    debug!(target: "consensus::protocol_proposal::init()", "ProtocolProposal::handle_receive_proposal(): recv fail: {}", e);
                     continue
                 }
             };
 
-            debug!("ProtocolProposal::handle_receive_proposal(): recv: {}", proposal);
-            trace!("ProtocolProposal::handle_receive_proposal(): Full proposal: {:?}", proposal);
+            debug!(target: "consensus::protocol_proposal::init()", "ProtocolProposal::handle_receive_proposal(): recv: {}", proposal);
+            trace!(target: "consensus::protocol_proposal::init()", "ProtocolProposal::handle_receive_proposal(): Full proposal: {:?}", proposal);
 
             let proposal_copy = (*proposal).clone();
 
             // Verify we have the proposal already
             let mut lock = self.state.write().await;
             if lock.consensus.proposal_exists(&proposal_copy.hash) {
-                debug!("ProtocolProposal::handle_receive_proposal(): Proposal already received.");
+                debug!(target: "consensus::protocol_proposal::init()", "ProtocolProposal::handle_receive_proposal(): Proposal already received.");
                 continue
             }
 
@@ -95,6 +95,7 @@ impl ProtocolProposal {
                             self.p2p.broadcast_with_exclude(proposal_copy, &exclude_list).await
                         {
                             error!(
+                                target: "consensus::protocol_proposal::init()",
                                 "ProtocolProposal::handle_receive_proposal(): proposal broadcast fail: {}",
                                 e
                             );
@@ -103,6 +104,7 @@ impl ProtocolProposal {
                 }
                 Err(e) => {
                     error!(
+                        target: "consensus::protocol_proposal::init()",
                         "ProtocolProposal::handle_receive_proposal(): receive_proposal error: {}",
                         e
                     );
@@ -116,10 +118,10 @@ impl ProtocolProposal {
 #[async_trait]
 impl ProtocolBase for ProtocolProposal {
     async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!("ProtocolProposal::start() [START]");
+        debug!(target: "consensus::protocol_proposal::init()", "ProtocolProposal::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().handle_receive_proposal(), executor.clone()).await;
-        debug!("ProtocolProposal::start() [END]");
+        debug!(target: "consensus::protocol_proposal::init()", "ProtocolProposal::start() [END]");
         Ok(())
     }
 

+ 29 - 21
src/consensus/proto/protocol_sync.rs

@@ -86,39 +86,39 @@ impl ProtocolSync {
             let order = match self.request_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    debug!("ProtocolSync::handle_receive_request(): recv fail: {}", e);
+                    debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_request(): recv fail: {}", e);
                     continue
                 }
             };
 
-            debug!("ProtocolSync::handle_receive_request() received {:?}", order);
+            debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_request() received {:?}", order);
 
             // Extra validations can be added here
             let key = order.slot;
             let blocks = match self.state.read().await.blockchain.get_blocks_after(key, BATCH) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!("ProtocolSync::handle_receive_request(): get_blocks_after fail: {}", e);
+                    error!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_request(): get_blocks_after fail: {}", e);
                     continue
                 }
             };
-            debug!("ProtocolSync::handle_receive_request(): Found {} blocks", blocks.len());
+            debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_request(): Found {} blocks", blocks.len());
 
             let response = BlockResponse { blocks };
             if let Err(e) = self.channel.send(response).await {
-                error!("ProtocolSync::handle_receive_request(): channel send fail: {}", e)
+                error!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_request(): channel send fail: {}", e)
             };
         }
     }
 
     async fn handle_receive_block(self: Arc<Self>) -> Result<()> {
-        debug!("ProtocolSync::handle_receive_block() [START]");
+        debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_block() [START]");
         let exclude_list = vec![self.channel.address()];
         loop {
             let info = match self.block_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    debug!("ProtocolSync::handle_receive_block(): recv fail: {}", e);
+                    debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_block(): recv fail: {}", e);
                     continue
                 }
             };
@@ -135,6 +135,7 @@ impl ProtocolSync {
                     let slot = participating.unwrap();
                     if current >= slot {
                         debug!(
+                            target: "consensus::protocol_sync::handle_receive_request()",
                             "ProtocolSync::handle_receive_block(): node runs in consensus mode, skipping..."
                         );
                         continue
@@ -142,18 +143,19 @@ impl ProtocolSync {
                 }
             }
 
-            info!("ProtocolSync::handle_receive_block(): Received block: {}", info.blockhash());
+            info!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_block(): Received block: {}", info.blockhash());
 
-            debug!("ProtocolSync::handle_receive_block(): Processing received block");
+            debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_block(): Processing received block");
             let info_copy = (*info).clone();
             match self.state.write().await.receive_finalized_block(info_copy.clone()).await {
                 Ok(v) => {
                     if v {
-                        debug!("ProtocolProposal::handle_receive_block(): block processed successfully, broadcasting...");
+                        debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolProposal::handle_receive_block(): block processed successfully, broadcasting...");
                         if let Err(e) =
                             self.p2p.broadcast_with_exclude(info_copy, &exclude_list).await
                         {
                             error!(
+                                target: "consensus::protocol_sync::handle_receive_request()",
                                 "ProtocolSync::handle_receive_block(): p2p broadcast fail: {}",
                                 e
                             );
@@ -161,19 +163,20 @@ impl ProtocolSync {
                     }
                 }
                 Err(e) => {
-                    debug!("ProtocolSync::handle_receive_block(): error processing finalized block: {}", e);
+                    debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_block(): error processing finalized block: {}", e);
                 }
             };
         }
     }
 
     async fn handle_receive_slot_checkpoint_request(self: Arc<Self>) -> Result<()> {
-        debug!("ProtocolSync::handle_receive_slot_checkpoint_request() [START]");
+        debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_slot_checkpoint_request() [START]");
         loop {
             let request = match self.slot_checkpoin_request_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
                     debug!(
+                        target: "consensus::protocol_sync::handle_receive_request()",
                         "ProtocolSync::handle_receive_slot_checkpoint_request(): recv fail: {}",
                         e
                     );
@@ -181,7 +184,7 @@ impl ProtocolSync {
                 }
             };
 
-            debug!("ProtocolSync::handle_receive_slot_checkpoint_request() received {:?}", request);
+            debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_slot_checkpoint_request() received {:?}", request);
 
             // Extra validations can be added here
             let key = request.slot;
@@ -194,11 +197,12 @@ impl ProtocolSync {
             {
                 Ok(v) => v,
                 Err(e) => {
-                    error!("ProtocolSync::handle_receive_slot_checkpoint_request(): get_slot_checkpoints_after fail: {}", e);
+                    error!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_slot_checkpoint_request(): get_slot_checkpoints_after fail: {}", e);
                     continue
                 }
             };
             debug!(
+                target: "consensus::protocol_sync::handle_receive_request()",
                 "ProtocolSync::handle_receive_slot_checkpoint_request(): Found {} slot checkpoints",
                 slot_checkpoints.len()
             );
@@ -206,6 +210,7 @@ impl ProtocolSync {
             let response = SlotCheckpointResponse { slot_checkpoints };
             if let Err(e) = self.channel.send(response).await {
                 error!(
+                    target: "consensus::protocol_sync::handle_receive_request()",
                     "ProtocolSync::handle_receive_slot_checkpoint_request(): channel send fail: {}",
                     e
                 )
@@ -214,13 +219,13 @@ impl ProtocolSync {
     }
 
     async fn handle_receive_slot_checkpoint(self: Arc<Self>) -> Result<()> {
-        debug!("ProtocolSync::handle_receive_slot_checkpoint() [START]");
+        debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_slot_checkpoint() [START]");
         let exclude_list = vec![self.channel.address()];
         loop {
             let slot_checkpoint = match self.slot_checkpoints_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    debug!("ProtocolSync::handle_receive_slot_checkpoint(): recv fail: {}", e);
+                    debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_slot_checkpoint(): recv fail: {}", e);
                     continue
                 }
             };
@@ -237,6 +242,7 @@ impl ProtocolSync {
                     let slot = participating.unwrap();
                     if current >= slot {
                         debug!(
+                            target: "consensus::protocol_sync::handle_receive_request()",
                             "ProtocolSync::handle_receive_block(): node runs in consensus mode, skipping..."
                         );
                         continue
@@ -245,11 +251,12 @@ impl ProtocolSync {
             }
 
             info!(
+                target: "consensus::protocol_sync::handle_receive_request()",
                 "ProtocolSync::handle_receive_slot_checkpoint(): Received slot checkpoint: {}",
                 slot_checkpoint.slot
             );
 
-            debug!("ProtocolSync::handle_receive_slot_checkpoint(): Processing received slot checkpoint");
+            debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_slot_checkpoint(): Processing received slot checkpoint");
             let slot_checkpoint_copy = (*slot_checkpoint).clone();
             match self
                 .state
@@ -260,13 +267,14 @@ impl ProtocolSync {
             {
                 Ok(v) => {
                     if v {
-                        debug!("ProtocolProposal::handle_receive_slot_checkpoint(): slot checkpoint processed successfully, broadcasting...");
+                        debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolProposal::handle_receive_slot_checkpoint(): slot checkpoint processed successfully, broadcasting...");
                         if let Err(e) = self
                             .p2p
                             .broadcast_with_exclude(slot_checkpoint_copy, &exclude_list)
                             .await
                         {
                             error!(
+                                target: "consensus::protocol_sync::handle_receive_request()",
                                 "ProtocolSync::handle_receive_slot_checkpoint(): p2p broadcast fail: {}",
                                 e
                             );
@@ -274,7 +282,7 @@ impl ProtocolSync {
                     }
                 }
                 Err(e) => {
-                    debug!("ProtocolSync::handle_receive_slot_checkpoint(): error processing finalized slot checkpoint: {}", e);
+                    debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::handle_receive_slot_checkpoint(): error processing finalized slot checkpoint: {}", e);
                 }
             };
         }
@@ -284,7 +292,7 @@ impl ProtocolSync {
 #[async_trait]
 impl ProtocolBase for ProtocolSync {
     async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!("ProtocolSync::start() [START]");
+        debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().handle_receive_request(), executor.clone()).await;
         self.jobsman
@@ -296,7 +304,7 @@ impl ProtocolBase for ProtocolSync {
             .clone()
             .spawn(self.clone().handle_receive_slot_checkpoint(), executor.clone())
             .await;
-        debug!("ProtocolSync::start() [END]");
+        debug!(target: "consensus::protocol_sync::handle_receive_request()", "ProtocolSync::start() [END]");
         Ok(())
     }
 

+ 9 - 8
src/consensus/proto/protocol_sync_consensus.rs

@@ -73,12 +73,12 @@ impl ProtocolSyncConsensus {
             let req = match self.request_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    debug!("ProtocolSyncConsensus::handle_receive_request() recv fail: {}", e);
+                    debug!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensus::handle_receive_request() recv fail: {}", e);
                     continue
                 }
             };
 
-            debug!("ProtocolSyncConsensuss::handle_receive_request() received {:?}", req);
+            debug!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensuss::handle_receive_request() received {:?}", req);
 
             // Extra validations can be added here.
             let lock = self.state.read().await;
@@ -102,23 +102,24 @@ impl ProtocolSyncConsensus {
                 nullifiers,
             };
             if let Err(e) = self.channel.send(response).await {
-                error!("ProtocolSyncConsensus::handle_receive_request() channel send fail: {}", e);
+                error!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensus::handle_receive_request() channel send fail: {}", e);
             };
         }
     }
 
     async fn handle_receive_slot_checkpoints_request(self: Arc<Self>) -> Result<()> {
-        debug!("ProtocolSyncConsensus::handle_receive_slot_checkpoints_request() [START]");
+        debug!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensus::handle_receive_slot_checkpoints_request() [START]");
         loop {
             let req = match self.slot_checkpoints_request_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    debug!("ProtocolSyncConsensus::handle_receive_slot_checkpoints_request() recv fail: {}", e);
+                    debug!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensus::handle_receive_slot_checkpoints_request() recv fail: {}", e);
                     continue
                 }
             };
 
             debug!(
+                target: "consensus::protocol_sync_consensus::handle_receive_request()",
                 "ProtocolSyncConsensuss::handle_receive_slot_checkpoints_request() received {:?}",
                 req
             );
@@ -129,7 +130,7 @@ impl ProtocolSyncConsensus {
             let is_empty = lock.consensus.slot_checkpoints.is_empty();
             let response = ConsensusSlotCheckpointsResponse { bootstrap_slot, is_empty };
             if let Err(e) = self.channel.send(response).await {
-                error!("ProtocolSyncConsensus::handle_receive_slot_checkpoints_request() channel send fail: {}", e);
+                error!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensus::handle_receive_slot_checkpoints_request() channel send fail: {}", e);
             };
         }
     }
@@ -138,14 +139,14 @@ impl ProtocolSyncConsensus {
 #[async_trait]
 impl ProtocolBase for ProtocolSyncConsensus {
     async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!("ProtocolSyncConsensus::start() [START]");
+        debug!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensus::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().handle_receive_request(), executor.clone()).await;
         self.jobsman
             .clone()
             .spawn(self.clone().handle_receive_slot_checkpoints_request(), executor.clone())
             .await;
-        debug!("ProtocolSyncConsensus::start() [END]");
+        debug!(target: "consensus::protocol_sync_consensus::handle_receive_request()", "ProtocolSyncConsensus::start() [END]");
         Ok(())
     }
 

+ 5 - 5
src/consensus/proto/protocol_tx.rs

@@ -70,13 +70,13 @@ impl ProtocolTx {
     }
 
     async fn handle_receive_tx(self: Arc<Self>) -> Result<()> {
-        debug!("ProtocolTx::handle_receive_tx() [START]");
+        debug!(target: "consensus::protocol_tx::init()", "ProtocolTx::handle_receive_tx() [START]");
         let exclude_list = vec![self.channel_address.clone()];
         loop {
             let tx = match self.tx_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    debug!("ProtocolTx::handle_receive_tx(): recv fail: {}", e);
+                    debug!(target: "consensus::protocol_tx::init()", "ProtocolTx::handle_receive_tx(): recv fail: {}", e);
                     continue
                 }
             };
@@ -86,7 +86,7 @@ impl ProtocolTx {
             // Nodes use unconfirmed_txs vector as seen_txs pool.
             if self.state.write().await.append_tx(tx_copy.clone()).await {
                 if let Err(e) = self.p2p.broadcast_with_exclude(tx_copy, &exclude_list).await {
-                    error!("handle_receive_tx(): p2p broadcast fail: {}", e);
+                    error!(target: "consensus::protocol_tx::init()", "handle_receive_tx(): p2p broadcast fail: {}", e);
                 };
             }
         }
@@ -96,10 +96,10 @@ impl ProtocolTx {
 #[async_trait]
 impl ProtocolBase for ProtocolTx {
     async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!("ProtocolTx::start() [START]");
+        debug!(target: "consensus::protocol_tx::init()", "ProtocolTx::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().handle_receive_tx(), executor.clone()).await;
-        debug!("ProtocolTx::start() [END]");
+        debug!(target: "consensus::protocol_tx::init()", "ProtocolTx::start() [END]");
         Ok(())
     }
 

+ 19 - 18
src/consensus/state.rs

@@ -237,8 +237,8 @@ impl ConsensusState {
     pub fn sigmas(&mut self) -> (pallas::Base, pallas::Base) {
         let f = self.win_inv_prob_with_full_stake();
         let total_stake = self.total_stake();
-        info!("sigmas(): f: {}", f);
-        info!("sigmas(): stake: {}", total_stake);
+        info!(target: "consensus::state", "sigmas(): f: {}", f);
+        info!(target: "consensus::state", "sigmas(): stake: {}", total_stake);
         let one = constants::FLOAT10_ONE.clone();
         let two = constants::FLOAT10_TWO.clone();
         let field_p = Float10::from_str_native(constants::P)
@@ -314,7 +314,7 @@ impl ConsensusState {
         if self.offset.is_none() {
             let (last_slot, last_offset) = self.blockchain.get_last_offset().unwrap();
             let offset = last_offset + (current_slot - last_slot);
-            info!("get_current_offset(): Setting slot offset: {}", offset);
+            info!(target: "consensus::state", "get_current_offset(): Setting slot offset: {}", offset);
             self.offset = Some(offset);
         }
 
@@ -330,6 +330,7 @@ impl ConsensusState {
         // Setup offset if only have genesis and havent received offset from other nodes
         if blocks == 0 && self.offset.is_none() {
             info!(
+                target: "consensus::state",
                 "overall_empty_slots(): Blockchain contains only genesis, setting slot offset: {}",
                 current_slot
             );
@@ -370,7 +371,7 @@ impl ConsensusState {
             }
         }
         self.leaders_history.push(count);
-        info!("extend_leaders_history(): Current leaders history: {:?}", self.leaders_history);
+        info!(target: "consensus::state", "extend_leaders_history(): Current leaders history: {:?}", self.leaders_history);
         Float10::try_from(count as i64).unwrap().with_precision(constants::RADIX_BITS).value()
     }
 
@@ -465,11 +466,11 @@ impl ConsensusState {
         let p = self.weighted_f_dif();
         let i = self.weighted_f_int();
         let d = self.weighted_f_der();
-        info!("win_inv_prob_with_full_stake(): PID P: {:?}", p);
-        info!("win_inv_prob_with_full_stake(): PID I: {:?}", i);
-        info!("win_inv_prob_with_full_stake(): PID D: {:?}", d);
+        info!(target: "consensus::state", "win_inv_prob_with_full_stake(): PID P: {:?}", p);
+        info!(target: "consensus::state", "win_inv_prob_with_full_stake(): PID I: {:?}", i);
+        info!(target: "consensus::state", "win_inv_prob_with_full_stake(): PID D: {:?}", d);
         let f = p + i.clone() + d;
-        info!("win_inv_prob_with_full_stake(): PID f: {}", f);
+        info!(target: "consensus::state", "win_inv_prob_with_full_stake(): PID f: {}", f);
         if f == constants::FLOAT10_ZERO.clone() {
             return constants::MIN_F.clone()
         } else if f >= constants::FLOAT10_ONE.clone() {
@@ -514,9 +515,9 @@ impl ConsensusState {
         let mut highest_stake_idx = 0;
         let total_stake = self.total_stake();
         for (winning_idx, coin) in competing_coins.iter().enumerate() {
-            info!("is_slot_leader: coin stake: {:?}", coin.value);
-            info!("is_slot_leader: total stake: {}", total_stake);
-            info!("is_slot_leader: relative stake: {}", (coin.value as f64) / total_stake as f64);
+            info!(target: "consensus::state", "is_slot_leader: coin stake: {:?}", coin.value);
+            info!(target: "consensus::state", "is_slot_leader: total stake: {}", total_stake);
+            info!(target: "consensus::state", "is_slot_leader: relative stake: {}", (coin.value as f64) / total_stake as f64);
             let first_winning = coin.is_leader(sigma1, sigma2);
             if first_winning && !won {
                 highest_stake_idx = winning_idx;
@@ -587,7 +588,7 @@ impl ConsensusState {
             if proposal.block.header.previous != last_block ||
                 proposal.block.header.slot <= last_slot
             {
-                info!("find_extended_chain_index(): Proposal doesn't extend any known chain");
+                info!(target: "consensus::state", "find_extended_chain_index(): Proposal doesn't extend any known chain");
                 return Ok(-2)
             }
 
@@ -602,7 +603,7 @@ impl ConsensusState {
             return Ok(chain_index)
         }
 
-        info!("find_extended_chain_index(): Proposal to fork a forkchain was received.");
+        info!(target: "consensus::state", "find_extended_chain_index(): Proposal to fork a forkchain was received.");
         let mut chain = self.forks[chain_index as usize].clone();
         // We keep all proposals until the one it extends
         chain.sequence.drain((state_checkpoint_index + 1)..);
@@ -629,16 +630,16 @@ impl ConsensusState {
         // Check if we found longest fork to extract sequence from
         match index {
             -1 => {
-                info!("set_leader_history(): No fork exists.");
+                info!(target: "consensus::state", "set_leader_history(): No fork exists.");
             }
             _ => {
-                info!("set_leader_history(): Checking last proposal of fork: {}", index);
+                info!(target: "consensus::state", "set_leader_history(): Checking last proposal of fork: {}", index);
                 let last_proposal = &self.forks[index as usize].sequence.last().unwrap().proposal;
                 if last_proposal.block.header.slot == current_slot {
                     // Replacing our last history element with the leaders one
                     self.leaders_history.pop();
                     self.leaders_history.push(last_proposal.block.lead_info.leaders);
-                    info!("set_leader_history(): New leaders history: {:?}", self.leaders_history);
+                    info!(target: "consensus::state", "set_leader_history(): New leaders history: {:?}", self.leaders_history);
                     return
                 }
             }
@@ -909,14 +910,14 @@ impl Fork {
         previous: &StateCheckpoint,
     ) -> bool {
         if state_checkpoint.proposal.block.header.previous == self.genesis_block {
-            info!("check_checkpoint(): Genesis block proposal provided.");
+            info!(target: "consensus::state", "check_checkpoint(): Genesis block proposal provided.");
             return false
         }
 
         if state_checkpoint.proposal.block.header.previous != previous.proposal.hash ||
             state_checkpoint.proposal.block.header.slot <= previous.proposal.block.header.slot
         {
-            info!("check_checkpoint(): Provided state checkpoint proposal is invalid.");
+            info!(target: "consensus::state", "check_checkpoint(): Provided state checkpoint proposal is invalid.");
             return false
         }
 

+ 9 - 9
src/consensus/task/block_sync.rs

@@ -28,7 +28,7 @@ use log::{debug, info, warn};
 
 /// async task used for block syncing.
 pub async fn block_sync_task(p2p: net::P2pPtr, state: ValidatorStatePtr) -> Result<()> {
-    info!("Starting blockchain sync...");
+    info!(target: "consensus::block_sync", "Starting blockchain sync...");
     // Getting a random connected channel to ask from peers
     match p2p.clone().random_channel().await {
         Some(channel) => {
@@ -40,7 +40,7 @@ pub async fn block_sync_task(p2p: net::P2pPtr, state: ValidatorStatePtr) -> Resu
             // Node sends the last known slot checkpoint of the canonical blockchain
             // and loops until the response is the same slot (used to utilize batch requests).
             let mut last = state.read().await.blockchain.last_slot_checkpoint()?;
-            info!("Last known slot checkpoint: {:?}", last.slot);
+            info!(target: "consensus::block_sync", "Last known slot checkpoint: {:?}", last.slot);
 
             loop {
                 // Node creates a `SlotCheckpointRequest` and sends it
@@ -51,11 +51,11 @@ pub async fn block_sync_task(p2p: net::P2pPtr, state: ValidatorStatePtr) -> Resu
                 let resp = response_sub.receive().await?;
 
                 // Verify and store retrieved checkpoints
-                debug!("block_sync_task(): Processing received slot checkpoints");
+                debug!(target: "consensus::block_sync", "block_sync_task(): Processing received slot checkpoints");
                 state.write().await.receive_slot_checkpoints(&resp.slot_checkpoints).await?;
 
                 let last_received = state.read().await.blockchain.last_slot_checkpoint()?;
-                info!("Last received slot checkpoint: {:?}", last_received.slot);
+                info!(target: "consensus::block_sync", "Last received slot checkpoint: {:?}", last_received.slot);
 
                 if last.slot == last_received.slot {
                     break
@@ -73,7 +73,7 @@ pub async fn block_sync_task(p2p: net::P2pPtr, state: ValidatorStatePtr) -> Resu
             // and loops until the response is the same block (used to utilize
             // batch requests).
             let mut last = state.read().await.blockchain.last()?;
-            info!("Last known block: {:?} - {:?}", last.0, last.1);
+            info!(target: "consensus::block_sync", "Last known block: {:?} - {:?}", last.0, last.1);
 
             loop {
                 // Node creates a `BlockOrder` and sends it
@@ -84,11 +84,11 @@ pub async fn block_sync_task(p2p: net::P2pPtr, state: ValidatorStatePtr) -> Resu
                 let resp = response_sub.receive().await?;
 
                 // Verify and store retrieved blocks
-                debug!("block_sync_task(): Processing received blocks");
+                debug!(target: "consensus::block_sync", "block_sync_task(): Processing received blocks");
                 state.write().await.receive_sync_blocks(&resp.blocks).await?;
 
                 let last_received = state.read().await.blockchain.last()?;
-                info!("Last received block: {:?} - {:?}", last_received.0, last_received.1);
+                info!(target: "consensus::block_sync", "Last received block: {:?} - {:?}", last_received.0, last_received.1);
 
                 if last == last_received {
                     break
@@ -97,9 +97,9 @@ pub async fn block_sync_task(p2p: net::P2pPtr, state: ValidatorStatePtr) -> Resu
                 last = last_received;
             }
         }
-        None => warn!("Node is not connected to other nodes"),
+        None => warn!(target: "consensus::block_sync", "Node is not connected to other nodes"),
     };
 
-    info!("Blockchain synced!");
+    info!(target: "consensus::block_sync", "Blockchain synced!");
     Ok(())
 }

+ 12 - 12
src/consensus/task/consensus_sync.rs

@@ -35,7 +35,7 @@ use crate::{
 /// Returns flag if node is not connected to other peers or consensus hasn't started,
 /// so it can immediately start proposing proposals.
 pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Result<bool> {
-    info!("Starting consensus state sync...");
+    info!(target: "consensus::consensus_sync", "Starting consensus state sync...");
     let current_slot = state.read().await.consensus.current_slot();
     // Loop through connected channels
     let channels_map = p2p.channels().lock().await;
@@ -43,11 +43,11 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
     // Using len here because is_empty() uses unstable library feature
     // called 'exact_size_is_empty'.
     if values.len() == 0 {
-        warn!("Node is not connected to other nodes");
+        warn!(target: "consensus::consensus_sync", "Node is not connected to other nodes");
         let mut lock = state.write().await;
         lock.consensus.bootstrap_slot = current_slot;
         lock.consensus.init_coins().await?;
-        info!("Consensus state synced!");
+        info!(target: "consensus::consensus_sync", "Consensus state synced!");
         return Ok(true)
     }
 
@@ -64,11 +64,11 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
         // Node checks response
         let response = response_sub.receive().await?;
         if response.bootstrap_slot == current_slot {
-            warn!("Network was just bootstraped, checking rest nodes");
+            warn!(target: "consensus::consensus_sync", "Network was just bootstraped, checking rest nodes");
             continue
         }
         if response.is_empty {
-            warn!("Node has not seen any slot checkpoints, retrying...");
+            warn!(target: "consensus::consensus_sync", "Node has not seen any slot checkpoints, retrying...");
             continue
         }
         // Keep peer to ask for consensus state
@@ -82,17 +82,17 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
     // If no peer knows about any slot checkpoints, that means that the network was bootstrapped or restarted
     // and no node has started consensus.
     if peer.is_none() {
-        warn!("No node that has seen any slot checkpoints was found, or network was just boostrapped.");
+        warn!(target: "consensus::consensus_sync", "No node that has seen any slot checkpoints was found, or network was just boostrapped.");
         let mut lock = state.write().await;
         lock.consensus.bootstrap_slot = current_slot;
         lock.consensus.init_coins().await?;
-        info!("Consensus state synced!");
+        info!(target: "consensus::consensus_sync", "Consensus state synced!");
         return Ok(true)
     }
     let peer = peer.unwrap();
 
     // Listen for next finalization
-    info!("Waiting for next finalization...");
+    info!(target: "consensus::consensus_sync", "Waiting for next finalization...");
     let subscriber = state.read().await.subscribers.get("blocks").unwrap().clone();
     let subscription = subscriber.subscribe().await;
     subscription.receive().await;
@@ -100,7 +100,7 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
 
     // After finalization occurs, sync our consensus state.
     // This ensures that the received state always consists of 1 fork with one proposal.
-    info!("Finalization signal received, requesting consensus state...");
+    info!(target: "consensus::consensus_sync", "Finalization signal received, requesting consensus state...");
     // Communication setup
     let msg_subsystem = peer.get_message_subsystem();
     msg_subsystem.add_dispatch::<ConsensusResponse>().await;
@@ -114,7 +114,7 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
     // Verify that peer has finished finalizing forks
     loop {
         if response.forks.len() != 1 || response.forks[0].sequence.len() != 1 {
-            warn!("Peer has not finished finalization, retrying...");
+            warn!(target: "consensus::consensus_sync", "Peer has not finished finalization, retrying...");
             sleep(1).await;
             peer.send(ConsensusRequest {}).await?;
             response = response_sub.receive().await?;
@@ -127,7 +127,7 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
     let last_finalized_slot = response.forks[0].sequence[0].proposal.block.header.slot - 1;
     loop {
         if !state.read().await.blockchain.has_slot(last_finalized_slot)? {
-            warn!("Node has not finished finalization, retrying...");
+            warn!(target: "consensus::consensus_sync", "Node has not finished finalization, retrying...");
             sleep(1).await;
             continue
         }
@@ -149,6 +149,6 @@ pub async fn consensus_sync_task(p2p: P2pPtr, state: ValidatorStatePtr) -> Resul
     lock.consensus.nullifiers = response.nullifiers.clone();
     lock.consensus.init_coins().await?;
 
-    info!("Consensus state synced!");
+    info!(target: "consensus::consensus_sync", "Consensus state synced!");
     Ok(false)
 }

+ 42 - 30
src/consensus/task/proposal.rs

@@ -43,7 +43,7 @@ pub async fn proposal_task(
     let bootstrap_ts = state.read().await.consensus.bootstrap_ts;
     if current_ts < bootstrap_ts {
         let diff = bootstrap_ts.0 - current_ts.0;
-        info!("consensus: Waiting for network bootstrap: {} seconds", diff);
+        info!(target: "consensus::proposal", "consensus: Waiting for network bootstrap: {} seconds", diff);
         sleep(diff as u64).await;
     } else {
         let mut sleep_time = state.read().await.consensus.next_n_slot_start(1);
@@ -53,11 +53,11 @@ pub async fn proposal_task(
                 sleep_time -= sync_offset;
                 break
             }
-            info!("consensus: Waiting for next slot ({:?})", sleep_time);
+            info!(target: "consensus::proposal", "consensus: Waiting for next slot ({:?})", sleep_time);
             sleep(sleep_time.as_secs()).await;
             sleep_time = state.read().await.consensus.next_n_slot_start(1);
         }
-        info!("consensus: Waiting for finalization sync period ({:?})", sleep_time);
+        info!(target: "consensus::proposal", "consensus: Waiting for finalization sync period ({:?})", sleep_time);
         sleep(sleep_time.as_secs()).await;
     }
 
@@ -70,8 +70,8 @@ pub async fn proposal_task(
 
         // Checking sync retries
         if retries > constants::SYNC_MAX_RETRIES {
-            error!("consensus: Node reached max sync retries ({}) due to not being able to follow up with consensus processing.", constants::SYNC_MAX_RETRIES);
-            warn!("consensus: Terminating consensus participation.");
+            error!(target: "consensus::proposal", "consensus: Node reached max sync retries ({}) due to not being able to follow up with consensus processing.", constants::SYNC_MAX_RETRIES);
+            warn!(target: "consensus::proposal", "consensus: Terminating consensus participation.");
             break
         }
 
@@ -81,12 +81,12 @@ pub async fn proposal_task(
                 // Check if node is not connected to other nodes and can
                 // start proposing immediately.
                 if p {
-                    info!("consensus: Node can start proposing!");
+                    info!(target: "consensus::proposal", "consensus: Node can start proposing!");
                     state.write().await.consensus.proposing = p;
                 }
             }
             Err(e) => {
-                error!("consensus: Failed syncing consensus state: {}. Quitting consensus.", e);
+                error!(target: "consensus::proposal", "consensus: Failed syncing consensus state: {}. Quitting consensus.", e);
                 // TODO: Perhaps notify over a channel in order to
                 // stop consensus p2p protocols.
                 return
@@ -95,8 +95,12 @@ pub async fn proposal_task(
 
         // Node modifies its participating slot to next.
         match state.write().await.consensus.set_participating() {
-            Ok(()) => info!("consensus: Node will start participating in the next slot"),
-            Err(e) => error!("consensus: Failed to set participation slot: {}", e),
+            Ok(()) => {
+                info!(target: "consensus::proposal", "consensus: Node will start participating in the next slot")
+            }
+            Err(e) => {
+                error!(target: "consensus::proposal", "consensus: Failed to set participation slot: {}", e)
+            }
         }
 
         // Record epoch we start the consensus loop
@@ -138,7 +142,7 @@ async fn consensus_loop(
         // and listened_slots doesn't increment further.
         if listened_slots > constants::EPOCH_LENGTH {
             if !changed_status {
-                info!("consensus: Node can start proposing!");
+                info!(target: "consensus::proposal", "consensus: Node can start proposing!");
                 state.write().await.consensus.proposing = true;
                 changed_status = true;
             }
@@ -150,6 +154,7 @@ async fn consensus_loop(
         if propose_period(consensus_p2p.clone(), state.clone()).await {
             // Node needs to resync
             warn!(
+                target: "consensus::proposal",
                 "consensus: Node missed slot {} due to proposal processing, resyncing...",
                 state.read().await.consensus.current_slot()
             );
@@ -160,6 +165,7 @@ async fn consensus_loop(
         if finalization_period(sync_p2p.clone(), state.clone(), ex.clone()).await {
             // Node needs to resync
             warn!(
+                target: "consensus::proposal",
                 "consensus: Node missed slot {} due to finalizated blocks processing, resyncing...",
                 state.read().await.consensus.current_slot()
             );
@@ -176,7 +182,7 @@ async fn consensus_loop(
 async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool {
     // Node sleeps until next slot
     let seconds_next_slot = state.read().await.consensus.next_n_slot_start(1).as_secs();
-    info!("consensus: Waiting for next slot ({} sec)", seconds_next_slot);
+    info!(target: "consensus::proposal", "consensus: Waiting for next slot ({} sec)", seconds_next_slot);
     sleep(seconds_next_slot).await;
 
     // Keep a record of slot to verify if next slot got skipped during processing
@@ -189,11 +195,11 @@ async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool
     match epoch_changed {
         Ok(changed) => {
             if changed {
-                info!("consensus: New epoch started: {}", state.read().await.consensus.epoch);
+                info!(target: "consensus::proposal", "consensus: New epoch started: {}", state.read().await.consensus.epoch);
             }
         }
         Err(e) => {
-            error!("consensus: Epoch check failed: {}", e);
+            error!(target: "consensus::proposal", "consensus: Epoch check failed: {}", e);
             return false
         }
     };
@@ -210,13 +216,13 @@ async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool
     let (proposal, coin) = match result {
         Ok(pair) => {
             if pair.is_none() {
-                info!("consensus: Node is not the slot lead");
+                info!(target: "consensus::proposal", "consensus: Node is not the slot lead");
                 return false
             }
             pair.unwrap()
         }
         Err(e) => {
-            error!("consensus: Block proposal failed: {}", e);
+            error!(target: "consensus::proposal", "consensus: Block proposal failed: {}", e);
             return false
         }
     };
@@ -225,6 +231,7 @@ async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool
     let next_slot_start = state.read().await.consensus.next_n_slot_start(1);
     if next_slot_start.as_secs() <= constants::FINAL_SYNC_DUR {
         warn!(
+            target: "consensus::proposal",
             "consensus: Node missed slot {} finalization period due to proposal creation, resyncing...",
             state.read().await.consensus.current_slot()
         );
@@ -232,21 +239,25 @@ async fn propose_period(consensus_p2p: P2pPtr, state: ValidatorStatePtr) -> bool
     }
 
     // Node stores the proposal and broadcast to rest nodes
-    info!("consensus: Node is the slot leader: Proposed block: {}", proposal);
-    debug!("consensus: Full proposal: {:?}", proposal);
+    info!(target: "consensus::proposal", "consensus: Node is the slot leader: Proposed block: {}", proposal);
+    debug!(target: "consensus::proposal", "consensus: Full proposal: {:?}", proposal);
     match state.write().await.receive_proposal(&proposal, Some((coin_index, coin))).await {
         Ok(_) => {
             // Here we don't have to check to broadcast, because the flag
             // will always be true, since the node is able to produce proposals
-            info!("consensus: Block proposal saved successfully");
+            info!(target: "consensus::proposal", "consensus: Block proposal saved successfully");
             // Broadcast proposal to other consensus nodes
             match consensus_p2p.broadcast(proposal).await {
-                Ok(()) => info!("consensus: Proposal broadcasted successfully"),
-                Err(e) => error!("consensus: Failed broadcasting proposal: {}", e),
+                Ok(()) => {
+                    info!(target: "consensus::proposal", "consensus: Proposal broadcasted successfully")
+                }
+                Err(e) => {
+                    error!(target: "consensus::proposal", "consensus: Failed broadcasting proposal: {}", e)
+                }
             }
         }
         Err(e) => {
-            error!("consensus: Block proposal save failed: {}", e);
+            error!(target: "consensus::proposal", "consensus: Block proposal save failed: {}", e);
         }
     }
 
@@ -266,10 +277,11 @@ async fn finalization_period(
     if next_slot_start.as_secs() > constants::FINAL_SYNC_DUR {
         let seconds_sync_period =
             (next_slot_start - Duration::new(constants::FINAL_SYNC_DUR, 0)).as_secs();
-        info!("consensus: Waiting for finalization sync period ({} sec)", seconds_sync_period);
+        info!(target: "consensus::proposal", "consensus: Waiting for finalization sync period ({} sec)", seconds_sync_period);
         sleep(seconds_sync_period).await;
     } else {
         warn!(
+            target: "consensus::proposal",
             "consensus: Node missed slot {} finalization period due to proposals processing, resyncing...",
             state.read().await.consensus.current_slot()
         );
@@ -286,32 +298,32 @@ async fn finalization_period(
             if !to_broadcast_block.is_empty() || !to_broadcast_slot_checkpoints.is_empty() {
                 ex.spawn(async move {
                     // Broadcast finalized blocks info, if any:
-                    info!("consensus: Broadcasting finalized blocks");
+                    info!(target: "consensus::proposal", "consensus: Broadcasting finalized blocks");
                     for info in to_broadcast_block {
                         match sync_p2p.broadcast(info).await {
-                            Ok(()) => info!("consensus: Broadcasted block"),
-                            Err(e) => error!("consensus: Failed broadcasting block: {}", e),
+                            Ok(()) => info!(target: "consensus::proposal", "consensus: Broadcasted block"),
+                            Err(e) => error!(target: "consensus::proposal", "consensus: Failed broadcasting block: {}", e),
                         }
                     }
 
                     // Broadcast finalized slot checkpoints, if any:
-                    info!("consensus: Broadcasting finalized slot checkpoints");
+                    info!(target: "consensus::proposal", "consensus: Broadcasting finalized slot checkpoints");
                     for slot_checkpoint in to_broadcast_slot_checkpoints {
                         match sync_p2p.broadcast(slot_checkpoint).await {
-                            Ok(()) => info!("consensus: Broadcasted slot_checkpoint"),
+                            Ok(()) => info!(target: "consensus::proposal", "consensus: Broadcasted slot_checkpoint"),
                             Err(e) => {
-                                error!("consensus: Failed broadcasting slot_checkpoint: {}", e)
+                                error!(target: "consensus::proposal", "consensus: Failed broadcasting slot_checkpoint: {}", e)
                             }
                         }
                     }
                 })
                 .detach();
             } else {
-                info!("consensus: No finalized blocks or slot checkpoints to broadcast");
+                info!(target: "consensus::proposal", "consensus: No finalized blocks or slot checkpoints to broadcast");
             }
         }
         Err(e) => {
-            error!("consensus: Finalization check failed: {}", e);
+            error!(target: "consensus::proposal", "consensus: Finalization check failed: {}", e);
         }
     }
 

+ 3 - 3
src/consensus/utils.rs

@@ -27,8 +27,8 @@ pub fn fbig2ibig(f: Float10) -> IBig {
     let sig = f.repr().significand();
     let exp = f.repr().exponent();
     let val: IBig = if exp >= 0 { sig.clone() * rad.pow(exp as usize) } else { sig.clone() };
-    debug!("fbig2ibig (f): {}", f);
-    debug!("fbig2ibig (i): {}", val);
+    debug!(target: "consensus::utils", "fbig2ibig (f): {}", f);
+    debug!(target: "consensus::utils", "fbig2ibig (i): {}", val);
     val
 }
 /*
@@ -48,7 +48,7 @@ pub fn base2ibig(base: pallas::Base) -> IBig {
 }
 */
 pub fn fbig2base(f: Float10) -> pallas::Base {
-    debug!("fbig -> base (f): {}", f);
+    debug!(target: "consensus::utils", "fbig -> base (f): {}", f);
     let val: IBig = fbig2ibig(f);
     let (sign, word) = val.as_sign_words();
     let mut words: [u64; 4] = [0, 0, 0, 0];

+ 112 - 86
src/consensus/validator.rs

@@ -98,9 +98,9 @@ impl ValidatorState {
         faucet_pubkeys: Vec<PublicKey>,
         enable_participation: bool,
     ) -> Result<ValidatorStatePtr> {
-        debug!("Initializing ValidatorState");
+        debug!(target: "consensus::validator", "Initializing ValidatorState");
 
-        debug!("Initializing wallet tables for consensus");
+        debug!(target: "consensus::validator", "Initializing wallet tables for consensus");
         // TODO: TESTNET: The stuff is kept entirely in memory for now, what should we write
         //                to disk/wallet?
         //let consensus_tree_init_query = include_str!("../../script/sql/consensus_tree.sql");
@@ -108,7 +108,7 @@ impl ValidatorState {
         //wallet.exec_sql(consensus_tree_init_query).await?;
         //wallet.exec_sql(consensus_keys_init_query).await?;
 
-        debug!("Generating leader proof keys with k: {}", constants::LEADER_PROOF_K);
+        debug!(target: "consensus::validator", "Generating leader proof keys with k: {}", constants::LEADER_PROOF_K);
         let bincode = include_bytes!("../../proof/lead.zk.bin");
         let zkbin = ZkBinary::decode(bincode)?;
         let witnesses = empty_witnesses(&zkbin);
@@ -170,17 +170,17 @@ impl ValidatorState {
             ),
         ];
 
-        info!("Deploying native wasm contracts");
+        info!(target: "consensus::validator", "Deploying native wasm contracts");
         for nc in native_contracts {
-            info!("Deploying {} with ContractID {}", nc.0, nc.1);
+            info!(target: "consensus::validator", "Deploying {} with ContractID {}", nc.0, nc.1);
             let mut runtime = Runtime::new(&nc.2[..], blockchain.clone(), nc.1)?;
             runtime.deploy(&nc.3)?;
-            info!("Successfully deployed {}", nc.0);
+            info!(target: "consensus::validator", "Successfully deployed {}", nc.0);
 
             // When deployed, we can do a lookup for the zkas circuits and
             // initialize verifying keys for them.
-            info!("Creating ZK verifying keys for {} zkas circuits", nc.0);
-            info!("Looking up zkas db for {} (ContractID: {})", nc.0, nc.1);
+            info!(target: "consensus::validator", "Creating ZK verifying keys for {} zkas circuits", nc.0);
+            info!(target: "consensus::validator", "Looking up zkas db for {} (ContractID: {})", nc.0, nc.1);
             let zkas_db = blockchain.contracts.lookup(
                 &blockchain.sled_db,
                 &nc.1,
@@ -189,11 +189,11 @@ impl ValidatorState {
 
             let mut vks = vec![];
             for i in zkas_db.iter() {
-                info!("Iterating over zkas db");
+                info!(target: "consensus::validator", "Iterating over zkas db");
                 let (zkas_ns, zkas_bincode) = i?;
-                info!("Deserializing namespace");
+                info!(target: "consensus::validator", "Deserializing namespace");
                 let zkas_ns: String = deserialize(&zkas_ns)?;
-                info!("Creating VerifyingKey for zkas circuit with namespace {}", zkas_ns);
+                info!(target: "consensus::validator", "Creating VerifyingKey for zkas circuit with namespace {}", zkas_ns);
                 let zkbin = ZkBinary::decode(&zkas_bincode)?;
                 let circuit = ZkCircuit::new(empty_witnesses(&zkbin), zkbin);
                 // FIXME: This k=13 man...
@@ -201,10 +201,10 @@ impl ValidatorState {
                 vks.push((zkas_ns, vk));
             }
 
-            info!("Finished creating VerifyingKey objects for {} (ContractID: {})", nc.0, nc.1);
+            info!(target: "consensus::validator", "Finished creating VerifyingKey objects for {} (ContractID: {})", nc.0, nc.1);
             verifying_keys.insert(nc.1.to_bytes(), vks);
         }
-        info!("Finished deployment of native wasm contracts");
+        info!(target: "consensus::validator", "Finished deployment of native wasm contracts");
         // -----NATIVE WASM CONTRACTS-----
 
         // Here we initialize various subscribers that can export live consensus/blockchain data.
@@ -233,23 +233,23 @@ impl ValidatorState {
         let tx_in_txstore = match self.blockchain.transactions.contains(&tx_hash) {
             Ok(v) => v,
             Err(e) => {
-                error!("append_tx(): Failed querying txstore: {}", e);
+                error!(target: "consensus::validator", "append_tx(): Failed querying txstore: {}", e);
                 return false
             }
         };
 
         if self.unconfirmed_txs.contains(&tx) || tx_in_txstore {
-            info!("append_tx(): We have already seen this tx.");
+            info!(target: "consensus::validator", "append_tx(): We have already seen this tx.");
             return false
         }
 
-        info!("append_tx(): Starting state transition validation");
+        info!(target: "consensus::validator", "append_tx(): Starting state transition validation");
         if let Err(e) = self.verify_transactions(&[tx.clone()], false).await {
-            error!("append_tx(): Failed to verify transaction: {}", e);
+            error!(target: "consensus::validator", "append_tx(): Failed to verify transaction: {}", e);
             return false
         };
 
-        info!("append_tx(): Appended tx to mempool");
+        info!(target: "consensus::validator", "append_tx(): Appended tx to mempool");
         self.unconfirmed_txs.push(tx);
         true
     }
@@ -373,7 +373,7 @@ impl ValidatorState {
 
         // Node have already checked for finalization in this slot
         if current <= self.consensus.checked_finalization {
-            warn!("receive_proposal(): Proposal received after finalization sync period.");
+            warn!(target: "consensus::validator", "receive_proposal(): Proposal received after finalization sync period.");
             return Err(Error::ProposalAfterFinalizationError)
         }
 
@@ -395,6 +395,7 @@ impl ValidatorState {
             elapsed_slots <= (constants::EPOCH_LENGTH as u64)
         {
             warn!(
+                target: "consensus::validator",
                 "receive_proposal(): Proposer {} is not eligible to produce proposals",
                 lf.public_key
             );
@@ -410,6 +411,7 @@ impl ValidatorState {
         // Check that proposal transactions don't exceed limit
         if proposal.block.txs.len() > constants::TXS_CAP {
             warn!(
+                target: "consensus::validator",
                 "receive_proposal(): Received proposal transactions exceed configured cap: {} - {}",
                 proposal.block.txs.len(),
                 constants::TXS_CAP
@@ -420,7 +422,7 @@ impl ValidatorState {
         // Verify proposal signature is valid based on producer public key
         // TODO: derive public key from proof
         if !lf.public_key.verify(proposal.header.as_bytes(), &lf.signature) {
-            warn!("receive_proposal(): Proposer {} signature could not be verified", lf.public_key);
+            warn!(target: "consensus::validator", "receive_proposal(): Proposer {} signature could not be verified", lf.public_key);
             return Err(Error::InvalidSignature)
         }
 
@@ -428,6 +430,7 @@ impl ValidatorState {
         let proposal_hash = proposal.block.blockhash();
         if proposal.hash != proposal_hash {
             warn!(
+                target: "consensus::validator",
                 "receive_proposal(): Received proposal contains mismatched hashes: {} - {}",
                 proposal.hash, proposal_hash
             );
@@ -438,6 +441,7 @@ impl ValidatorState {
         let proposal_header = hdr.headerhash();
         if proposal.header != proposal_header {
             warn!(
+                target: "consensus::validator",
                 "receive_proposal(): Received proposal contains mismatched headers: {} - {}",
                 proposal.header, proposal_header
             );
@@ -448,6 +452,7 @@ impl ValidatorState {
         let offset = self.consensus.get_current_offset(current);
         if offset != lf.offset {
             warn!(
+                target: "consensus::validator",
                 "receive_proposal(): Received proposal contains different offset: {} - {}",
                 offset, lf.offset
             );
@@ -456,10 +461,10 @@ impl ValidatorState {
 
         // Verify proposal leader proof
         if let Err(e) = lf.proof.verify(&self.lead_verifying_key, &lf.public_inputs) {
-            error!("receive_proposal(): Error during leader proof verification: {}", e);
+            error!(target: "consensus::validator", "receive_proposal(): Error during leader proof verification: {}", e);
             return Err(Error::LeaderProofVerification)
         };
-        info!("receive_proposal(): Leader proof verified successfully!");
+        info!(target: "consensus::validator", "receive_proposal(): Leader proof verified successfully!");
 
         // Validate proposal public value against coin creation slot checkpoint
         let checkpoint = self.consensus.get_slot_checkpoint(lf.coin_slot)?;
@@ -471,6 +476,7 @@ impl ValidatorState {
         let prop_mu_y = lf.public_inputs[constants::PI_MU_Y_INDEX];
         if mu_y != prop_mu_y {
             error!(
+                target: "consensus::validator",
                 "receive_proposal(): Failed to verify mu_y: {:?}, proposed: {:?}",
                 mu_y, prop_mu_y
             );
@@ -480,6 +486,7 @@ impl ValidatorState {
         let prop_mu_rho = lf.public_inputs[constants::PI_MU_RHO_INDEX];
         if mu_rho != prop_mu_rho {
             error!(
+                target: "consensus::validator",
                 "receive_proposal(): Failed to verify mu_rho: {:?}, proposed: {:?}",
                 mu_rho, prop_mu_rho
             );
@@ -492,6 +499,7 @@ impl ValidatorState {
         let prop_sigma1 = lf.public_inputs[constants::PI_SIGMA1_INDEX];
         if checkpoint.sigma1 != prop_sigma1 {
             error!(
+                target: "consensus::validator",
                 "receive_proposal(): Failed to verify public value sigma1: {:?}, to proposed: {:?}",
                 checkpoint.sigma1, prop_sigma1
             );
@@ -500,6 +508,7 @@ impl ValidatorState {
         let prop_sigma2 = lf.public_inputs[constants::PI_SIGMA2_INDEX];
         if checkpoint.sigma2 != prop_sigma2 {
             error!(
+                target: "consensus::validator",
                 "receive_proposal(): Failed to verify public value sigma2: {:?}, to proposed: {:?}",
                 checkpoint.sigma2, prop_sigma2
             );
@@ -532,7 +541,7 @@ impl ValidatorState {
         let prop_sn = lf.public_inputs[constants::PI_NULLIFIER_INDEX];
         for sn in &state_checkpoint.nullifiers {
             if *sn == prop_sn {
-                error!("receive_proposal(): Proposal nullifiers exist.");
+                error!(target: "consensus::validator", "receive_proposal(): Proposal nullifiers exist.");
                 return Err(Error::ProposalIsSpent)
             }
         }
@@ -542,17 +551,17 @@ impl ValidatorState {
         let tree_root: MerkleNode = self.consensus.coins_tree.root(0).unwrap();
         let prop_cm_root: pallas::Base = lf.public_inputs[constants::PI_COMMITMENT_ROOT];
         if tree_root.inner() <= prop_cm_root {
-            error!("validation of tree root failed");
-            info!("tree_root: {:?}", tree_root.inner());
-            info!("prop_root: {:?}", prop_cm_root);
+            error!(target: "consensus::validator", "validation of tree root failed");
+            info!(target: "consensus::validator", "tree_root: {:?}", tree_root.inner());
+            info!(target: "consensus::validator", "prop_root: {:?}", prop_cm_root);
         }
         */
 
         // Validate state transition against canonical state
         // TODO: This should be validated against fork state
-        info!("receive_proposal(): Starting state transition validation");
+        info!(target: "consensus::validator", "receive_proposal(): Starting state transition validation");
         if let Err(e) = self.verify_transactions(&proposal.block.txs, false).await {
-            error!("receive_proposal(): Transaction verifications failed: {}", e);
+            error!(target: "consensus::validator", "receive_proposal(): Transaction verifications failed: {}", e);
             return Err(e)
         };
 
@@ -599,7 +608,7 @@ impl ValidatorState {
     /// slot checkpoints until current slot are apppended to canonical state.
     pub async fn chain_finalization(&mut self) -> Result<(Vec<BlockInfo>, Vec<SlotCheckpoint>)> {
         let slot = self.consensus.current_slot();
-        info!("chain_finalization(): Started finalization check for slot: {}", slot);
+        info!(target: "consensus::validator", "chain_finalization(): Started finalization check for slot: {}", slot);
         // Set last slot finalization check occured to current slot
         self.consensus.checked_finalization = slot;
 
@@ -639,16 +648,18 @@ impl ValidatorState {
         // Check if we found any fork to finalize
         match fork_index {
             -2 => {
-                info!("chain_finalization(): Eligible forks with same height exist, nothing to finalize.");
+                info!(target: "consensus::validator", "chain_finalization(): Eligible forks with same height exist, nothing to finalize.");
                 self.consensus.set_leader_history(index_for_history, slot);
                 return Ok((vec![], vec![]))
             }
             -1 => {
-                info!("chain_finalization(): All chains have less than 3 proposals, nothing to finalize.");
+                info!(target: "consensus::validator", "chain_finalization(): All chains have less than 3 proposals, nothing to finalize.");
                 self.consensus.set_leader_history(index_for_history, slot);
                 return Ok((vec![], vec![]))
             }
-            _ => info!("chain_finalization(): Chain {} can be finalized!", fork_index),
+            _ => {
+                info!(target: "consensus::validator", "chain_finalization(): Chain {} can be finalized!", fork_index)
+            }
         }
 
         // Starting finalization
@@ -667,11 +678,11 @@ impl ValidatorState {
         fork.sequence.drain(..bound);
 
         // Adding finalized proposals to canonical
-        info!("consensus: Adding {} finalized block to canonical chain.", finalized.len());
+        info!(target: "consensus::validator", "consensus: Adding {} finalized block to canonical chain.", finalized.len());
         match self.blockchain.add(&finalized) {
             Ok(v) => v,
             Err(e) => {
-                error!("consensus: Failed appending finalized blocks to canonical chain: {}", e);
+                error!(target: "consensus::validator", "consensus: Failed appending finalized blocks to canonical chain: {}", e);
                 return Err(e)
             }
         };
@@ -684,22 +695,22 @@ impl ValidatorState {
             // TODO: These state transitions have already been checked. (I wrote this, but where?)
             // TODO: FIXME: The state transitions have already been written, they have to be in memory
             //              until this point.
-            info!(target: "consensus", "Applying state transition for finalized block");
+            info!(target: "consensus::validator", "Applying state transition for finalized block");
             if let Err(e) = self.verify_transactions(&proposal.txs, true).await {
-                error!(target: "consensus", "Finalized block transaction verifications failed: {}", e);
+                error!(target: "consensus::validator", "Finalized block transaction verifications failed: {}", e);
                 return Err(e)
             }
 
             // Remove proposal transactions from memory pool
             if let Err(e) = self.remove_txs(&proposal.txs) {
-                error!(target: "consensus", "Removing finalized block transactions failed: {}", e);
+                error!(target: "consensus::validator", "Removing finalized block transactions failed: {}", e);
                 return Err(e)
             }
 
             // TODO: Don't hardcode this:
             let params = json!([bs58::encode(&serialize(proposal)).into_string()]);
             let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
-            info!("consensus: Sending notification about finalized block");
+            info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
             blocks_subscriber.notify(notif).await;
         }
 
@@ -731,6 +742,7 @@ impl ValidatorState {
         self.consensus.slot_checkpoints.drain(..bound);
 
         debug!(
+            target: "consensus::validator",
             "consensus: Adding {} finalized slot checkpoints to canonical chain.",
             finalized_slot_checkpoints.len()
         );
@@ -738,6 +750,7 @@ impl ValidatorState {
             Ok(v) => v,
             Err(e) => {
                 error!(
+                    target: "consensus::validator",
                     "consensus: Failed appending finalized slot checkpoints to canonical chain: {}",
                     e
                 );
@@ -763,16 +776,16 @@ impl ValidatorState {
     /// Validate and append to canonical state received blocks.
     pub async fn receive_blocks(&mut self, blocks: &[BlockInfo]) -> Result<()> {
         // Verify state transitions for all blocks and their respective transactions.
-        info!("receive_blocks(): Starting state transition validations");
+        info!(target: "consensus::validator", "receive_blocks(): Starting state transition validations");
         for block in blocks {
             if let Err(e) = self.verify_transactions(&block.txs, true).await {
-                error!("receive_blocks(): Transaction verifications failed: {}", e);
+                error!(target: "consensus::validator", "receive_blocks(): Transaction verifications failed: {}", e);
                 return Err(e)
             }
         }
 
-        info!("receive_blocks(): All state transitions passed");
-        info!("receive_blocks(): Appending blocks to ledger");
+        info!(target: "consensus::validator", "receive_blocks(): All state transitions passed");
+        info!(target: "consensus::validator", "receive_blocks(): Appending blocks to ledger");
         self.blockchain.add(blocks)?;
 
         Ok(())
@@ -784,27 +797,27 @@ impl ValidatorState {
         match self.blockchain.has_block(&block) {
             Ok(v) => {
                 if v {
-                    info!("receive_finalized_block(): Existing block received");
+                    info!(target: "consensus::validator", "receive_finalized_block(): Existing block received");
                     return Ok(false)
                 }
             }
             Err(e) => {
-                error!("receive_finalized_block(): failed checking for has_block(): {}", e);
+                error!(target: "consensus::validator", "receive_finalized_block(): failed checking for has_block(): {}", e);
                 return Ok(false)
             }
         };
 
-        info!("receive_finalized_block(): Executing state transitions");
+        info!(target: "consensus::validator", "receive_finalized_block(): Executing state transitions");
         self.receive_blocks(&[block.clone()]).await?;
 
         // TODO: Don't hardcode this:
         let blocks_subscriber = self.subscribers.get("blocks").unwrap();
         let params = json!([bs58::encode(&serialize(&block)).into_string()]);
         let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
-        info!("consensus: Sending notification about finalized block");
+        info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
         blocks_subscriber.notify(notif).await;
 
-        info!("receive_finalized_block(): Removing block transactions from unconfirmed_txs");
+        info!(target: "consensus::validator", "receive_finalized_block(): Removing block transactions from unconfirmed_txs");
         self.remove_txs(&block.txs)?;
 
         Ok(true)
@@ -818,24 +831,24 @@ impl ValidatorState {
             match self.blockchain.has_block(block) {
                 Ok(v) => {
                     if v {
-                        info!("receive_sync_blocks(): Existing block received");
+                        info!(target: "consensus::validator", "receive_sync_blocks(): Existing block received");
                         continue
                     }
                     new_blocks.push(block.clone());
                 }
                 Err(e) => {
-                    error!("receive_sync_blocks(): failed checking for has_block(): {}", e);
+                    error!(target: "consensus::validator", "receive_sync_blocks(): failed checking for has_block(): {}", e);
                     continue
                 }
             };
         }
 
         if new_blocks.is_empty() {
-            info!("receive_sync_blocks(): no new blocks to append");
+            info!(target: "consensus::validator", "receive_sync_blocks(): no new blocks to append");
             return Ok(())
         }
 
-        info!("receive_sync_blocks(): Executing state transitions");
+        info!(target: "consensus::validator", "receive_sync_blocks(): Executing state transitions");
         self.receive_blocks(&new_blocks[..]).await?;
 
         // TODO: Don't hardcode this:
@@ -843,7 +856,7 @@ impl ValidatorState {
         for block in new_blocks {
             let params = json!([bs58::encode(&serialize(&block)).into_string()]);
             let notif = JsonNotification::new("blockchain.subscribe_blocks", params);
-            info!("consensus: Sending notification about finalized block");
+            info!(target: "consensus::validator", "consensus: Sending notification about finalized block");
             blocks_subscriber.notify(notif).await;
         }
 
@@ -859,10 +872,10 @@ impl ValidatorState {
     // TODO: This should be paralellized as if even one tx in the batch fails to verify,
     //       we can drop everything.
     pub async fn verify_transactions(&self, txs: &[Transaction], write: bool) -> Result<()> {
-        info!("Verifying {} transaction(s)", txs.len());
+        info!(target: "consensus::validator", "Verifying {} transaction(s)", txs.len());
         for tx in txs {
             let tx_hash = blake3::hash(&serialize(tx));
-            info!("Verifying transaction {}", tx_hash);
+            info!(target: "consensus::validator", "Verifying transaction {}", tx_hash);
 
             // Table of public inputs used for ZK proof verification
             let mut zkp_table = vec![];
@@ -873,14 +886,15 @@ impl ValidatorState {
 
             // Iterate over all calls to get the metadata
             for (idx, call) in tx.calls.iter().enumerate() {
-                info!("Executing contract call {}", idx);
+                info!(target: "consensus::validator", "Executing contract call {}", idx);
                 let wasm = match self.blockchain.wasm_bincode.get(call.contract_id) {
                     Ok(v) => {
-                        info!("Found wasm bincode for {}", call.contract_id);
+                        info!(target: "consensus::validator", "Found wasm bincode for {}", call.contract_id);
                         v
                     }
                     Err(e) => {
                         error!(
+                            target: "consensus::validator",
                             "Could not find wasm bincode for contract {}: {}",
                             call.contract_id, e
                         );
@@ -899,6 +913,7 @@ impl ValidatorState {
                         Ok(v) => v,
                         Err(e) => {
                             error!(
+                                target: "consensus::validator",
                                 "Failed to instantiate WASM runtime for contract {}",
                                 call.contract_id
                             );
@@ -906,49 +921,51 @@ impl ValidatorState {
                         }
                     };
 
-                info!("Executing \"metadata\" call");
+                info!(target: "consensus::validator", "Executing \"metadata\" call");
                 let metadata = match runtime.metadata(&payload) {
                     Ok(v) => v,
                     Err(e) => {
-                        error!("Failed to execute \"metadata\" call: {}", e);
+                        error!(target: "consensus::validator", "Failed to execute \"metadata\" call: {}", e);
                         return Err(e)
                     }
                 };
 
                 // Decode the metadata retrieved from the execution
                 let mut decoder = Cursor::new(&metadata);
-                let zkp_pub: Vec<(String, Vec<pallas::Base>)> =
-                    match Decodable::decode(&mut decoder) {
-                        Ok(v) => v,
-                        Err(e) => {
-                            error!("Failed to decode ZK public inputs from metadata: {}", e);
-                            return Err(e.into())
-                        }
-                    };
+                let zkp_pub: Vec<(String, Vec<pallas::Base>)> = match Decodable::decode(
+                    &mut decoder,
+                ) {
+                    Ok(v) => v,
+                    Err(e) => {
+                        error!(target: "consensus::validator", "Failed to decode ZK public inputs from metadata: {}", e);
+                        return Err(e.into())
+                    }
+                };
 
                 let sig_pub: Vec<PublicKey> = match Decodable::decode(&mut decoder) {
                     Ok(v) => v,
                     Err(e) => {
-                        error!("Failed to decode signature pubkeys from metadata: {}", e);
+                        error!(target: "consensus::validator", "Failed to decode signature pubkeys from metadata: {}", e);
                         return Err(e.into())
                     }
                 };
 
                 // TODO: Make sure we've read all the bytes above.
-                info!("Successfully executed \"metadata\" call");
+                info!(target: "consensus::validator", "Successfully executed \"metadata\" call");
                 zkp_table.push(zkp_pub);
                 sig_table.push(sig_pub);
 
                 // After getting the metadata, we run the "exec" function with the same
                 // runtime and the same payload.
-                info!("Executing \"exec\" call");
+                info!(target: "consensus::validator", "Executing \"exec\" call");
                 match runtime.exec(&payload) {
                     Ok(v) => {
-                        info!("Successfully executed \"exec\" call");
+                        info!(target: "consensus::validator", "Successfully executed \"exec\" call");
                         updates.push(v);
                     }
                     Err(e) => {
                         error!(
+                            target: "consensus::validator",
                             "Failed to execute \"exec\" call for contract id {}: {}",
                             call.contract_id, e
                         );
@@ -961,16 +978,18 @@ impl ValidatorState {
             // When we're done looping and executing over the tx's contract calls, we
             // move on with verification. First we verify the signatures as that's
             // cheaper, and then finally we verify the ZK proofs.
-            info!("Verifying signatures for transaction {}", tx_hash);
+            info!(target: "consensus::validator", "Verifying signatures for transaction {}", tx_hash);
             if sig_table.len() != tx.signatures.len() {
-                error!("Incorrect number of signatures in tx {}", tx_hash);
+                error!(target: "consensus::validator", "Incorrect number of signatures in tx {}", tx_hash);
                 return Err(Error::InvalidSignature)
             }
 
             match tx.verify_sigs(sig_table) {
-                Ok(()) => info!("Signatures verification for tx {} successful", tx_hash),
+                Ok(()) => {
+                    info!(target: "consensus::validator", "Signatures verification for tx {} successful", tx_hash)
+                }
                 Err(e) => {
-                    error!("Signature verification for tx {} failed: {}", tx_hash, e);
+                    error!(target: "consensus::validator", "Signature verification for tx {} failed: {}", tx_hash, e);
                     return Err(e)
                 }
             };
@@ -979,11 +998,13 @@ impl ValidatorState {
             // verifying keys, but if we do not find them, we'll generate them
             // inside of this function. This can be kinda expensive, so open to
             // alternatives.
-            info!("Verifying ZK proofs for transaction {}", tx_hash);
+            info!(target: "consensus::validator", "Verifying ZK proofs for transaction {}", tx_hash);
             match tx.verify_zkps(self.verifying_keys.clone(), zkp_table).await {
-                Ok(()) => info!("ZK proof verification for tx {} successful", tx_hash),
+                Ok(()) => {
+                    info!(target: "consensus::validator", "ZK proof verification for tx {} successful", tx_hash)
+                }
                 Err(e) => {
-                    error!("ZK proof verification for tx {} failed: {}", tx_hash, e);
+                    error!(target: "consensus::validator", "ZK proof verification for tx {} failed: {}", tx_hash, e);
                     return Err(e)
                 }
             };
@@ -992,7 +1013,7 @@ impl ValidatorState {
             // apply the state updates.
             assert!(tx.calls.len() == updates.len());
             if write {
-                info!("Performing state updates");
+                info!(target: "consensus::validator", "Performing state updates");
                 for (call, update) in tx.calls.iter().zip(updates.iter()) {
                     // For this we instantiate the runtimes again.
                     // TODO: Optimize this
@@ -1000,11 +1021,12 @@ impl ValidatorState {
                     //       and verification and these.
                     let wasm = match self.blockchain.wasm_bincode.get(call.contract_id) {
                         Ok(v) => {
-                            info!("Found wasm bincode for {}", call.contract_id);
+                            info!(target: "consensus::validator", "Found wasm bincode for {}", call.contract_id);
                             v
                         }
                         Err(e) => {
                             error!(
+                                target: "consensus::validator",
                                 "Could not find wasm bincode for contract {}: {}",
                                 call.contract_id, e
                             );
@@ -1017,6 +1039,7 @@ impl ValidatorState {
                             Ok(v) => v,
                             Err(e) => {
                                 error!(
+                                    target: "consensus::validator",
                                     "Failed to instantiate WASM runtime for contract {}",
                                     call.contract_id
                                 );
@@ -1024,21 +1047,23 @@ impl ValidatorState {
                             }
                         };
 
-                    info!("Executing \"apply\" call");
+                    info!(target: "consensus::validator", "Executing \"apply\" call");
                     match runtime.apply(update) {
                         // TODO: FIXME: This should be done in an atomic tx/batch
-                        Ok(()) => info!("State update applied successfully"),
+                        Ok(()) => {
+                            info!(target: "consensus::validator", "State update applied successfully")
+                        }
                         Err(e) => {
-                            error!("Failed to apply state update: {}", e);
+                            error!(target: "consensus::validator", "Failed to apply state update: {}", e);
                             return Err(e)
                         }
                     };
                 }
             } else {
-                info!("Skipping apply of state updates because write=false");
+                info!(target: "consensus::validator", "Skipping apply of state updates because write=false");
             }
 
-            info!("Transaction {} verified successfully", tx_hash);
+            info!(target: "consensus::validator", "Transaction {} verified successfully", tx_hash);
         }
 
         Ok(())
@@ -1049,7 +1074,7 @@ impl ValidatorState {
         &mut self,
         slot_checkpoints: &[SlotCheckpoint],
     ) -> Result<()> {
-        info!("receive_slot_checkpoints(): Appending slot checkpoints to ledger");
+        info!(target: "consensus::validator", "receive_slot_checkpoints(): Appending slot checkpoints to ledger");
         self.blockchain.add_slot_checkpoints(slot_checkpoints)?;
 
         Ok(())
@@ -1065,13 +1090,14 @@ impl ValidatorState {
             Ok(v) => {
                 if v {
                     info!(
+                        target: "consensus::validator",
                         "receive_finalized_slot_checkpoints(): Existing slot checkpoint received"
                     );
                     return Ok(false)
                 }
             }
             Err(e) => {
-                error!("receive_finalized_slot_checkpoints(): failed checking for has_slot_checkpoint(): {}", e);
+                error!(target: "consensus::validator", "receive_finalized_slot_checkpoints(): failed checking for has_slot_checkpoint(): {}", e);
                 return Ok(false)
             }
         };

+ 1 - 1
src/consensus/wallet.rs

@@ -35,7 +35,7 @@ pub trait ConsensusWallet {
 #[async_trait]
 impl ConsensusWallet for WalletDb {
     async fn get_default_keypair(&self) -> Result<Keypair> {
-        debug!("Returning default keypair");
+        debug!(target: "consensus::wallet", "Returning default keypair");
         let mut conn = self.conn.acquire().await?;
 
         let row = sqlx::query(&format!(

+ 1 - 1
src/contract/dao/Cargo.toml

@@ -11,7 +11,7 @@ crate-type = ["cdylib", "rlib"]
 [dependencies]
 darkfi-sdk = { path = "../../sdk" }
 darkfi-serial = { path = "../../serial", features = ["derive", "crypto"] }
-darkfi-money-contract = { path = "../money", features = ["client", "no-entrypoint"] }
+darkfi-money-contract = { path = "../money", features = ["no-entrypoint"] }
 
 # The following dependencies are used for the client API and
 # probably shouldn't be in WASM

+ 1 - 1
src/contract/dao/src/dao_client.rs

@@ -186,7 +186,7 @@ pub fn build_dao_mint_tx(
     dao_mint_zkbin: &ZkBinary,
     dao_mint_pk: &ProvingKey,
 ) -> Result<(DaoMintParams, Vec<Proof>)> {
-    debug!("Building DAO contract mint transaction");
+    debug!(target: "dao", "Building DAO contract mint transaction");
 
     let (proof, revealed) = create_dao_mint_proof(
         dao_mint_zkbin,

+ 1 - 1
src/contract/dao/src/dao_exec_client.rs

@@ -74,7 +74,7 @@ impl Builder {
         exec_zkbin: &ZkBinary,
         exec_pk: &ProvingKey,
     ) -> Result<(DaoExecParams, Vec<Proof>)> {
-        debug!(target: "dao_contract::exec::wallet::Builder", "build()");
+        debug!(target: "dao", "build()");
         let mut proofs = vec![];
 
         let (proposal_dest_x, proposal_dest_y) = self.proposal.dest.xy();

+ 3 - 3
src/contract/dao/src/dao_vote_client.rs

@@ -93,7 +93,7 @@ impl Builder {
         main_zkbin: &ZkBinary,
         main_pk: &ProvingKey,
     ) -> Result<(DaoVoteParams, Vec<Proof>)> {
-        debug!(target: "dao_contract::vote::wallet::Builder", "build()");
+        debug!(target: "dao", "build()");
         let mut proofs = vec![];
 
         let gov_token_blind = pallas::Base::random(&mut OsRng);
@@ -189,7 +189,7 @@ impl Builder {
             ];
 
             let circuit = ZkCircuit::new(prover_witnesses, burn_zkbin.clone());
-            debug!(target: "dao_contract::vote::wallet::Builder", "input_proof Proof::create()");
+            debug!(target: "dao", "input_proof Proof::create()");
             let input_proof = Proof::create(&burn_pk, &[circuit], &public_inputs, &mut OsRng)
                 .expect("DAO::vote() proving error!");
             proofs.push(input_proof);
@@ -298,7 +298,7 @@ impl Builder {
 
         let circuit = ZkCircuit::new(prover_witnesses, main_zkbin.clone());
 
-        debug!(target: "dao_contract::vote::wallet::Builder", "main_proof = Proof::create()");
+        debug!(target: "dao", "main_proof = Proof::create()");
         let main_proof = Proof::create(&main_pk, &[circuit], &public_inputs, &mut OsRng)
             .expect("DAO::vote() proving error!");
         proofs.push(main_proof);

+ 2 - 2
src/contract/dao/tests/dao_harness.rs

@@ -136,7 +136,7 @@ impl DaoTestHarness {
             SMART_CONTRACT_ZKAS_DB_NAME,
         )?;
 
-        info!("Decoding bincode");
+        info!(target: "dao", "Decoding bincode");
 
         let money_mint_zkbin =
             money_db_handle.get(&serialize(&MONEY_CONTRACT_ZKAS_MINT_NS_V1))?.unwrap();
@@ -190,7 +190,7 @@ impl DaoTestHarness {
         let dao_exec_witnesses = empty_witnesses(&dao_exec_zkbin);
         let dao_exec_circuit = ZkCircuit::new(dao_exec_witnesses, dao_exec_zkbin.clone());
 
-        info!("Creating zk proving keys");
+        info!(target: "dao", "Creating zk proving keys");
 
         let k = 13;
         let mut proving_keys = HashMap::<[u8; 32], Vec<(&str, ProvingKey)>>::new();

+ 35 - 35
src/contract/dao/tests/integration.rs

@@ -91,13 +91,13 @@ async fn integration_test() -> Result<()> {
     //
     // Create the DAO bulla
     // =======================================================
-    debug!(target: "demo", "Stage 1. Creating DAO bulla");
+    debug!(target: "dao", "Stage 1. Creating DAO bulla");
 
     let dao_bulla_blind = pallas::Base::random(&mut OsRng);
 
-    info!("[Alice] =========================");
-    info!("[Alice] Building Dao::Mint params");
-    info!("[Alice] =========================");
+    info!(target: "dao", "[Alice] =========================");
+    info!(target: "dao", "[Alice] Building Dao::Mint params");
+    info!(target: "dao", "[Alice] =========================");
     let (params, proofs) = build_dao_mint_tx(
         dao_proposer_limit,
         dao_quorum,
@@ -111,9 +111,9 @@ async fn integration_test() -> Result<()> {
         &dao_th.dao_mint_pk,
     )?;
 
-    info!("[Alice] ==========================================");
-    info!("[Alice] Building Dao::Mint transaction with params");
-    info!("[Alice] ==========================================");
+    info!(target: "dao", "[Alice] ==========================================");
+    info!(target: "dao", "[Alice] Building Dao::Mint transaction with params");
+    info!(target: "dao", "[Alice] ==========================================");
     let mut data = vec![DaoFunction::Mint as u8];
     params.encode(&mut data)?;
     let calls = vec![ContractCall { contract_id: dao_th.dao_contract_id, data }];
@@ -122,9 +122,9 @@ async fn integration_test() -> Result<()> {
     let sigs = tx.create_sigs(&mut OsRng, &[])?;
     tx.signatures = vec![sigs];
 
-    info!("[Alice] ===============================");
-    info!("[Alice] Executing Dao::Mint transaction");
-    info!("[Alice] ===============================");
+    info!(target: "dao", "[Alice] ===============================");
+    info!(target: "dao", "[Alice] Executing Dao::Mint transaction");
+    info!(target: "dao", "[Alice] ===============================");
     dao_th.alice_state.read().await.verify_transactions(&[tx.clone()], true).await?;
     // TODO: Witness and add to wallet merkle tree?
 
@@ -135,7 +135,7 @@ async fn integration_test() -> Result<()> {
         dao_tree.witness().unwrap()
     };
     let dao_bulla = params.dao_bulla;
-    debug!(target: "demo", "Created DAO bulla: {:?}", dao_bulla.inner());
+    debug!(target: "dao", "Created DAO bulla: {:?}", dao_bulla.inner());
 
     // =======================================================
     // Money::Transfer
@@ -143,7 +143,7 @@ async fn integration_test() -> Result<()> {
     // Mint the initial supply of treasury token
     // and send it all to the DAO directly
     // =======================================================
-    debug!(target: "demo", "Stage 2. Minting treasury token");
+    debug!(target: "dao", "Stage 2. Minting treasury token");
 
     cache.track(dao_th.dao_kp.secret);
 
@@ -240,7 +240,7 @@ async fn integration_test() -> Result<()> {
     assert_eq!(treasury_note.spend_hook, spend_hook);
     assert_eq!(treasury_note.user_data, dao_bulla.inner());
 
-    debug!("DAO received a coin worth {} xDRK", treasury_note.value);
+    debug!(target: "dao", "DAO received a coin worth {} xDRK", treasury_note.value);
 
     // =======================================================
     // Money::Transfer
@@ -248,7 +248,7 @@ async fn integration_test() -> Result<()> {
     // Mint the governance token
     // Send it to three hodlers
     // =======================================================
-    debug!(target: "demo", "Stage 3. Minting governance token");
+    debug!(target: "dao", "Stage 3. Minting governance token");
 
     cache.track(dao_th.alice_kp.secret);
     cache.track(dao_th.bob_kp.secret);
@@ -363,7 +363,7 @@ async fn integration_test() -> Result<()> {
             ]);
             assert_eq!(coin, recv_coin.coin.0);
 
-            debug!("Holder{} received a coin worth {} gDRK", i, note.value);
+            debug!(target: "dao", "Holder{} received a coin worth {} gDRK", i, note.value);
 
             recv_coin
         };
@@ -388,7 +388,7 @@ async fn integration_test() -> Result<()> {
     //   output 0: value and address
     //   output 1: change address
     // =======================================================
-    debug!(target: "demo", "Stage 4. Propose the vote");
+    debug!(target: "dao", "Stage 4. Propose the vote");
 
     // TODO: look into proposal expiry once time for voting has finished
 
@@ -481,12 +481,12 @@ async fn integration_test() -> Result<()> {
         // Return the proposal info
         (note.proposal, params.proposal_bulla)
     };
-    debug!(target: "demo", "Proposal now active!");
-    debug!(target: "demo", "  destination: {:?}", proposal.dest);
-    debug!(target: "demo", "  amount: {}", proposal.amount);
-    debug!(target: "demo", "  token_id: {:?}", proposal.token_id);
-    debug!(target: "demo", "  dao_bulla: {:?}", dao_bulla.inner());
-    debug!(target: "demo", "Proposal bulla: {:?}", proposal_bulla);
+    debug!(target: "dao", "Proposal now active!");
+    debug!(target: "dao", "  destination: {:?}", proposal.dest);
+    debug!(target: "dao", "  amount: {}", proposal.amount);
+    debug!(target: "dao", "  token_id: {:?}", proposal.token_id);
+    debug!(target: "dao", "  dao_bulla: {:?}", dao_bulla.inner());
+    debug!(target: "dao", "Proposal bulla: {:?}", proposal_bulla);
 
     // =======================================================
     // Proposal is accepted!
@@ -512,7 +512,7 @@ async fn integration_test() -> Result<()> {
     // beginning of gov period
     // Cannot use nullifiers from before voting period
 
-    debug!(target: "demo", "Stage 5. Start voting");
+    debug!(target: "dao", "Stage 5. Start voting");
 
     // We were previously saving updates here for testing
     // let mut updates = vec![];
@@ -584,9 +584,9 @@ async fn integration_test() -> Result<()> {
         let note: dao_vote_client::Note = enc_note.decrypt(&vote_keypair_1.secret).unwrap();
         note
     };
-    debug!(target: "demo", "User 1 voted!");
-    debug!(target: "demo", "  vote_option: {}", vote_note_1.vote.vote_option);
-    debug!(target: "demo", "  value: {}", vote_note_1.vote_value);
+    debug!(target: "dao", "User 1 voted!");
+    debug!(target: "dao", "  vote_option: {}", vote_note_1.vote.vote_option);
+    debug!(target: "dao", "  value: {}", vote_note_1.vote_value);
 
     // User 2: NO
 
@@ -652,9 +652,9 @@ async fn integration_test() -> Result<()> {
         let note: dao_vote_client::Note = enc_note.decrypt(&vote_keypair_2.secret).unwrap();
         note
     };
-    debug!(target: "demo", "User 2 voted!");
-    debug!(target: "demo", "  vote_option: {}", vote_note_2.vote.vote_option);
-    debug!(target: "demo", "  value: {}", vote_note_2.vote_value);
+    debug!(target: "dao", "User 2 voted!");
+    debug!(target: "dao", "  vote_option: {}", vote_note_2.vote.vote_option);
+    debug!(target: "dao", "  value: {}", vote_note_2.vote_value);
 
     // User 3: YES
 
@@ -723,9 +723,9 @@ async fn integration_test() -> Result<()> {
         let note: dao_vote_client::Note = enc_note.decrypt(&vote_keypair_3.secret).unwrap();
         note
     };
-    debug!(target: "demo", "User 3 voted!");
-    debug!(target: "demo", "  vote_option: {}", vote_note_3.vote.vote_option);
-    debug!(target: "demo", "  value: {}", vote_note_3.vote_value);
+    debug!(target: "dao", "User 3 voted!");
+    debug!(target: "dao", "  vote_option: {}", vote_note_3.vote.vote_option);
+    debug!(target: "dao", "  value: {}", vote_note_3.vote_value);
 
     // Every votes produces a semi-homomorphic encryption of their vote.
     // Which is either yes or no
@@ -775,10 +775,10 @@ async fn integration_test() -> Result<()> {
         all_votes_value += note.vote_value;
         let vote_result: String = if vote_option { "yes".to_string() } else { "no".to_string() };
 
-        debug!("Voter {} voted {}", i, vote_result);
+        debug!(target: "dao", "Voter {} voted {}", i, vote_result);
     }
 
-    debug!("Outcome = {} / {}", yes_votes_value, all_votes_value);
+    debug!(target: "dao", "Outcome = {} / {}", yes_votes_value, all_votes_value);
 
     assert!(all_votes_commit == pedersen_commitment_u64(all_votes_value, all_votes_blind));
     assert!(yes_votes_commit == pedersen_commitment_u64(yes_votes_value, yes_votes_blind));
@@ -787,7 +787,7 @@ async fn integration_test() -> Result<()> {
     // Execute the vote
     // =======================================================
 
-    debug!(target: "demo", "Stage 6. Execute vote");
+    debug!(target: "dao", "Stage 6. Execute vote");
 
     // Used to export user_data from this coin so it can be accessed by DAO::exec()
     let user_data_blind = pallas::Base::random(&mut OsRng);

+ 13 - 13
src/contract/money/src/client.rs

@@ -678,15 +678,15 @@ pub fn build_half_swap_tx(
     Vec<ValueBlind>,
     Vec<ValueBlind>,
 )> {
-    debug!("Building OTC swap transaction half");
+    debug!(target: "money", "Building OTC swap transaction half");
     assert!(value_send != 0);
     assert!(value_recv != 0);
     assert!(!coins.is_empty());
 
-    debug!("Money::build_half_swap_tx(): Building anonymous inputs");
+    debug!(target: "money", "Money::build_half_swap_tx(): Building anonymous inputs");
     // We'll take any coin that has correct value
     let Some(coin) = coins.iter().find(|x| x.note.value == value_send && x.note.token_id == token_id_send) else {
-        error!("Money::build_half_swap_tx(): Did not find a coin with enough value to swap");
+        error!(target: "money", "Money::build_half_swap_tx(): Did not find a coin with enough value to swap");
         return Err(ClientFailed::NotEnoughValue(value_send).into())
     };
 
@@ -752,7 +752,7 @@ pub fn build_half_swap_tx(
 
     let mut zk_proofs = vec![];
 
-    info!("Creating swap burn proof for input 0");
+    info!(target: "money", "Creating swap burn proof for input 0");
     let (proof, revealed) = create_transfer_burn_proof(
         burn_zkbin,
         burn_pk,
@@ -790,7 +790,7 @@ pub fn build_half_swap_tx(
     let spend_hook = pallas::Base::zero();
     let user_data = pallas::Base::zero();
 
-    info!("Creating swap mint proof for output 0");
+    info!(target: "money", "Creating swap mint proof for output 0");
     let (proof, revealed) = create_transfer_mint_proof(
         mint_zkbin,
         mint_pk,
@@ -863,7 +863,7 @@ pub fn build_transfer_tx(
     burn_pk: &ProvingKey,
     clear_input: bool,
 ) -> Result<(MoneyTransferParams, Vec<Proof>, Vec<SecretKey>, Vec<OwnCoin>)> {
-    debug!("Building money contract transfer transaction");
+    debug!(target: "money", "Building money contract transfer transaction");
     assert!(value != 0);
     if !clear_input {
         assert!(!coins.is_empty());
@@ -880,16 +880,16 @@ pub fn build_transfer_tx(
     let mut spent_coins = vec![];
 
     if clear_input {
-        debug!("Money::build_transfer_tx(): Building clear input");
+        debug!(target: "money", "Money::build_transfer_tx(): Building clear input");
         let input =
             TransactionBuilderClearInputInfo { value, token_id, signature_secret: keypair.secret };
         clear_inputs.push(input);
     } else {
-        debug!("Money::build_transfer_tx(): Building anonymous inputs");
+        debug!(target: "money", "Money::build_transfer_tx(): Building anonymous inputs");
         let mut inputs_value = 0;
         for coin in coins.iter() {
             if inputs_value >= value {
-                debug!("inputs_value >= value");
+                debug!(target: "money", "inputs_value >= value");
                 break
             }
 
@@ -910,7 +910,7 @@ pub fn build_transfer_tx(
         }
 
         if inputs_value < value {
-            error!("Money::build_transfer_tx(): Not enough value to build tx inputs");
+            error!(target: "money", "Money::build_transfer_tx(): Not enough value to build tx inputs");
             return Err(ClientFailed::NotEnoughValue(inputs_value).into())
         }
 
@@ -923,7 +923,7 @@ pub fn build_transfer_tx(
             });
         }
 
-        debug!("Money::build_transfer_tx(): Finished building inputs");
+        debug!(target: "money", "Money::build_transfer_tx(): Finished building inputs");
     }
 
     outputs.push(TransactionBuilderOutputInfo { value, token_id, public_key: *pubkey });
@@ -967,7 +967,7 @@ pub fn build_transfer_tx(
         let user_data = pallas::Base::zero();
         let user_data_blind = pallas::Base::random(&mut OsRng);
 
-        info!("Creating transfer burn proof for input {}", i);
+        info!(target: "money", "Creating transfer burn proof for input {}", i);
         let (proof, revealed) = create_transfer_burn_proof(
             burn_zkbin,
             burn_pk,
@@ -1018,7 +1018,7 @@ pub fn build_transfer_tx(
         let spend_hook = pallas::Base::zero();
         let user_data = pallas::Base::zero();
 
-        info!("Creating transfer mint proof for output {}", i);
+        info!(target: "money", "Creating transfer mint proof for output {}", i);
         let (proof, revealed) = create_transfer_mint_proof(
             mint_zkbin,
             mint_pk,

+ 112 - 112
src/contract/money/tests/drop_pay_swap.rs

@@ -71,9 +71,9 @@ async fn money_contract_transfer() -> Result<()> {
     let mut alice_owncoins = vec![];
     let mut bob_owncoins = vec![];
 
-    info!("[Faucet] ===================================================");
-    info!("[Faucet] Building Money::Transfer params for Alice's airdrop");
-    info!("[Faucet] ===================================================");
+    info!(target: "money", "[Faucet] ===================================================");
+    info!(target: "money", "[Faucet] Building Money::Transfer params for Alice's airdrop");
+    info!(target: "money", "[Faucet] ===================================================");
     let (alice_params, alice_proofs, alicedrop_secret_keys, _spent_coins) = build_transfer_tx(
         &th.faucet_kp,
         &th.alice_kp.public,
@@ -88,9 +88,9 @@ async fn money_contract_transfer() -> Result<()> {
         true,
     )?;
 
-    info!("[Faucet] =================================================");
-    info!("[Faucet] Building Money::Transfer params for Bob's airdrop");
-    info!("[Faucet] =================================================");
+    info!(target: "money", "[Faucet] =================================================");
+    info!(target: "money", "[Faucet] Building Money::Transfer params for Bob's airdrop");
+    info!(target: "money", "[Faucet] =================================================");
     let (bob_params, bob_proofs, bobdrop_secret_keys, _spent_coins) = build_transfer_tx(
         &th.faucet_kp,
         &th.bob_kp.public,
@@ -105,9 +105,9 @@ async fn money_contract_transfer() -> Result<()> {
         true,
     )?;
 
-    info!("[Faucet] =====================================");
-    info!("[Faucet] Building airdrop tx with Alice params");
-    info!("[Faucet] =====================================");
+    info!(target: "money", "[Faucet] =====================================");
+    info!(target: "money", "[Faucet] Building airdrop tx with Alice params");
+    info!(target: "money", "[Faucet] =====================================");
     let mut data = vec![MoneyFunction::Transfer as u8];
     alice_params.encode(&mut data)?;
     let calls = vec![ContractCall { contract_id: th.money_contract_id, data }];
@@ -116,9 +116,9 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = alicedrop_tx.create_sigs(&mut OsRng, &alicedrop_secret_keys)?;
     alicedrop_tx.signatures = vec![sigs];
 
-    info!("[Faucet] ===================================");
-    info!("[Faucet] Building airdrop tx with Bob params");
-    info!("[Faucet] ===================================");
+    info!(target: "money", "[Faucet] ===================================");
+    info!(target: "money", "[Faucet] Building airdrop tx with Bob params");
+    info!(target: "money", "[Faucet] ===================================");
     let mut data = vec![MoneyFunction::Transfer as u8];
     bob_params.encode(&mut data)?;
     let calls = vec![ContractCall { contract_id: th.money_contract_id, data }];
@@ -127,41 +127,41 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = bobdrop_tx.create_sigs(&mut OsRng, &bobdrop_secret_keys)?;
     bobdrop_tx.signatures = vec![sigs];
 
-    info!("[Faucet] ==========================");
-    info!("[Faucet] Executing Alice airdrop tx");
-    info!("[Faucet] ==========================");
+    info!(target: "money", "[Faucet] ==========================");
+    info!(target: "money", "[Faucet] Executing Alice airdrop tx");
+    info!(target: "money", "[Faucet] ==========================");
     th.faucet_state.read().await.verify_transactions(&[alicedrop_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(alice_params.outputs[0].coin));
 
-    info!("[Faucet] ========================");
-    info!("[Faucet] Executing Bob airdrop tx");
-    info!("[Faucet] ========================");
+    info!(target: "money", "[Faucet] ========================");
+    info!(target: "money", "[Faucet] Executing Bob airdrop tx");
+    info!(target: "money", "[Faucet] ========================");
     th.faucet_state.read().await.verify_transactions(&[bobdrop_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(bob_params.outputs[0].coin));
 
-    info!("[Alice] ==========================");
-    info!("[Alice] Executing Alice airdrop tx");
-    info!("[Alice] ==========================");
+    info!(target: "money", "[Alice] ==========================");
+    info!(target: "money", "[Alice] Executing Alice airdrop tx");
+    info!(target: "money", "[Alice] ==========================");
     th.alice_state.read().await.verify_transactions(&[alicedrop_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(alice_params.outputs[0].coin));
     // Alice has to witness this coin because it's hers.
     let alice_leaf_pos = th.alice_merkle_tree.witness().unwrap();
 
-    info!("[Alice] ========================");
-    info!("[Alice] Executing Bob airdrop tx");
-    info!("[Alice] ========================");
+    info!(target: "money", "[Alice] ========================");
+    info!(target: "money", "[Alice] Executing Bob airdrop tx");
+    info!(target: "money", "[Alice] ========================");
     th.alice_state.read().await.verify_transactions(&[bobdrop_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(bob_params.outputs[0].coin));
 
-    info!("[Bob] ==========================");
-    info!("[Bob] Executing Alice airdrop tx");
-    info!("[Bob] ==========================");
+    info!(target: "money", "[Bob] ==========================");
+    info!(target: "money", "[Bob] Executing Alice airdrop tx");
+    info!(target: "money", "[Bob] ==========================");
     th.bob_state.read().await.verify_transactions(&[alicedrop_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(alice_params.outputs[0].coin));
 
-    info!("[Bob] ========================");
-    info!("[Bob] Executing Bob airdrop tx");
-    info!("[Bob] ========================");
+    info!(target: "money", "[Bob] ========================");
+    info!(target: "money", "[Bob] Executing Bob airdrop tx");
+    info!(target: "money", "[Bob] ========================");
     th.bob_state.read().await.verify_transactions(&[bobdrop_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(bob_params.outputs[0].coin));
     let bob_leaf_pos = th.bob_merkle_tree.witness().unwrap();
@@ -198,9 +198,9 @@ async fn money_contract_transfer() -> Result<()> {
     bob_owncoins.push(bob_oc);
 
     // Now Alice can send a little bit of funds to Bob
-    info!("[Alice] ====================================================");
-    info!("[Alice] Building Money::Transfer params for a payment to Bob");
-    info!("[Alice] ====================================================");
+    info!(target: "money", "[Alice] ====================================================");
+    info!(target: "money", "[Alice] Building Money::Transfer params for a payment to Bob");
+    info!(target: "money", "[Alice] ====================================================");
     let (alice2bob_params, alice2bob_proofs, alice2bob_secret_keys, alice2bob_spent_coins) =
         build_transfer_tx(
             &th.alice_kp,
@@ -222,9 +222,9 @@ async fn money_contract_transfer() -> Result<()> {
     alice_owncoins.retain(|x| x != &alice2bob_spent_coins[0]);
     assert!(alice_owncoins.is_empty());
 
-    info!("[Alice] ==========================");
-    info!("[Alice] Building payment tx to Bob");
-    info!("[Alice] ==========================");
+    info!(target: "money", "[Alice] ==========================");
+    info!(target: "money", "[Alice] Building payment tx to Bob");
+    info!(target: "money", "[Alice] ==========================");
     let mut data = vec![MoneyFunction::Transfer as u8];
     alice2bob_params.encode(&mut data)?;
     let calls = vec![ContractCall { contract_id: th.money_contract_id, data }];
@@ -233,24 +233,24 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = alice2bob_tx.create_sigs(&mut OsRng, &alice2bob_secret_keys)?;
     alice2bob_tx.signatures = vec![sigs];
 
-    info!("[Faucet] ==============================");
-    info!("[Faucet] Executing Alice2Bob payment tx");
-    info!("[Faucet] ==============================");
+    info!(target: "money", "[Faucet] ==============================");
+    info!(target: "money", "[Faucet] Executing Alice2Bob payment tx");
+    info!(target: "money", "[Faucet] ==============================");
     th.faucet_state.read().await.verify_transactions(&[alice2bob_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(alice2bob_params.outputs[0].coin));
     th.faucet_merkle_tree.append(&MerkleNode::from(alice2bob_params.outputs[1].coin));
 
-    info!("[Alice] ==============================");
-    info!("[Alice] Executing Alice2Bob payment tx");
-    info!("[Alice] ==============================");
+    info!(target: "money", "[Alice] ==============================");
+    info!(target: "money", "[Alice] Executing Alice2Bob payment tx");
+    info!(target: "money", "[Alice] ==============================");
     th.alice_state.read().await.verify_transactions(&[alice2bob_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(alice2bob_params.outputs[0].coin));
     let alice_leaf_pos = th.alice_merkle_tree.witness().unwrap();
     th.alice_merkle_tree.append(&MerkleNode::from(alice2bob_params.outputs[1].coin));
 
-    info!("[Bob] ==============================");
-    info!("[Bob] Executing Alice2Bob payment tx");
-    info!("[Bob] ==============================");
+    info!(target: "money", "[Bob] ==============================");
+    info!(target: "money", "[Bob] Executing Alice2Bob payment tx");
+    info!(target: "money", "[Bob] ==============================");
     th.bob_state.read().await.verify_transactions(&[alice2bob_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(alice2bob_params.outputs[0].coin));
     th.bob_merkle_tree.append(&MerkleNode::from(alice2bob_params.outputs[1].coin));
@@ -291,9 +291,9 @@ async fn money_contract_transfer() -> Result<()> {
     assert!(bob_owncoins.len() == 2);
 
     // Bob can send a little bit to Alice as well
-    info!("[Bob] ======================================================");
-    info!("[Bob] Building Money::Transfer params for a payment to Alice");
-    info!("[Bob] ======================================================");
+    info!(target: "money", "[Bob] ======================================================");
+    info!(target: "money", "[Bob] Building Money::Transfer params for a payment to Alice");
+    info!(target: "money", "[Bob] ======================================================");
     let mut bob_owncoins_tmp = bob_owncoins.clone();
     bob_owncoins_tmp.retain(|x| x.note.token_id == bob_token_id);
     let (bob2alice_params, bob2alice_proofs, bob2alice_secret_keys, bob2alice_spent_coins) =
@@ -317,9 +317,9 @@ async fn money_contract_transfer() -> Result<()> {
     bob_owncoins.retain(|x| x != &bob2alice_spent_coins[0]);
     assert!(bob_owncoins.len() == 1);
 
-    info!("[Bob] ============================");
-    info!("[Bob] Building payment tx to Alice");
-    info!("[Bob] ============================");
+    info!(target: "money", "[Bob] ============================");
+    info!(target: "money", "[Bob] Building payment tx to Alice");
+    info!(target: "money", "[Bob] ============================");
     let mut data = vec![MoneyFunction::Transfer as u8];
     bob2alice_params.encode(&mut data)?;
     let calls = vec![ContractCall { contract_id: th.money_contract_id, data }];
@@ -328,24 +328,24 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = bob2alice_tx.create_sigs(&mut OsRng, &bob2alice_secret_keys)?;
     bob2alice_tx.signatures = vec![sigs];
 
-    info!("[Faucet] ==============================");
-    info!("[Faucet] Executing Bob2Alice payment tx");
-    info!("[Faucet] ==============================");
+    info!(target: "money", "[Faucet] ==============================");
+    info!(target: "money", "[Faucet] Executing Bob2Alice payment tx");
+    info!(target: "money", "[Faucet] ==============================");
     th.faucet_state.read().await.verify_transactions(&[bob2alice_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(bob2alice_params.outputs[0].coin));
     th.faucet_merkle_tree.append(&MerkleNode::from(bob2alice_params.outputs[1].coin));
 
-    info!("[Alice] ==============================");
-    info!("[Alice] Executing Bob2Alice payment tx");
-    info!("[Alice] ==============================");
+    info!(target: "money", "[Alice] ==============================");
+    info!(target: "money", "[Alice] Executing Bob2Alice payment tx");
+    info!(target: "money", "[Alice] ==============================");
     th.alice_state.read().await.verify_transactions(&[bob2alice_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(bob2alice_params.outputs[0].coin));
     th.alice_merkle_tree.append(&MerkleNode::from(bob2alice_params.outputs[1].coin));
     let alice_leaf_pos = th.alice_merkle_tree.witness().unwrap();
 
-    info!("[Bob] ==================+===========");
-    info!("[Bob] Executing Bob2Alice payment tx");
-    info!("[Bob] ==================+===========");
+    info!(target: "money", "[Bob] ==================+===========");
+    info!(target: "money", "[Bob] Executing Bob2Alice payment tx");
+    info!(target: "money", "[Bob] ==================+===========");
     th.bob_state.read().await.verify_transactions(&[bob2alice_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(bob2alice_params.outputs[0].coin));
     let bob_leaf_pos = th.bob_merkle_tree.witness().unwrap();
@@ -396,7 +396,7 @@ async fn money_contract_transfer() -> Result<()> {
 
     // Alice and Bob decide to swap back their tokens so Alice gets back her initial
     // tokens and Bob gets his.
-    info!("[Alice] Building OtcSwap half");
+    info!(target: "money", "[Alice] Building OtcSwap half");
     let (
         alice_swap_params,
         alice_swap_proofs,
@@ -427,7 +427,7 @@ async fn money_contract_transfer() -> Result<()> {
     assert!(alice_owncoins.len() == 1);
 
     // Alice sends Bob necessary data and he builds his half.
-    info!("[Bob] Building OtcSwap half");
+    info!(target: "money", "[Bob] Building OtcSwap half");
     let (
         bob_swap_params,
         bob_swap_proofs,
@@ -486,24 +486,24 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = alicebob_swap_tx.create_sigs(&mut OsRng, &alice_swap_secret_keys)?;
     alicebob_swap_tx.signatures[0].insert(0, sigs[0]);
 
-    info!("[Faucet] ==========================");
-    info!("[Faucet] Executing AliceBob swap tx");
-    info!("[Faucet] ==========================");
+    info!(target: "money", "[Faucet] ==========================");
+    info!(target: "money", "[Faucet] Executing AliceBob swap tx");
+    info!(target: "money", "[Faucet] ==========================");
     th.faucet_state.read().await.verify_transactions(&[alicebob_swap_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[0].coin));
     th.faucet_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[1].coin));
 
-    info!("[Alice] ==========================");
-    info!("[Alice] Executing AliceBob swap tx");
-    info!("[Alice] ==========================");
+    info!(target: "money", "[Alice] ==========================");
+    info!(target: "money", "[Alice] Executing AliceBob swap tx");
+    info!(target: "money", "[Alice] ==========================");
     th.alice_state.read().await.verify_transactions(&[alicebob_swap_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[0].coin));
     let alice_leaf_pos = th.alice_merkle_tree.witness().unwrap();
     th.alice_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[1].coin));
 
-    info!("[Bob] ==========================");
-    info!("[Bob] Executing AliceBob swap tx");
-    info!("[Bob] ==========================");
+    info!(target: "money", "[Bob] ==========================");
+    info!(target: "money", "[Bob] Executing AliceBob swap tx");
+    info!(target: "money", "[Bob] ==========================");
     th.bob_state.read().await.verify_transactions(&[alicebob_swap_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[0].coin));
     th.bob_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[1].coin));
@@ -549,9 +549,9 @@ async fn money_contract_transfer() -> Result<()> {
     assert!(bob_owncoins[1].note.token_id == bob_token_id);
 
     // Now Alice will create a new coin for herself to combine the two owncoins.
-    info!("[Alice] ======================================================");
-    info!("[Alice] Building Money::Transfer params for a payment to Alice");
-    info!("[Alice] =======================================================");
+    info!(target: "money", "[Alice] ======================================================");
+    info!(target: "money", "[Alice] Building Money::Transfer params for a payment to Alice");
+    info!(target: "money", "[Alice] =======================================================");
     let (alice2alice_params, alice2alice_proofs, alice2alice_secret_keys, alice2alice_spent_coins) =
         build_transfer_tx(
             &th.alice_kp,
@@ -574,9 +574,9 @@ async fn money_contract_transfer() -> Result<()> {
     assert!(alice2alice_params.inputs.len() == 2);
     assert!(alice2alice_params.outputs.len() == 1);
 
-    info!("[Alice] ============================");
-    info!("[Alice] Building payment tx to Alice");
-    info!("[Alice] ============================");
+    info!(target: "money", "[Alice] ============================");
+    info!(target: "money", "[Alice] Building payment tx to Alice");
+    info!(target: "money", "[Alice] ============================");
     let mut data = vec![MoneyFunction::Transfer as u8];
     alice2alice_params.encode(&mut data)?;
     let calls = vec![ContractCall { contract_id: th.money_contract_id, data }];
@@ -585,22 +585,22 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = alice2alice_tx.create_sigs(&mut OsRng, &alice2alice_secret_keys)?;
     alice2alice_tx.signatures = vec![sigs];
 
-    info!("[Faucet] ================================");
-    info!("[Faucet] Executing Alice2Alice payment tx");
-    info!("[Faucet] ================================");
+    info!(target: "money", "[Faucet] ================================");
+    info!(target: "money", "[Faucet] Executing Alice2Alice payment tx");
+    info!(target: "money", "[Faucet] ================================");
     th.faucet_state.read().await.verify_transactions(&[alice2alice_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(alice2alice_params.outputs[0].coin));
 
-    info!("[Alice] ================================");
-    info!("[Alice] Executing Alice2Alice payment tx");
-    info!("[Alice] ================================");
+    info!(target: "money", "[Alice] ================================");
+    info!(target: "money", "[Alice] Executing Alice2Alice payment tx");
+    info!(target: "money", "[Alice] ================================");
     th.alice_state.read().await.verify_transactions(&[alice2alice_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(alice2alice_params.outputs[0].coin));
     let alice_leaf_pos = th.alice_merkle_tree.witness().unwrap();
 
-    info!("[Bob] ================================");
-    info!("[Bob] Executing Alice2Alice payment tx");
-    info!("[Bob] ================================");
+    info!(target: "money", "[Bob] ================================");
+    info!(target: "money", "[Bob] Executing Alice2Alice payment tx");
+    info!(target: "money", "[Bob] ================================");
     th.bob_state.read().await.verify_transactions(&[alice2alice_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(alice2alice_params.outputs[0].coin));
 
@@ -626,9 +626,9 @@ async fn money_contract_transfer() -> Result<()> {
     assert!(alice_owncoins[0].note.token_id == alice_token_id);
 
     // Bob does the same
-    info!("[Bob] ====================================================");
-    info!("[Bob] Building Money::Transfer params for a payment to Bob");
-    info!("[Bob] ====================================================");
+    info!(target: "money", "[Bob] ====================================================");
+    info!(target: "money", "[Bob] Building Money::Transfer params for a payment to Bob");
+    info!(target: "money", "[Bob] ====================================================");
     let (bob2bob_params, bob2bob_proofs, bob2bob_secret_keys, bob2bob_spent_coins) =
         build_transfer_tx(
             &th.bob_kp,
@@ -651,9 +651,9 @@ async fn money_contract_transfer() -> Result<()> {
     assert!(bob2bob_params.inputs.len() == 2);
     assert!(bob2bob_params.outputs.len() == 1);
 
-    info!("[Bob] ==========================");
-    info!("[Bob] Building payment tx to Bob");
-    info!("[Bob] ==========================");
+    info!(target: "money", "[Bob] ==========================");
+    info!(target: "money", "[Bob] Building payment tx to Bob");
+    info!(target: "money", "[Bob] ==========================");
     let mut data = vec![MoneyFunction::Transfer as u8];
     bob2bob_params.encode(&mut data)?;
     let calls = vec![ContractCall { contract_id: th.money_contract_id, data }];
@@ -662,21 +662,21 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = bob2bob_tx.create_sigs(&mut OsRng, &bob2bob_secret_keys)?;
     bob2bob_tx.signatures = vec![sigs];
 
-    info!("[Faucet] ============================");
-    info!("[Faucet] Executing Bob2Bob payment tx");
-    info!("[Faucet] ============================");
+    info!(target: "money", "[Faucet] ============================");
+    info!(target: "money", "[Faucet] Executing Bob2Bob payment tx");
+    info!(target: "money", "[Faucet] ============================");
     th.faucet_state.read().await.verify_transactions(&[bob2bob_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(bob2bob_params.outputs[0].coin));
 
-    info!("[Alice] ============================");
-    info!("[Alice] Executing Bob2Bob payment tx");
-    info!("[Alice] ============================");
+    info!(target: "money", "[Alice] ============================");
+    info!(target: "money", "[Alice] Executing Bob2Bob payment tx");
+    info!(target: "money", "[Alice] ============================");
     th.alice_state.read().await.verify_transactions(&[bob2bob_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(bob2bob_params.outputs[0].coin));
 
-    info!("[Bob] ============================");
-    info!("[Bob] Executing Bob2Bob payment tx");
-    info!("[Bob] ============================");
+    info!(target: "money", "[Bob] ============================");
+    info!(target: "money", "[Bob] Executing Bob2Bob payment tx");
+    info!(target: "money", "[Bob] ============================");
     th.bob_state.read().await.verify_transactions(&[bob2bob_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(bob2bob_params.outputs[0].coin));
     let bob_leaf_pos = th.bob_merkle_tree.witness().unwrap();
@@ -703,7 +703,7 @@ async fn money_contract_transfer() -> Result<()> {
     assert!(bob_owncoins[0].note.token_id == bob_token_id);
 
     // Now they decide to swap all of their tokens
-    info!("[Alice] Building OtcSwap half");
+    info!(target: "money", "[Alice] Building OtcSwap half");
     let (
         alice_swap_params,
         alice_swap_proofs,
@@ -733,7 +733,7 @@ async fn money_contract_transfer() -> Result<()> {
     alice_owncoins.retain(|x| x != &alice_swap_spent_coins[0]);
     assert!(alice_owncoins.is_empty());
 
-    info!("[Bob] Building OtcSwap half");
+    info!(target: "money", "[Bob] Building OtcSwap half");
     let (
         bob_swap_params,
         bob_swap_proofs,
@@ -791,24 +791,24 @@ async fn money_contract_transfer() -> Result<()> {
     let sigs = alicebob_swap_tx.create_sigs(&mut OsRng, &alice_swap_secret_keys)?;
     alicebob_swap_tx.signatures[0].insert(0, sigs[0]);
 
-    info!("[Faucet] ==========================");
-    info!("[Faucet] Executing AliceBob swap tx");
-    info!("[Faucet] ==========================");
+    info!(target: "money", "[Faucet] ==========================");
+    info!(target: "money", "[Faucet] Executing AliceBob swap tx");
+    info!(target: "money", "[Faucet] ==========================");
     th.faucet_state.read().await.verify_transactions(&[alicebob_swap_tx.clone()], true).await?;
     th.faucet_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[0].coin));
     th.faucet_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[1].coin));
 
-    info!("[Alice] ==========================");
-    info!("[Alice] Executing AliceBob swap tx");
-    info!("[Alice] ==========================");
+    info!(target: "money", "[Alice] ==========================");
+    info!(target: "money", "[Alice] Executing AliceBob swap tx");
+    info!(target: "money", "[Alice] ==========================");
     th.alice_state.read().await.verify_transactions(&[alicebob_swap_tx.clone()], true).await?;
     th.alice_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[0].coin));
     let alice_leaf_pos = th.alice_merkle_tree.witness().unwrap();
     th.alice_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[1].coin));
 
-    info!("[Bob] ==========================");
-    info!("[Bob] Executing AliceBob swap tx");
-    info!("[Bob] ==========================");
+    info!(target: "money", "[Bob] ==========================");
+    info!(target: "money", "[Bob] Executing AliceBob swap tx");
+    info!(target: "money", "[Bob] ==========================");
     th.bob_state.read().await.verify_transactions(&[alicebob_swap_tx.clone()], true).await?;
     th.bob_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[0].coin));
     th.bob_merkle_tree.append(&MerkleNode::from(swap_full_params.outputs[1].coin));

+ 3 - 3
src/contract/money/tests/harness.rs

@@ -61,7 +61,7 @@ pub fn init_logger() -> Result<()> {
         simplelog::TerminalMode::Mixed,
         simplelog::ColorChoice::Auto,
     ) {
-        warn!("Logger already initialized");
+        warn!(target: "dao", "Logger already initialized");
     }
 
     Ok(())
@@ -166,7 +166,7 @@ impl MoneyTestHarness {
 
         let mint_zkbin = db_handle.get(&serialize(&MONEY_CONTRACT_ZKAS_MINT_NS_V1))?.unwrap();
         let burn_zkbin = db_handle.get(&serialize(&MONEY_CONTRACT_ZKAS_BURN_NS_V1))?.unwrap();
-        info!("Decoding bincode");
+        info!(target: "dao", "Decoding bincode");
         let mint_zkbin = ZkBinary::decode(&mint_zkbin)?;
         let burn_zkbin = ZkBinary::decode(&burn_zkbin)?;
         let mint_witnesses = empty_witnesses(&mint_zkbin);
@@ -174,7 +174,7 @@ impl MoneyTestHarness {
         let mint_circuit = ZkCircuit::new(mint_witnesses, mint_zkbin.clone());
         let burn_circuit = ZkCircuit::new(burn_witnesses, burn_zkbin.clone());
 
-        info!("Creating zk proving keys");
+        info!(target: "dao", "Creating zk proving keys");
         let k = 13;
         let mut proving_keys = HashMap::<[u8; 32], Vec<(&str, ProvingKey)>>::new();
         let mint_pk = ProvingKey::build(k, &mint_circuit);

+ 11 - 11
src/contract/money/tests/verification_bench.rs

@@ -84,15 +84,15 @@ async fn alice2alice_random_amounts() -> Result<()> {
     });
 
     for i in 0..n {
-        info!("Building Alice2Alice transfer tx {}", i);
+        info!(target: "money", "Building Alice2Alice transfer tx {}", i);
 
-        info!("Alice coins: {}", owncoins.len());
+        info!(target: "money", "Alice coins: {}", owncoins.len());
         for (i, c) in owncoins.iter().enumerate() {
-            info!("\t coin {} value: {}", i, c.note.value);
+            info!(target: "money", "\t coin {} value: {}", i, c.note.value);
         }
 
         let amount = rand::thread_rng().gen_range(1..ALICE_AIRDROP);
-        info!("Sending: {}", amount);
+        info!(target: "money", "Sending: {}", amount);
 
         let (params, proofs, secret_keys, spent_coins) = build_transfer_tx(
             &th.alice_kp,
@@ -181,7 +181,7 @@ async fn alice2alice_random_amounts_multiplecoins() -> Result<()> {
         let token_id = TokenId::from(pallas::Base::random(&mut OsRng));
         let amount = rand::thread_rng().gen_range(1..1000);
 
-        info!("Generating token {}: ID {} - amount {}", i, token_id, amount);
+        info!(target: "money", "Generating token {}: ID {} - amount {}", i, token_id, amount);
 
         let (airdrop_tx, airdrop_params) = th.airdrop(amount, token_id, &th.alice_kp.public)?;
 
@@ -210,28 +210,28 @@ async fn alice2alice_random_amounts_multiplecoins() -> Result<()> {
 
     // Simulating N blocks
     for b in 0..n {
-        info!("Generating transactions for block: {}", b);
+        info!(target: "money", "Generating transactions for block: {}", b);
         // Get a random sized sample of owncoins
         let sample =
             (0..10).choose_multiple(&mut rand::thread_rng(), rand::thread_rng().gen_range(1..10));
-        info!("Coins to use: {:?}", sample);
+        info!(target: "money", "Coins to use: {:?}", sample);
 
         // Generate a transaction for each coin
         let mut txs = vec![];
         for index in sample {
-            info!("Building Alice2Alice transfer tx for coin {}", index);
+            info!(target: "money", "Building Alice2Alice transfer tx for coin {}", index);
 
             let mut coins = owncoins[index].clone();
             let token_id = token_ids[index];
             let airdrop_amount = airdrops_amounts[index];
 
-            info!("Alice coins: {}", coins.len());
+            info!(target: "money", "Alice coins: {}", coins.len());
             for (i, c) in coins.iter().enumerate() {
-                info!("\t coin {} value: {}", i, c.note.value);
+                info!(target: "money", "\t coin {} value: {}", i, c.note.value);
             }
 
             let amount = rand::thread_rng().gen_range(1..airdrop_amount);
-            info!("Sending: {}", amount);
+            info!(target: "money", "Sending: {}", amount);
 
             let (params, proofs, secret_keys, spent_coins) = build_transfer_tx(
                 &th.alice_kp,

+ 12 - 12
src/dht/mod.rs

@@ -125,13 +125,13 @@ impl Dht {
         self.map.insert(key, value);
 
         if let Err(e) = self.lookup_insert(key, self.id) {
-            error!("Failed to insert record to lookup map: {}", e);
+            error!(target: "dht", "Failed to insert record to lookup map: {}", e);
             return Err(e)
         };
 
         let request = LookupRequest::new(self.id, key, 0);
         if let Err(e) = self.p2p.broadcast(request).await {
-            error!("Failed broadcasting request: {}", e);
+            error!(target: "dht", "Failed broadcasting request: {}", e);
             return Err(e)
         }
 
@@ -143,10 +143,10 @@ impl Dht {
         // Check if key value pair existed and act accordingly
         match self.map.remove(&key) {
             Some(_) => {
-                debug!("Key removed: {}", key);
+                debug!(target: "dht", "Key removed: {}", key);
                 let request = LookupRequest::new(self.id, key, 1);
                 if let Err(e) = self.p2p.broadcast(request).await {
-                    error!("Failed broadcasting request: {}", e);
+                    error!(target: "dht", "Failed broadcasting request: {}", e);
                     return Err(e)
                 }
 
@@ -213,7 +213,7 @@ impl Dht {
             None => return Err(UnknownKey),
         };
 
-        debug!("Key is in peers: {:?}", peers);
+        debug!(target: "dht", "Key is in peers: {:?}", peers);
 
         // We retrieve p2p network connected channels, to verify if we
         // are connected to a network.
@@ -229,7 +229,7 @@ impl Dht {
         let request = KeyRequest::new(self.id, peer, key);
         // TODO: ask connected peers directly, not broadcast
         if let Err(e) = self.p2p.broadcast(request).await {
-            error!("Failed broadcasting request: {}", e);
+            error!(target: "dht", "Failed broadcasting request: {}", e);
             return Err(e)
         }
 
@@ -238,7 +238,7 @@ impl Dht {
 
     /// Auxilary function to sync lookup map with network
     pub async fn sync_lookup_map(&mut self) -> Result<()> {
-        debug!("Starting lookup map sync...");
+        debug!(target: "dht", "Starting lookup map sync...");
         let channels_map = self.p2p.channels().lock().await.clone();
         let values = channels_map.values();
         // Using len here because is_empty() uses unstable library feature
@@ -258,12 +258,12 @@ impl Dht {
                 // Node stores response data.
                 let resp = response_sub.receive().await?;
                 if resp.lookup.is_empty() {
-                    warn!("Retrieved empty lookup map from an unsynced node, retrying...");
+                    warn!(target: "dht", "Retrieved empty lookup map from an unsynced node, retrying...");
                     continue
                 }
 
                 // Store retrieved records
-                debug!("Processing received records");
+                debug!(target: "dht", "Processing received records");
                 for (k, v) in &resp.lookup {
                     for node in v {
                         self.lookup_insert(*k, *node)?;
@@ -273,10 +273,10 @@ impl Dht {
                 break
             }
         } else {
-            warn!("Node is not connected to other nodes");
+            warn!(target: "dht", "Node is not connected to other nodes");
         }
 
-        debug!("Lookup map synced!");
+        debug!(target: "dht", "Lookup map synced!");
         Ok(())
     }
 }
@@ -315,7 +315,7 @@ pub async fn waiting_for_response(dht: DhtPtr) -> Result<Option<KeyResponse>> {
 async fn prune_seen_messages(dht: DhtPtr) {
     loop {
         sleep(SEEN_DURATION as u64).await;
-        debug!("Pruning seen messages");
+        debug!(target: "dht", "Pruning seen messages");
 
         let now = Utc::now().timestamp();
 

+ 28 - 24
src/dht/protocol.rs

@@ -54,7 +54,7 @@ impl Protocol {
         dht: DhtPtr,
         p2p: P2pPtr,
     ) -> Result<ProtocolBasePtr> {
-        debug!("Adding Protocol to the protocol registry");
+        debug!(target: "dht::protocol", "Adding Protocol to the protocol registry");
         let msg_subsystem = channel.get_message_subsystem();
         msg_subsystem.add_dispatch::<KeyRequest>().await;
         msg_subsystem.add_dispatch::<KeyResponse>().await;
@@ -80,24 +80,25 @@ impl Protocol {
     }
 
     async fn handle_receive_request(self: Arc<Self>) -> Result<()> {
-        debug!("Protocol::handle_receive_request() [START]");
+        debug!(target: "dht::protocol", "Protocol::handle_receive_request() [START]");
         let exclude_list = vec![self.channel.address()];
         loop {
             let req = match self.req_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    error!("Protocol::handle_receive_request(): recv fail: {}", e);
+                    error!(target: "dht::protocol", "Protocol::handle_receive_request(): recv fail: {}", e);
                     continue
                 }
             };
 
             let req_copy = (*req).clone();
-            debug!("Protocol::handle_receive_request(): req: {:?}", req_copy);
+            debug!(target: "dht::protocol", "Protocol::handle_receive_request(): req: {:?}", req_copy);
 
             {
                 let dht = &mut self.dht.write().await;
                 if dht.seen.contains_key(&req_copy.id) {
                     debug!(
+                        target: "dht::protocol",
                         "Protocol::handle_receive_request(): We have already seen this request."
                     );
                     continue
@@ -111,7 +112,7 @@ impl Protocol {
                 if let Err(e) =
                     self.p2p.broadcast_with_exclude(req_copy.clone(), &exclude_list).await
                 {
-                    error!("Protocol::handle_receive_response(): p2p broadcast fail: {}", e);
+                    error!(target: "dht::protocol", "Protocol::handle_receive_response(): p2p broadcast fail: {}", e);
                 };
                 continue
             }
@@ -120,37 +121,38 @@ impl Protocol {
                 Some(value) => {
                     let response =
                         KeyResponse::new(daemon, req_copy.from, req_copy.key, value.clone());
-                    debug!("Protocol::handle_receive_request(): sending response: {:?}", response);
+                    debug!(target: "dht::protocol", "Protocol::handle_receive_request(): sending response: {:?}", response);
                     if let Err(e) = self.channel.send(response).await {
-                        error!("Protocol::handle_receive_request(): p2p broadcast of response failed: {}", e);
+                        error!(target: "dht::protocol", "Protocol::handle_receive_request(): p2p broadcast of response failed: {}", e);
                     };
                 }
                 None => {
-                    error!("Protocol::handle_receive_request(): Requested key doesn't exist locally: {}", req_copy.key);
+                    error!(target: "dht::protocol", "Protocol::handle_receive_request(): Requested key doesn't exist locally: {}", req_copy.key);
                 }
             }
         }
     }
 
     async fn handle_receive_response(self: Arc<Self>) -> Result<()> {
-        debug!("Protocol::handle_receive_response() [START]");
+        debug!(target: "dht::protocol", "Protocol::handle_receive_response() [START]");
         let exclude_list = vec![self.channel.address()];
         loop {
             let resp = match self.resp_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    error!("Protocol::handle_receive_response(): recv fail: {}", e);
+                    error!(target: "dht::protocol", "Protocol::handle_receive_response(): recv fail: {}", e);
                     continue
                 }
             };
 
             let resp_copy = (*resp).clone();
-            debug!("Protocol::handle_receive_response(): resp: {:?}", resp_copy);
+            debug!(target: "dht::protocol", "Protocol::handle_receive_response(): resp: {:?}", resp_copy);
 
             {
                 let dht = &mut self.dht.write().await;
                 if dht.seen.contains_key(&resp_copy.id) {
                     debug!(
+                        target: "dht::protocol",
                         "Protocol::handle_receive_request(): We have already seen this request."
                     );
                     continue
@@ -163,7 +165,7 @@ impl Protocol {
                 if let Err(e) =
                     self.p2p.broadcast_with_exclude(resp_copy.clone(), &exclude_list).await
                 {
-                    error!("Protocol::handle_receive_response(): p2p broadcast fail: {}", e);
+                    error!(target: "dht::protocol", "Protocol::handle_receive_response(): p2p broadcast fail: {}", e);
                 };
                 continue
             }
@@ -173,22 +175,22 @@ impl Protocol {
     }
 
     async fn handle_receive_lookup_request(self: Arc<Self>) -> Result<()> {
-        debug!("Protocol::handle_receive_lookup_request() [START]");
+        debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request() [START]");
         let exclude_list = vec![self.channel.address()];
         loop {
             let req = match self.lookup_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    error!("Protocol::handle_receive_lookup_request(): recv fail: {}", e);
+                    error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): recv fail: {}", e);
                     continue
                 }
             };
 
             let req_copy = (*req).clone();
-            debug!("Protocol::handle_receive_lookup_request(): req: {:?}", req_copy);
+            debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): req: {:?}", req_copy);
 
             if !(0..=1).contains(&req_copy.req_type) {
-                debug!("Protocol::handle_receive_lookup_request(): Unknown request type.");
+                debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): Unknown request type.");
                 continue
             }
 
@@ -196,6 +198,7 @@ impl Protocol {
                 let dht = &mut self.dht.write().await;
                 if dht.seen.contains_key(&req_copy.id) {
                     debug!(
+                        target: "dht::protocol",
                         "Protocol::handle_receive_request(): We have already seen this request."
                     );
                     continue
@@ -210,33 +213,34 @@ impl Protocol {
             };
 
             if let Err(e) = result {
-                error!("Protocol::handle_receive_lookup_request(): request action failed: {}", e);
+                error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): request action failed: {}", e);
                 continue
             };
 
             if let Err(e) = self.p2p.broadcast_with_exclude(req_copy, &exclude_list).await {
-                error!("Protocol::handle_receive_lookup_request(): p2p broadcast fail: {}", e);
+                error!(target: "dht::protocol", "Protocol::handle_receive_lookup_request(): p2p broadcast fail: {}", e);
             };
         }
     }
 
     async fn handle_receive_lookup_map_request(self: Arc<Self>) -> Result<()> {
-        debug!("Protocol::handle_receive_lookup_map_request() [START]");
+        debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request() [START]");
         loop {
             let req = match self.lookup_map_sub.receive().await {
                 Ok(v) => v,
                 Err(e) => {
-                    error!("Protocol::handle_receive_lookup_map_request(): recv fail: {}", e);
+                    error!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request(): recv fail: {}", e);
                     continue
                 }
             };
 
-            debug!("Protocol::handle_receive_lookup_map_request(): req: {:?}", req);
+            debug!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request(): req: {:?}", req);
 
             {
                 let dht = &mut self.dht.write().await;
                 if dht.seen.contains_key(&req.id) {
                     debug!(
+                        target: "dht::protocol",
                         "Protocol::handle_receive_lookup_map_request(): We have already seen this request."
                     );
                     continue
@@ -249,7 +253,7 @@ impl Protocol {
             let lookup = self.dht.read().await.lookup.clone();
             let response = LookupMapResponse::new(lookup);
             if let Err(e) = self.channel.send(response).await {
-                error!("Protocol::handle_receive_lookup_map_request() channel send fail: {}", e);
+                error!(target: "dht::protocol", "Protocol::handle_receive_lookup_map_request() channel send fail: {}", e);
             };
         }
     }
@@ -258,7 +262,7 @@ impl Protocol {
 #[async_trait]
 impl ProtocolBase for Protocol {
     async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!("Protocol::start() [START]");
+        debug!(target: "dht::protocol", "Protocol::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().handle_receive_request(), executor.clone()).await;
         self.jobsman.clone().spawn(self.clone().handle_receive_response(), executor.clone()).await;
@@ -270,7 +274,7 @@ impl ProtocolBase for Protocol {
             .clone()
             .spawn(self.clone().handle_receive_lookup_map_request(), executor.clone())
             .await;
-        debug!("Protocol::start() [END]");
+        debug!(target: "dht::protocol", "Protocol::start() [END]");
         Ok(())
     }
 

+ 4 - 4
src/net/acceptor.rs

@@ -64,14 +64,14 @@ impl Acceptor {
         macro_rules! accept {
             ($listener:expr, $transport:expr, $upgrade:expr) => {{
                 if let Err(err) = $listener {
-                    error!("Setup for {} failed: {}", accept_url, err);
+                    error!(target: "net::acceptor", "Setup for {} failed: {}", accept_url, err);
                     return Err(Error::BindFailed(accept_url.as_str().into()))
                 }
 
                 let listener = $listener?.await;
 
                 if let Err(err) = listener {
-                    error!("Bind listener to {} failed: {}", accept_url, err);
+                    error!(target: "net::acceptor", "Bind listener to {} failed: {}", accept_url, err);
                     return Err(Error::BindFailed(accept_url.as_str().into()))
                 }
 
@@ -126,7 +126,7 @@ impl Acceptor {
                 // generate EHS pointing to local address
                 let hurl = transport.create_ehs(accept_url.clone())?;
 
-                info!("EHS TOR: {}", hurl.to_string());
+                info!(target: "net::acceptor", "EHS TOR: {}", hurl.to_string());
 
                 let listener = transport.clone().listen_on(accept_url.clone());
 
@@ -170,7 +170,7 @@ impl Acceptor {
                     self.channel_subscriber.notify(Ok(channel)).await;
                 }
                 Err(e) => {
-                    error!("Error listening for new connection: {}", e);
+                    error!(target: "net::acceptor", "Error listening for new connection: {}", e);
                 }
             }
         }

+ 17 - 17
src/net/channel.rs

@@ -141,7 +141,7 @@ impl Channel {
     /// Starts the channel. Runs a receive loop to start receiving messages or
     /// handles a network failure.
     pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
-        debug!(target: "net", "Channel::start() [START, address={}]", self.address());
+        debug!(target: "net::channel", "Channel::start() [START, address={}]", self.address());
         let self2 = self.clone();
         self.receive_task.clone().start(
             self.clone().main_receive_loop(),
@@ -149,28 +149,28 @@ impl Channel {
             Error::NetworkServiceStopped,
             executor,
         );
-        debug!(target: "net", "Channel::start() [END, address={}]", self.address());
+        debug!(target: "net::channel", "Channel::start() [END, address={}]", self.address());
     }
 
     /// Stops the channel. Steps through each component of the channel
     /// connection and sends a stop signal. Notifies all subscribers that
     /// the channel has been closed.
     pub async fn stop(&self) {
-        debug!(target: "net", "Channel::stop() [START, address={}]", self.address());
+        debug!(target: "net::channel", "Channel::stop() [START, address={}]", self.address());
         if !(*self.stopped.lock().await) {
             *self.stopped.lock().await = true;
 
             self.stop_subscriber.notify(Error::ChannelStopped).await;
             self.receive_task.stop().await;
             self.message_subsystem.trigger_error(Error::ChannelStopped).await;
-            debug!(target: "net", "Channel::stop() [END, address={}]", self.address());
+            debug!(target: "net::channel", "Channel::stop() [END, address={}]", self.address());
         }
     }
 
     /// Creates a subscription to a stopped signal.
     /// If the channel is stopped then this will return a ChannelStopped error.
     pub async fn subscribe_stop(&self) -> Result<Subscription<Error>> {
-        debug!(target: "net",
+        debug!(target: "net::channel",
          "Channel::subscribe_stop() [START, address={}]",
          self.address()
         );
@@ -183,7 +183,7 @@ impl Channel {
         }
 
         let sub = self.stop_subscriber.clone().subscribe().await;
-        debug!(target: "net",
+        debug!(target: "net::channel",
          "Channel::subscribe_stop() [END, address={}]",
          self.address()
         );
@@ -195,7 +195,7 @@ impl Channel {
     /// creates a new payload and sends it over the TCP connection as a
     /// packet. Returns an error if something goes wrong.
     pub async fn send<M: message::Message>(&self, message: M) -> Result<()> {
-        debug!(target: "net",
+        debug!(target: "net::channel",
          "Channel::send() [START, command={:?}, address={}]",
          M::name(),
          self.address()
@@ -212,13 +212,13 @@ impl Channel {
         let result = match self.send_message(message).await {
             Ok(()) => Ok(()),
             Err(err) => {
-                error!("Channel send error for [{}]: {}", self.address(), err);
+                error!(target: "net::channel", "Channel send error for [{}]: {}", self.address(), err);
                 self.stop().await;
                 Err(Error::ChannelStopped)
             }
         };
 
-        debug!(target: "net",
+        debug!(target: "net::channel",
          "Channel::send() [END, command={:?}, address={}]",
          M::name(),
          self.address()
@@ -256,13 +256,13 @@ impl Channel {
 
     /// Subscribe to a messages on the message subsystem.
     pub async fn subscribe_msg<M: message::Message>(&self) -> Result<MessageSubscription<M>> {
-        debug!(target: "net",
+        debug!(target: "net::channel",
          "Channel::subscribe_msg() [START, command={:?}, address={}]",
          M::name(),
          self.address()
         );
         let sub = self.message_subsystem.subscribe::<M>().await;
-        debug!(target: "net",
+        debug!(target: "net::channel",
          "Channel::subscribe_msg() [END, command={:?}, address={}]",
          M::name(),
          self.address()
@@ -309,7 +309,7 @@ impl Channel {
     /// Run the receive loop. Start receiving messages or handle network
     /// failure.
     async fn main_receive_loop(self: Arc<Self>) -> Result<()> {
-        debug!(target: "net",
+        debug!(target: "net::channel",
          "Channel::receive_loop() [START, address={}]",
          self.address()
         );
@@ -321,11 +321,11 @@ impl Channel {
                 Ok(packet) => packet,
                 Err(err) => {
                     if Self::is_eof_error(err.clone()) {
-                        info!("Inbound connection {} disconnected", self.address());
+                        info!(target: "net::channel", "Inbound connection {} disconnected", self.address());
                     } else {
-                        error!("Read error on channel {}: {}", self.address(), err);
+                        error!(target: "net::channel", "Read error on channel {}: {}", self.address(), err);
                     }
-                    debug!(target: "net",
+                    debug!(target: "net::channel",
                      "Channel::receive_loop() stopping channel {}",
                      self.address()
                     );
@@ -352,7 +352,7 @@ impl Channel {
     /// Handle network errors. Panic if error passes silently, otherwise
     /// broadcast the error.
     async fn handle_stop(self: Arc<Self>, result: Result<()>) {
-        debug!(target: "net", "Channel::handle_stop() [START, address={}]", self.address());
+        debug!(target: "net::channel", "Channel::handle_stop() [START, address={}]", self.address());
         match result {
             Ok(()) => panic!("Channel task should never complete without error status"),
             Err(err) => {
@@ -360,7 +360,7 @@ impl Channel {
                 self.message_subsystem.trigger_error(err).await;
             }
         }
-        debug!(target: "net", "Channel::handle_stop() [END, address={}]", self.address());
+        debug!(target: "net::channel", "Channel::handle_stop() [END, address={}]", self.address());
     }
 
     fn session(&self) -> Arc<dyn Session> {

+ 2 - 2
src/net/connector.rs

@@ -60,14 +60,14 @@ impl Connector {
         macro_rules! connect {
             ($stream:expr, $transport:expr, $upgrade:expr) => {{
                 if let Err(err) = $stream {
-                    error!("Setup for {} failed: {}", connect_url, err);
+                    error!(target: "net::connector", "Setup for {} failed: {}", connect_url, err);
                     return Err(Error::ConnectFailed)
                 }
 
                 let stream = $stream?.await;
 
                 if let Err(err) = stream {
-                    error!("Connection to {}  failed: {}", connect_url, err);
+                    error!(target: "net::connector", "Connection to {}  failed: {}", connect_url, err);
                     return Err(Error::ConnectFailed)
                 }
 

+ 25 - 25
src/net/hosts.rs

@@ -65,33 +65,33 @@ impl Hosts {
             let filtered = filter_invalid(&self.ipv4_range, &self.ipv6_range, filtered);
             filtered.into_iter().map(|(k, _)| k).collect()
         } else {
-            debug!(target: "net", "hosts::store() [Localnet mode, skipping filterring.]");
+            debug!(target: "net::hosts::store()", "hosts::store() [Localnet mode, skipping filterring.]");
             input_addrs
         };
         let mut addrs_map = self.addrs.lock().await;
         for addr in addrs {
             addrs_map.insert(addr);
         }
-        debug!(target: "net", "hosts::store() [End]");
+        debug!(target: "net::hosts::store()", "hosts::store() [End]");
     }
 
     /// Add a new hosts external adders to the host list, after filtering and verifying
     /// the address url resolves to the provided connection address.
     pub async fn store_ext(&self, connection_addr: Url, input_addrs: Vec<Url>) {
-        debug!(target: "net", "hosts::store_ext() [Start]");
+        debug!(target: "net::hosts::store()", "hosts::store_ext() [Start]");
         let addrs = if !self.localnet {
             let filtered = filter_localnet(input_addrs);
             let filtered = filter_invalid(&self.ipv4_range, &self.ipv6_range, filtered);
             filter_non_resolving(connection_addr, filtered)
         } else {
-            debug!(target: "net", "hosts::store_ext() [Localnet mode, skipping filterring.]");
+            debug!(target: "net::hosts::store()", "hosts::store_ext() [Localnet mode, skipping filterring.]");
             input_addrs
         };
         let mut addrs_map = self.addrs.lock().await;
         for addr in addrs {
             addrs_map.insert(addr);
         }
-        debug!(target: "net", "hosts::store_ext() [End]");
+        debug!(target: "net::hosts::store()", "hosts::store_ext() [End]");
     }
 
     /// Return the list of hosts.
@@ -112,7 +112,7 @@ impl Hosts {
 
 /// Auxiliary function to filter localnet hosts.
 fn filter_localnet(input_addrs: Vec<Url>) -> Vec<Url> {
-    debug!(target: "net", "hosts::filter_localnet() [Input addresses: {:?}]", input_addrs);
+    debug!(target: "net::hosts::store()", "hosts::filter_localnet() [Input addresses: {:?}]", input_addrs);
     let mut filtered = vec![];
 
     for addr in &input_addrs {
@@ -121,13 +121,13 @@ fn filter_localnet(input_addrs: Vec<Url>) -> Vec<Url> {
                 filtered.push(addr.clone());
                 continue
             }
-            debug!(target: "net", "hosts::filter_localnet() [Filtered localnet addr: {}]", addr);
+            debug!(target: "net::hosts::store()", "hosts::filter_localnet() [Filtered localnet addr: {}]", addr);
             continue
         }
-        warn!(target: "net", "hosts::filter_localnet() [{} addr.host_str is empty, skipping.]", addr);
+        warn!(target: "net::hosts::store()", "hosts::filter_localnet() [{} addr.host_str is empty, skipping.]", addr);
     }
 
-    debug!(target: "net", "hosts::filter_localnet() [Filtered addresses: {:?}]", filtered);
+    debug!(target: "net::hosts::store()", "hosts::filter_localnet() [Filtered addresses: {:?}]", filtered);
     filtered
 }
 
@@ -137,14 +137,14 @@ fn filter_invalid(
     ipv6_range: &IpRange<Ipv6Net>,
     input_addrs: Vec<Url>,
 ) -> HashMap<Url, Vec<IpAddr>> {
-    debug!(target: "net", "hosts::filter_invalid() [Input addresses: {:?}]", input_addrs);
+    debug!(target: "net::hosts::store()", "hosts::filter_invalid() [Input addresses: {:?}]", input_addrs);
     let mut filtered = HashMap::new();
     for addr in &input_addrs {
         // Discard domainless Urls
         let domain = match addr.domain() {
             Some(d) => d,
             None => {
-                debug!(target: "net", "hosts::filter_invalid() [Filtered domainless url: {}]", addr);
+                debug!(target: "net::hosts::store()", "hosts::filter_invalid() [Filtered domainless url: {}]", addr);
                 continue
             }
         };
@@ -156,7 +156,7 @@ fn filter_invalid(
                     filtered.insert(addr.clone(), vec![]);
                 }
                 false => {
-                    warn!(target: "net", "hosts::filter_invalid() [Got invalid onion address: {}]", addr)
+                    warn!(target: "net::hosts::store()", "hosts::filter_invalid() [Got invalid onion address: {}]", addr)
                 }
             }
             continue
@@ -169,7 +169,7 @@ fn filter_invalid(
         if let Ok(socket_addrs) = addr.socket_addrs(|| None) {
             // Check if domain resolved to anything
             if socket_addrs.is_empty() {
-                debug!(target: "net", "hosts::filter_invalid() [Filtered unresolvable URL: {}]", addr);
+                debug!(target: "net::hosts::store()", "hosts::filter_invalid() [Filtered unresolvable URL: {}]", addr);
                 continue
             }
 
@@ -180,13 +180,13 @@ fn filter_invalid(
                 match ip {
                     IpAddr::V4(a) => {
                         if ipv4_range.contains(&a) {
-                            debug!(target: "net", "hosts::filter_invalid() [Filtered private-range IPv4: {}]", a);
+                            debug!(target: "net::hosts::store()", "hosts::filter_invalid() [Filtered private-range IPv4: {}]", a);
                             continue
                         }
                     }
                     IpAddr::V6(a) => {
                         if ipv6_range.contains(&a) {
-                            debug!(target: "net", "hosts::filter_invalid() [Filtered private range IPv6: {}]", a);
+                            debug!(target: "net::hosts::store()", "hosts::filter_invalid() [Filtered private range IPv6: {}]", a);
                             continue
                         }
                     }
@@ -195,18 +195,18 @@ fn filter_invalid(
             }
 
             if resolves.is_empty() {
-                debug!(target: "net", "hosts::filter_invalid() [Filtered unresolvable URL: {}]", addr);
+                debug!(target: "net::hosts::store()", "hosts::filter_invalid() [Filtered unresolvable URL: {}]", addr);
                 continue
             }
 
             filtered.insert(addr.clone(), resolves);
         } else {
-            warn!(target: "net", "hosts::filter_invalid() [Failed resolving socket_addrs for {}]", addr);
+            warn!(target: "net::hosts::store()", "hosts::filter_invalid() [Failed resolving socket_addrs for {}]", addr);
             continue
         }
     }
 
-    debug!(target: "net", "hosts::filter_invalid() [Filtered addresses: {:?}]", filtered);
+    debug!(target: "net::hosts::store()", "hosts::filter_invalid() [Filtered addresses: {:?}]", filtered);
     filtered
 }
 
@@ -214,8 +214,8 @@ fn filter_invalid(
 /// the same as `connection_addr`'s IP address.
 /// Skips .onion domains.
 fn filter_non_resolving(connection_addr: Url, input_addrs: HashMap<Url, Vec<IpAddr>>) -> Vec<Url> {
-    debug!(target: "net", "hosts::filter_non_resolving() [Input addresses: {:?}]", input_addrs);
-    debug!(target: "net", "hosts::filter_non_resolving() [Connection address: {}]", connection_addr);
+    debug!(target: "net::hosts::store()", "hosts::filter_non_resolving() [Input addresses: {:?}]", input_addrs);
+    debug!(target: "net::hosts::store()", "hosts::filter_non_resolving() [Connection address: {}]", connection_addr);
 
     // Retrieve connection IPs
     let mut ipv4_range = vec![];
@@ -231,13 +231,13 @@ fn filter_non_resolving(connection_addr: Url, input_addrs: HashMap<Url, Vec<IpAd
             }
         }
         Err(e) => {
-            error!(target: "net", "hosts::filter_non_resolving() [Failed resolving connection_addr {}: {}]", connection_addr, e);
+            error!(target: "net::hosts::store()", "hosts::filter_non_resolving() [Failed resolving connection_addr {}: {}]", connection_addr, e);
             return vec![]
         }
     };
 
-    debug!(target: "net", "hosts::filter_non_resolving() [{} IPv4: {:?}]", connection_addr, ipv4_range);
-    debug!(target: "net", "hosts::filter_non_resolving() [{} IPv6: {:?}]", connection_addr, ipv6_range);
+    debug!(target: "net::hosts::store()", "hosts::filter_non_resolving() [{} IPv4: {:?}]", connection_addr, ipv4_range);
+    debug!(target: "net::hosts::store()", "hosts::filter_non_resolving() [{} IPv6: {:?}]", connection_addr, ipv6_range);
 
     let mut filtered = vec![];
     for (addr, resolves) in &input_addrs {
@@ -269,14 +269,14 @@ fn filter_non_resolving(connection_addr: Url, input_addrs: HashMap<Url, Vec<IpAd
         }
 
         if !valid {
-            debug!(target: "net", "hosts::filter_non_resolving() [Filtered unresolvable url: {}]", addr);
+            debug!(target: "net::hosts::store()", "hosts::filter_non_resolving() [Filtered unresolvable url: {}]", addr);
             continue
         }
 
         filtered.push(addr.clone());
     }
 
-    debug!(target: "net", "hosts::filter_non_resolving() [Filtered addresses: {:?}]", filtered);
+    debug!(target: "net::hosts::store()", "hosts::filter_non_resolving() [Filtered addresses: {:?}]", filtered);
     filtered
 }
 

+ 8 - 8
src/net/message.rs

@@ -126,11 +126,11 @@ pub async fn read_packet<R: AsyncRead + Unpin + Sized>(stream: &mut R) -> Result
     // Packets have a 4 byte header of magic digits
     // This is used for network debugging
     let mut magic = [0u8; 4];
-    debug!(target: "net", "reading magic...");
+    debug!(target: "net::message", "reading magic...");
 
     stream.read_exact(&mut magic).await?;
 
-    debug!(target: "net", "read magic {:?}", magic);
+    debug!(target: "net::message", "read magic {:?}", magic);
     if magic != MAGIC_BYTES {
         return Err(Error::MalformedPacket)
     }
@@ -142,7 +142,7 @@ pub async fn read_packet<R: AsyncRead + Unpin + Sized>(stream: &mut R) -> Result
         stream.read_exact(&mut cmd).await?;
     }
     let cmd = String::from_utf8(cmd)?;
-    debug!(target: "net", "read command: {}", cmd);
+    debug!(target: "net::message", "read command: {}", cmd);
 
     let payload_len = VarInt::decode_async(stream).await?.0 as usize;
 
@@ -151,7 +151,7 @@ pub async fn read_packet<R: AsyncRead + Unpin + Sized>(stream: &mut R) -> Result
     if payload_len > 0 {
         stream.read_exact(&mut payload).await?;
     }
-    debug!(target: "net", "read payload {} bytes", payload_len);
+    debug!(target: "net::message", "read payload {} bytes", payload_len);
 
     Ok(Packet { command: cmd, payload })
 }
@@ -161,14 +161,14 @@ pub async fn send_packet<W: AsyncWrite + Unpin + Sized>(
     stream: &mut W,
     packet: Packet,
 ) -> Result<()> {
-    debug!(target: "net", "sending magic...");
+    debug!(target: "net::message", "sending magic...");
     stream.write_all(&MAGIC_BYTES).await?;
-    debug!(target: "net", "sent magic...");
+    debug!(target: "net::message", "sent magic...");
 
     VarInt(packet.command.len() as u64).encode_async(stream).await?;
     assert!(!packet.command.is_empty());
     stream.write_all(packet.command.as_bytes()).await?;
-    debug!(target: "net", "sent command: {}", packet.command);
+    debug!(target: "net::message", "sent command: {}", packet.command);
 
     assert_eq!(std::mem::size_of::<usize>(), std::mem::size_of::<u64>());
     VarInt(packet.payload.len() as u64).encode_async(stream).await?;
@@ -176,7 +176,7 @@ pub async fn send_packet<W: AsyncWrite + Unpin + Sized>(
     if !packet.payload.is_empty() {
         stream.write_all(&packet.payload).await?;
     }
-    debug!(target: "net", "sent payload {} bytes", packet.payload.len() as u64);
+    debug!(target: "net::message", "sent payload {} bytes", packet.payload.len() as u64);
 
     Ok(())
 }

+ 4 - 4
src/net/message_subscriber.rs

@@ -103,7 +103,7 @@ impl<M: Message> MessageDispatcher<M> {
     /// channels. Used strictly internally.
     async fn _trigger_all(&self, message: MessageResult<M>) {
         debug!(
-            target: "net",
+            target: "net::message_subscriber",
             "MessageDispatcher<M={}>::trigger_all({}) [START, subs={}]",
             M::name(),
             if message.is_ok() { "msg" } else { "err" },
@@ -126,7 +126,7 @@ impl<M: Message> MessageDispatcher<M> {
         self.collect_garbage(garbage_ids).await;
 
         debug!(
-            target: "net",
+            target: "net::message_subscriber",
             "MessageDispatcher<M={}>::trigger_all({}) [END, subs={}]",
             M::name(),
             if message.is_ok() { "msg" } else { "err" },
@@ -157,7 +157,7 @@ impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
                 self._trigger_all(message).await
             }
             Err(err) => {
-                debug!("Unable to decode data. Dropping...: {}", err);
+                debug!(target: "net::message_subscriber", "Unable to decode data. Dropping...: {}", err);
             }
         }
     }
@@ -225,7 +225,7 @@ impl MessageSubsystem {
             }
             None => {
                 warn!(
-                    target: "MessageSubsystem::notify",
+                    target: "net::message_subscriber",
                     "MessageSubsystem::notify(\"{}\", payload) did not find a dispatcher",
                     command
                 );

+ 13 - 12
src/net/p2p.rs

@@ -167,7 +167,7 @@ impl P2p {
 
         *self.state.lock().await = P2pState::Started;
 
-        debug!(target: "net", "P2p::start() [END]");
+        debug!(target: "net::p2p::start()", "P2p::start() [END]");
         Ok(())
     }
     // ANCHOR_END: start
@@ -186,7 +186,7 @@ impl P2p {
     /// Waits for a stop signal and stops the network if received.
     // ANCHOR: run
     pub async fn run(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "net", "P2p::run() [BEGIN]");
+        debug!(target: "net::p2p::start()", "P2p::run() [BEGIN]");
 
         *self.state.lock().await = P2pState::Run;
 
@@ -210,20 +210,20 @@ impl P2p {
         inbound.stop().await;
         outbound.stop().await;
 
-        debug!(target: "net", "P2p::run() [END]");
+        debug!(target: "net::p2p::start()", "P2p::run() [END]");
         Ok(())
     }
     // ANCHOR_END: run
 
     /// Wait for outbound connections to be established.
     pub async fn wait_for_outbound(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "net", "P2p::wait_for_outbound() [BEGIN]");
+        debug!(target: "net::p2p::start()", "P2p::wait_for_outbound() [BEGIN]");
         // To verify that the network needs initialization, we check if we have seeds or peers configured,
         // and have configured outbound slots.
         if !(self.settings.seeds.is_empty() && self.settings.peers.is_empty()) &&
             self.settings.outbound_connections > 0
         {
-            debug!(target: "net", "P2p::wait_for_outbound(): seeds are configured, waiting for outbound initialization...");
+            debug!(target: "net::p2p::start()", "P2p::wait_for_outbound(): seeds are configured, waiting for outbound initialization...");
             // Retrieve P2P network settings;
             let settings = self.settings();
 
@@ -278,7 +278,7 @@ impl P2p {
             self.session_outbound().await.disable_notify().await;
         }
 
-        debug!(target: "net", "P2p::wait_for_outbound() [END]");
+        debug!(target: "net::p2p::start()", "P2p::wait_for_outbound() [END]");
         Ok(())
     }
 
@@ -313,14 +313,15 @@ impl P2p {
                 msg = subscriber.receive().fuse() => {
                         if let Err(e) = msg {
                             warn!(
+                                target: "net::p2p::start()",
                                 "P2p::wait_for_outbound(): Outbound connection failed [{}]: {}",
                                 addr, e
                             );
                         }
                 },
-                _ = stop_sub.receive().fuse() => debug!("P2p::wait_for_outbound(): stop signal received!"),
+                _ = stop_sub.receive().fuse() => debug!(target: "net::p2p::start()", "P2p::wait_for_outbound(): stop signal received!"),
                 _ = timeout_r.recv().fuse() => {
-                    warn!("P2p::wait_for_outbound(): Timeout on outbound connection: {}", addr);
+                    warn!(target: "net::p2p::start()", "P2p::wait_for_outbound(): Timeout on outbound connection: {}", addr);
                     continue
                 },
             }
@@ -353,13 +354,13 @@ impl P2p {
         }
 
         if futures.is_empty() {
-            error!("P2P::broadcast: No connected channels found");
+            error!(target: "net::p2p::start()", "P2P::broadcast: No connected channels found");
             return Ok(())
         }
 
         while let Some(entry) = futures.next().await {
             if let Err(e) = entry {
-                error!("{}", e);
+                error!(target: "net::p2p::start()", "{}", e);
             }
         }
 
@@ -391,13 +392,13 @@ impl P2p {
         }
 
         if futures.is_empty() {
-            error!("P2P::broadcast_with_exclude: No connected channels found");
+            error!(target: "net::p2p::start()", "P2P::broadcast_with_exclude: No connected channels found");
             return Ok(())
         }
 
         while let Some(entry) = futures.next().await {
             if let Err(e) = entry {
-                error!("{}", e);
+                error!(target: "net::p2p::start()", "{}", e);
             }
         }
 

+ 9 - 9
src/net/protocol/protocol_address.rs

@@ -92,7 +92,7 @@ impl ProtocolAddress {
         debug!(target: "net", "ProtocolAddress::handle_receive_addrs() [START]");
         loop {
             let addrs_msg = self.addrs_sub.receive().await?;
-            debug!(target: "net", "ProtocolAddress::handle_receive_addrs() received {} addrs", addrs_msg.addrs.len());
+            debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::handle_receive_addrs() received {} addrs", addrs_msg.addrs.len());
             self.hosts.store(addrs_msg.addrs.clone()).await;
         }
     }
@@ -101,10 +101,10 @@ impl ProtocolAddress {
     /// external address messages on the address subsciption. Adds the recieved
     /// external addresses to the list of hosts.
     async fn handle_receive_ext_addrs(self: Arc<Self>) -> Result<()> {
-        debug!(target: "net", "ProtocolAddress::handle_receive_ext_addrs() [START]");
+        debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::handle_receive_ext_addrs() [START]");
         loop {
             let ext_addrs_msg = self.ext_addrs_sub.receive().await?;
-            debug!(target: "net", "ProtocolAddress::handle_receive_ext_addrs() received {} addrs", ext_addrs_msg.ext_addrs.len());
+            debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::handle_receive_ext_addrs() received {} addrs", ext_addrs_msg.ext_addrs.len());
             self.hosts.store_ext(self.channel.address(), ext_addrs_msg.ext_addrs.clone()).await;
         }
     }
@@ -113,17 +113,17 @@ impl ProtocolAddress {
     /// get-address messages on the get-address subsciption. Then replies
     /// with an address message.
     async fn handle_receive_get_addrs(self: Arc<Self>) -> Result<()> {
-        debug!(target: "net", "ProtocolAddress::handle_receive_get_addrs() [START]");
+        debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::handle_receive_get_addrs() [START]");
         loop {
             let _get_addrs = self.get_addrs_sub.receive().await?;
 
-            debug!(target: "net", "ProtocolAddress::handle_receive_get_addrs() received GetAddrs message");
+            debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::handle_receive_get_addrs() received GetAddrs message");
 
             // Loads the list of hosts.
             let mut addrs = self.hosts.load_all().await;
             // Shuffling list of hosts
             addrs.shuffle(&mut rand::thread_rng());
-            debug!(target: "net", "ProtocolAddress::handle_receive_get_addrs() sending {} addrs", addrs.len());
+            debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::handle_receive_get_addrs() sending {} addrs", addrs.len());
             // Creates an address messages containing host address.
             let addrs_msg = message::AddrsMessage { addrs };
             // Sends the address message across the channel.
@@ -132,7 +132,7 @@ impl ProtocolAddress {
     }
 
     async fn send_my_addrs(self: Arc<Self>) -> Result<()> {
-        debug!(target: "net", "ProtocolAddress::send_addrs() [START]");
+        debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::send_addrs() [START]");
         loop {
             let ext_addrs = self.settings.external_addr.clone();
             let ext_addr_msg = message::ExtAddrsMessage { ext_addrs };
@@ -157,7 +157,7 @@ impl ProtocolBase for ProtocolAddress {
             self.jobsman.clone().spawn(self.clone().send_my_addrs(), executor.clone()).await;
         }
 
-        debug!(target: "net", "ProtocolAddress::start() [START]");
+        debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().handle_receive_addrs(), executor.clone()).await;
         self.jobsman.clone().spawn(self.clone().handle_receive_ext_addrs(), executor.clone()).await;
@@ -166,7 +166,7 @@ impl ProtocolBase for ProtocolAddress {
         // Send get_address message.
         let get_addrs = message::GetAddrsMessage {};
         let _ = self.channel.clone().send(get_addrs).await;
-        debug!(target: "net", "ProtocolAddress::start() [END]");
+        debug!(target: "net::protocol_address::handle_receive_addrs()", "ProtocolAddress::start() [END]");
         Ok(())
     }
 

+ 1 - 1
src/net/protocol/protocol_jobs_manager.rs

@@ -75,7 +75,7 @@ impl ProtocolJobsManager {
     /// Closes all open tasks. Takes all the tasks from the internal queue and
     /// closes them.
     async fn close_all_tasks(self: Arc<Self>) {
-        debug!(target: "net",
+        debug!(target: "net::protocol_jobs_manager",
             "ProtocolJobsManager::close_all_tasks() [START, name={}, addr={}]",
             self.name,
             self.channel.address()

+ 8 - 8
src/net/protocol/protocol_ping.rs

@@ -83,7 +83,7 @@ impl ProtocolPing {
             // Send ping message.
             let ping = message::PingMessage { nonce };
             self.channel.clone().send(ping).await?;
-            debug!(target: "net", "ProtocolPing::run_ping_pong() send Ping message");
+            debug!(target: "net::protocol_ping::run_ping_pong()", "ProtocolPing::run_ping_pong() send Ping message");
             // Start the timer for ping timer.
             let start = Instant::now();
 
@@ -91,12 +91,12 @@ impl ProtocolPing {
             let pong_msg = self.pong_sub.receive().await?;
             if pong_msg.nonce != nonce {
                 // TODO: this is too extreme
-                error!("Wrong nonce for ping reply. Disconnecting from channel.");
+                error!(target: "net::protocol_ping::run_ping_pong()", "Wrong nonce for ping reply. Disconnecting from channel.");
                 self.channel.stop().await;
                 return Err(Error::ChannelStopped)
             }
             let duration = start.elapsed().as_millis();
-            debug!(target: "net", "Received Pong message {}ms from [{:?}]",
+            debug!(target: "net::protocol_ping::run_ping_pong()", "Received Pong message {}ms from [{:?}]",
                    duration, self.channel.address());
         }
     }
@@ -104,16 +104,16 @@ impl ProtocolPing {
     /// Waits for ping, then replies with pong. Copies ping's nonce into the
     /// pong reply.
     async fn reply_to_ping(self: Arc<Self>) -> Result<()> {
-        debug!(target: "net", "ProtocolPing::reply_to_ping() [START]");
+        debug!(target: "net::protocol_ping::run_ping_pong()", "ProtocolPing::reply_to_ping() [START]");
         loop {
             // Wait for ping, reply with pong that has a matching nonce.
             let ping = self.ping_sub.receive().await?;
-            debug!(target: "net", "ProtocolPing::reply_to_ping() received Ping message");
+            debug!(target: "net::protocol_ping::run_ping_pong()", "ProtocolPing::reply_to_ping() received Ping message");
 
             // Send pong message.
             let pong = message::PongMessage { nonce: ping.nonce };
             self.channel.clone().send(pong).await?;
-            debug!(target: "net", "ProtocolPing::reply_to_ping() sent Pong reply");
+            debug!(target: "net::protocol_ping::run_ping_pong()", "ProtocolPing::reply_to_ping() sent Pong reply");
         }
     }
 
@@ -129,11 +129,11 @@ impl ProtocolBase for ProtocolPing {
     /// protocol task manager, then queues the reply. Sends out a ping and
     /// waits for pong reply. Waits for ping and replies with a pong.
     async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "net", "ProtocolPing::start() [START]");
+        debug!(target: "net::protocol_ping::run_ping_pong()", "ProtocolPing::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().run_ping_pong(), executor.clone()).await;
         self.jobsman.clone().spawn(self.reply_to_ping(), executor).await;
-        debug!(target: "net", "ProtocolPing::start() [END]");
+        debug!(target: "net::protocol_ping::run_ping_pong()", "ProtocolPing::start() [END]");
         Ok(())
     }
 

+ 2 - 2
src/net/protocol/protocol_registry.rs

@@ -67,12 +67,12 @@ impl ProtocolRegistry {
         for (session_flags, construct) in self.protocol_constructors.lock().await.iter() {
             // Skip protocols that are not registered for this session
             if selector_id & session_flags == 0 {
-                debug!("Skipping {selector_id:#b}, {session_flags:#b}");
+                debug!(target: "net::protocol_registry", "Skipping {selector_id:#b}, {session_flags:#b}");
                 continue
             }
 
             let protocol: ProtocolBasePtr = construct(channel.clone(), p2p.clone()).await;
-            debug!(target: "net", "Attached {}", protocol.name());
+            debug!(target: "net::protocol_registry", "Attached {}", protocol.name());
 
             protocols.push(protocol)
         }

+ 3 - 3
src/net/protocol/protocol_seed.rs

@@ -77,7 +77,7 @@ impl ProtocolBase for ProtocolSeed {
     /// then sends our address to the seed server. Sends a get-address
     /// message and receives an address message.
     async fn start(self: Arc<Self>, _executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "net", "ProtocolSeed::start() [START]");
+        debug!(target: "net::protocol_seed::send_self_address()", "ProtocolSeed::start() [START]");
 
         // Send own address to the seed server.
         self.send_self_address().await?;
@@ -88,10 +88,10 @@ impl ProtocolBase for ProtocolSeed {
 
         // Receive addresses.
         let addrs_msg = self.addr_sub.receive().await?;
-        debug!(target: "net", "ProtocolSeed::start() received {} addrs", addrs_msg.addrs.len());
+        debug!(target: "net::protocol_seed::send_self_address()", "ProtocolSeed::start() received {} addrs", addrs_msg.addrs.len());
         self.hosts.store(addrs_msg.addrs.clone()).await;
 
-        debug!(target: "net", "ProtocolSeed::start() [END]");
+        debug!(target: "net::protocol_seed::send_self_address()", "ProtocolSeed::start() [END]");
         Ok(())
     }
 

+ 12 - 11
src/net/protocol/protocol_version.rs

@@ -79,13 +79,13 @@ impl ProtocolVersion {
             return Err(Error::ChannelTimeout)
         }
 
-        debug!(target: "net", "ProtocolVersion::run() [END]");
+        debug!(target: "net::protocol_version::run()", "ProtocolVersion::run() [END]");
         Ok(())
     }
 
     /// Send and recieve version information.
     async fn exchange_versions(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "net", "ProtocolVersion::exchange_versions() [START]");
+        debug!(target: "net::protocol_version::run()", "ProtocolVersion::exchange_versions() [START]");
 
         let send = executor.spawn(self.clone().send_version());
         let recv = executor.spawn(self.recv_version());
@@ -93,14 +93,14 @@ impl ProtocolVersion {
         send.await?;
         recv.await?;
 
-        debug!(target: "net", "ProtocolVersion::exchange_versions() [END]");
+        debug!(target: "net::protocol_version::run()", "ProtocolVersion::exchange_versions() [END]");
         Ok(())
     }
 
     /// Send version info and wait for version acknowledgement
     /// and ensures the app version is the same, if configured.
     async fn send_version(self: Arc<Self>) -> Result<()> {
-        debug!(target: "net", "ProtocolVersion::send_version() [START]");
+        debug!(target: "net::protocol_version::run()", "ProtocolVersion::send_version() [START]");
 
         let version = message::VersionMessage { node_id: self.settings.node_id.clone() };
 
@@ -114,14 +114,14 @@ impl ProtocolVersion {
         if !self.settings.seeds.contains(&self.channel.address()) {
             match &self.settings.app_version {
                 Some(app_version) => {
-                    debug!(target: "net", "ProtocolVersion::send_version() [App version: {}]", app_version);
-                    debug!(target: "net", "ProtocolVersion::send_version() [Recieved version: {}]", verack_msg.app);
+                    debug!(target: "net::protocol_version::run()", "ProtocolVersion::send_version() [App version: {}]", app_version);
+                    debug!(target: "net::protocol_version::run()", "ProtocolVersion::send_version() [Recieved version: {}]", verack_msg.app);
                     // Version format: MAJOR.MINOR.PATCH
                     let app_versions: Vec<&str> = app_version.split('.').collect();
                     let verack_msg_versions: Vec<&str> = verack_msg.app.split('.').collect();
                     // Check for malformed versions
                     if app_versions.len() != 3 || verack_msg_versions.len() != 3 {
-                        error!("ProtocolVersion::send_version() [Malformed version detected. Disconnecting from channel.]");
+                        error!(target: "net::protocol_version::run()", "ProtocolVersion::send_version() [Malformed version detected. Disconnecting from channel.]");
                         self.hosts.remove(&self.channel.address()).await;
                         self.channel.stop().await;
                         return Err(Error::ChannelStopped)
@@ -131,6 +131,7 @@ impl ProtocolVersion {
                         app_versions[1] != verack_msg_versions[1]
                     {
                         error!(
+                            target: "net::protocol_version::run()",
                             "ProtocolVersion::send_version() [Wrong app version from ({}). Disconnecting from channel.]",
                             self.channel.address()
                         );
@@ -140,19 +141,19 @@ impl ProtocolVersion {
                     }
                 }
                 None => {
-                    debug!(target: "net", "ProtocolVersion::send_version() [App version not set, ignorring received]")
+                    debug!(target: "net::protocol_version::run()", "ProtocolVersion::send_version() [App version not set, ignorring received]")
                 }
             }
         }
 
-        debug!(target: "net", "ProtocolVersion::send_version() [END]");
+        debug!(target: "net::protocol_version::run()", "ProtocolVersion::send_version() [END]");
         Ok(())
     }
 
     /// Recieve version info, check the message is okay and send version
     /// acknowledgement with app version attached.
     async fn recv_version(self: Arc<Self>) -> Result<()> {
-        debug!(target: "net", "ProtocolVersion::recv_version() [START]");
+        debug!(target: "net::protocol_version::run()", "ProtocolVersion::recv_version() [START]");
         // Receive version message
         let version = self.version_sub.receive().await?;
         self.channel.set_remote_node_id(version.node_id.clone()).await;
@@ -162,7 +163,7 @@ impl ProtocolVersion {
             message::VerackMessage { app: self.settings.app_version.clone().unwrap_or_default() };
         self.channel.clone().send(verack).await?;
 
-        debug!(target: "net", "ProtocolVersion::recv_version() [END]");
+        debug!(target: "net::protocol_version::run()", "ProtocolVersion::recv_version() [END]");
         Ok(())
     }
 }

+ 4 - 4
src/net/session/inbound_session.rs

@@ -68,7 +68,7 @@ impl InboundSession {
     /// loop.
     pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
         if self.p2p().settings().inbound.is_empty() {
-            info!(target: "net", "Not configured for accepting incoming connections.");
+            info!(target: "net::inbound_session", "Not configured for accepting incoming connections.");
             return Ok(())
         }
 
@@ -115,7 +115,7 @@ impl InboundSession {
         accept_addr: Url,
         executor: Arc<Executor<'_>>,
     ) -> Result<()> {
-        info!(target: "net", "#{} starting inbound session on {}", index, accept_addr);
+        info!(target: "net::inbound_session", "#{} starting inbound session on {}", index, accept_addr);
         // Generate a new acceptor for this inbound session
         let acceptor = Acceptor::new(Mutex::new(None));
         let parent = Arc::downgrade(&self);
@@ -124,7 +124,7 @@ impl InboundSession {
         // Start listener
         let result = acceptor.clone().start(accept_addr, executor).await;
         if let Err(err) = result.clone() {
-            error!(target: "net", "#{} error starting listener: {}", index, err);
+            error!(target: "net::inbound_session", "#{} error starting listener: {}", index, err);
         }
 
         self.acceptors.lock().await.push(acceptor);
@@ -157,7 +157,7 @@ impl InboundSession {
         channel: ChannelPtr,
         executor: Arc<Executor<'_>>,
     ) -> Result<()> {
-        info!(target: "net", "#{} connected inbound [{}]", index, channel.address());
+        info!(target: "net::inbound_session", "#{} connected inbound [{}]", index, channel.address());
 
         self.clone().register_channel(channel.clone(), executor.clone()).await?;
 

+ 5 - 5
src/net/session/manual_session.rs

@@ -101,7 +101,7 @@ impl ManualSession {
         let transports = if outbound_transports.contains(&addr_transport) {
             vec![addr_transport]
         } else {
-            warn!(target: "net", "Manual outbound address {} transport is not in accepted outbound transports, will try with: {:?}", addr, outbound_transports);
+            warn!(target: "net::manual_session", "Manual outbound address {} transport is not in accepted outbound transports, will try with: {:?}", addr, outbound_transports);
             outbound_transports.clone()
         };
 
@@ -119,11 +119,11 @@ impl ManualSession {
                 // Replace addr transport
                 let mut transport_addr = addr.clone();
                 transport_addr.set_scheme(&transport.to_scheme())?;
-                info!(target: "net", "Connecting to manual outbound [{}]", transport_addr);
+                info!(target: "net::manual_session", "Connecting to manual outbound [{}]", transport_addr);
                 match connector.connect(transport_addr.clone()).await {
                     Ok(channel) => {
                         // Blacklist goes here
-                        info!(target: "net", "Connected to manual outbound [{}]", transport_addr);
+                        info!(target: "net::manual_session", "Connected to manual outbound [{}]", transport_addr);
 
                         let stop_sub = channel.subscribe_stop().await;
                         if stop_sub.is_err() {
@@ -148,7 +148,7 @@ impl ManualSession {
                         stop_sub.unwrap().receive().await;
                     }
                     Err(err) => {
-                        info!(target: "net", "Unable to connect to manual outbound [{}]: {}", addr, err);
+                        info!(target: "net::manual_session", "Unable to connect to manual outbound [{}]: {}", addr, err);
                     }
                 }
             }
@@ -162,7 +162,7 @@ impl ManualSession {
         }
 
         warn!(
-        target: "net",
+        target: "net::manual_session",
         "Suspending manual connection to [{}] after {} failed attempts.",
         &addr,
         attempts

+ 17 - 15
src/net/session/outbound_session.rs

@@ -118,7 +118,7 @@ impl OutboundSession {
     /// Start the outbound session. Runs the channel connect loop.
     pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
         let slots_count = self.p2p().settings().outbound_connections;
-        info!(target: "net", "Starting {} outbound connection slots.", slots_count);
+        info!(target: "net::outbound_session", "Starting {} outbound connection slots.", slots_count);
         // Activate mutex lock on connection slots.
         let mut connect_slots = self.connect_slots.lock().await;
 
@@ -168,9 +168,11 @@ impl OutboundSession {
                 .try_connect(slot_number, executor.clone(), &connector, outbound_transports)
                 .await
             {
-                Ok(_) => info!(target: "net", "#{} slot disconnected", slot_number),
+                Ok(_) => {
+                    info!(target: "net::outbound_session", "#{} slot disconnected", slot_number)
+                }
                 Err(err) => {
-                    error!(target: "net", "#{} slot connection failed: {}", slot_number, err)
+                    error!(target: "net::outbound_session", "#{} slot connection failed: {}", slot_number, err)
                 }
             }
 
@@ -190,7 +192,7 @@ impl OutboundSession {
         outbound_transports: &Vec<TransportName>,
     ) -> Result<()> {
         let addr = self.load_address(slot_number).await?;
-        info!(target: "net", "#{} processing outbound [{}]", slot_number, addr);
+        info!(target: "net::outbound_session", "#{} processing outbound [{}]", slot_number, addr);
         {
             let info = &mut self.slot_info.lock().await[slot_number as usize];
             info.addr = Some(addr.clone());
@@ -202,7 +204,7 @@ impl OutboundSession {
         let transports = if outbound_transports.contains(&addr_transport) {
             vec![addr_transport]
         } else {
-            warn!(target: "net", "#{} address {} transport is not in accepted outbound transports, will try with: {:?}", slot_number, addr, outbound_transports);
+            warn!(target: "net::outbound_session", "#{} address {} transport is not in accepted outbound transports, will try with: {:?}", slot_number, addr, outbound_transports);
             outbound_transports.clone()
         };
 
@@ -210,11 +212,11 @@ impl OutboundSession {
             // Replace addr transport
             let mut transport_addr = addr.clone();
             transport_addr.set_scheme(&transport.to_scheme())?;
-            info!(target: "net", "#{} connecting to outbound [{}]", slot_number, transport_addr);
+            info!(target: "net::outbound_session", "#{} connecting to outbound [{}]", slot_number, transport_addr);
             match connector.connect(transport_addr.clone()).await {
                 Ok(channel) => {
                     // Blacklist goes here
-                    info!(target: "net", "#{} connected to outbound [{}]", slot_number, transport_addr);
+                    info!(target: "net::outbound_session", "#{} connected to outbound [{}]", slot_number, transport_addr);
 
                     let stop_sub = channel.subscribe_stop().await;
                     if stop_sub.is_err() {
@@ -244,7 +246,7 @@ impl OutboundSession {
                     return Ok(())
                 }
                 Err(err) => {
-                    error!(target: "net", "Unable to connect to outbound [{}]: {}", &transport_addr, err);
+                    error!(target: "net::outbound_session", "Unable to connect to outbound [{}]: {}", &transport_addr, err);
                 }
             }
         }
@@ -310,13 +312,13 @@ impl OutboundSession {
 
             // Peer discovery
             if p2p.settings().peer_discovery {
-                debug!(target: "net", "#{} No available address found, entering peer discovery mode.", slot_number);
+                debug!(target: "net::outbound_session", "#{} No available address found, entering peer discovery mode.", slot_number);
                 self.peer_discovery(slot_number).await?;
-                debug!(target: "net", "#{} Discovery mode ended.", slot_number);
+                debug!(target: "net::outbound_session", "#{} Discovery mode ended.", slot_number);
             }
 
             // Sleep and then retry
-            debug!(target: "net", "Retrying connect slot #{}", slot_number);
+            debug!(target: "net::outbound_session", "Retrying connect slot #{}", slot_number);
             async_util::sleep(p2p.settings().outbound_retry_seconds).await;
         }
     }
@@ -326,24 +328,24 @@ impl OutboundSession {
         // Check that another slot(thread) already tries to update hosts
         let p2p = self.p2p();
         if !p2p.clone().start_discovery().await {
-            debug!(target: "net", "#{} P2P already on discovery mode.", slot_number);
+            debug!(target: "net::outbound_session", "#{} P2P already on discovery mode.", slot_number);
             return Ok(())
         }
 
-        debug!(target: "net", "#{} Discovery mode started.", slot_number);
+        debug!(target: "net::outbound_session", "#{} Discovery mode started.", slot_number);
 
         // Getting a random connected channel to ask for peers
         let channel = match p2p.clone().random_channel().await {
             Some(c) => c,
             None => {
-                debug!(target: "net", "#{} No peers found.", slot_number);
+                debug!(target: "net::outbound_session", "#{} No peers found.", slot_number);
                 p2p.clone().stop_discovery().await;
                 return Ok(())
             }
         };
 
         // Ask peer
-        debug!(target: "net", "#{} Asking peer: {}", slot_number, channel.address());
+        debug!(target: "net::outbound_session", "#{} Asking peer: {}", slot_number, channel.address());
         let get_addr_msg = message::GetAddrsMessage {};
         channel.send(get_addr_msg).await?;
 

+ 13 - 13
src/net/session/seedsync_session.rs

@@ -50,11 +50,11 @@ impl SeedSyncSession {
     /// Start the seed sync session. Creates a new task for every seed connection and
     /// starts the seed on each task.
     pub async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "net", "SeedSyncSession::start() [START]");
+        debug!(target: "net::seedsync_session", "SeedSyncSession::start() [START]");
         let settings = self.p2p().settings();
 
         if settings.seeds.is_empty() {
-            warn!("Skipping seed sync process since no seeds are configured.");
+            warn!(target: "net::seedsync_session", "Skipping seed sync process since no seeds are configured.");
             // Store external addresses in hosts explicitly
             if !settings.external_addr.is_empty() {
                 self.p2p().hosts().store(settings.external_addr.clone()).await
@@ -84,13 +84,13 @@ impl SeedSyncSession {
                 match result {
                     Ok(t) => match t {
                         Ok(()) => {
-                            info!("Seed #{} connected successfully", i)
+                            info!(target: "net::seedsync_session", "Seed #{} connected successfully", i)
                         }
                         Err(err) => {
-                            warn!("Seed #{} failed for reason {}", i, err)
+                            warn!(target: "net::seedsync_session", "Seed #{} failed for reason {}", i, err)
                         }
                     },
-                    Err(_err) => error!("Seed #{} timed out", i),
+                    Err(_err) => error!(target: "net::seedsync_session", "Seed #{} timed out", i),
                 }
             });
         }
@@ -98,10 +98,10 @@ impl SeedSyncSession {
 
         // Seed process complete
         if self.p2p().hosts().is_empty().await {
-            warn!("Hosts pool still empty after seeding");
+            warn!(target: "net::seedsync_session", "Hosts pool still empty after seeding");
         }
 
-        debug!(target: "net", "SeedSyncSession::start() [END]");
+        debug!(target: "net::seedsync_session", "SeedSyncSession::start() [END]");
         Ok(())
     }
 
@@ -112,7 +112,7 @@ impl SeedSyncSession {
         seed: Url,
         executor: Arc<Executor<'_>>,
     ) -> Result<()> {
-        debug!(target: "net", "SeedSyncSession::start_seed(i={}) [START]", seed_index);
+        debug!(target: "net::seedsync_session", "SeedSyncSession::start_seed(i={}) [START]", seed_index);
         let (_hosts, settings) = {
             let p2p = self.p2p.upgrade().unwrap();
             (p2p.hosts(), p2p.settings())
@@ -124,22 +124,22 @@ impl SeedSyncSession {
             Ok(channel) => {
                 // Blacklist goes here
 
-                info!("Connected seed #{} [{}]", seed_index, seed);
+                info!(target: "net::seedsync_session", "Connected seed #{} [{}]", seed_index, seed);
 
                 if let Err(err) =
                     self.clone().register_channel(channel.clone(), executor.clone()).await
                 {
-                    warn!("Failure during seed sync session #{} [{}]: {}", seed_index, seed, err);
+                    warn!(target: "net::seedsync_session", "Failure during seed sync session #{} [{}]: {}", seed_index, seed, err);
                 }
 
-                info!("Disconnecting from seed #{} [{}]", seed_index, seed);
+                info!(target: "net::seedsync_session", "Disconnecting from seed #{} [{}]", seed_index, seed);
                 channel.stop().await;
 
-                debug!(target: "net", "SeedSyncSession::start_seed(i={}) [END]", seed_index);
+                debug!(target: "net::seedsync_session", "SeedSyncSession::start_seed(i={}) [END]", seed_index);
                 Ok(())
             }
             Err(err) => {
-                warn!("Failure contacting seed #{} [{}]: {}", seed_index, seed, err);
+                warn!(target: "net::seedsync_session", "Failure contacting seed #{} [{}]: {}", seed_index, seed, err);
                 Err(err)
             }
         }

+ 5 - 5
src/net/transport/tcp.rs

@@ -38,7 +38,7 @@ impl TransportListener for TcpListener {
         let (stream, peer_addr) = match self.accept().await {
             Ok((s, a)) => (s, a),
             Err(err) => {
-                error!("Error listening for connections: {}", err);
+                error!(target: "net::tcp", "Error listening for connections: {}", err);
                 return Err(Error::AcceptConnectionFailed(self.local_addr()?.to_string()))
             }
         };
@@ -53,7 +53,7 @@ impl TransportListener for (TlsAcceptor, TcpListener) {
         let (stream, peer_addr) = match self.1.accept().await {
             Ok((s, a)) => (s, a),
             Err(err) => {
-                error!("Error listening for connections: {}", err);
+                error!(target: "net::tcp", "Error listening for connections: {}", err);
                 return Err(Error::AcceptConnectionFailed(self.1.local_addr()?.to_string()))
             }
         };
@@ -63,7 +63,7 @@ impl TransportListener for (TlsAcceptor, TcpListener) {
         let url = socket_addr_to_url(peer_addr, "tcp+tls")?;
 
         if let Err(err) = stream {
-            error!("Error wrapping the connection {} with tls: {}", url, err);
+            error!(target: "net::tcp", "Error wrapping the connection {} with tls: {}", url, err);
             return Err(Error::AcceptTlsConnectionFailed(self.1.local_addr()?.to_string()))
         }
 
@@ -96,7 +96,7 @@ impl Transport for TcpTransport {
         }
 
         let socket_addr = url.socket_addrs(|| None)?[0];
-        debug!(target: "net", "{} transport: listening on {}", url.scheme(), socket_addr);
+        debug!(target: "net::tcp", "{} transport: listening on {}", url.scheme(), socket_addr);
         Ok(Box::pin(self.do_listen(socket_addr)))
     }
 
@@ -112,7 +112,7 @@ impl Transport for TcpTransport {
         }
 
         let socket_addr = url.socket_addrs(|| None)?[0];
-        debug!(target: "net", "{} transport: dialing {}", url.scheme(), socket_addr);
+        debug!(target: "net::tcp", "{} transport: dialing {}", url.scheme(), socket_addr);
         Ok(Box::pin(self.do_dial(socket_addr, timeout)))
     }
 

+ 3 - 3
src/net/transport/unix.rs

@@ -44,7 +44,7 @@ impl TransportListener for UnixListener {
         let (stream, peer_addr) = match self.accept().await {
             Ok((s, a)) => (s, a),
             Err(err) => {
-                error!("Error listening for connections: {}", err);
+                error!(target: "net::unix", "Error listening for connections: {}", err);
                 return Err(Error::AcceptConnectionFailed(unix_socket_addr_to_string(
                     self.local_addr()?,
                 )))
@@ -83,7 +83,7 @@ impl Transport for UnixTransport {
 
         let socket_path = url.path();
         let socket_addr = SocketAddr::from_pathname(socket_path)?;
-        debug!(target: "net", "{} transport: listening on {}", url.scheme(), socket_path);
+        debug!(target: "net::unix", "{} transport: listening on {}", url.scheme(), socket_path);
         Ok(Box::pin(self.do_listen(socket_addr)))
     }
 
@@ -99,7 +99,7 @@ impl Transport for UnixTransport {
 
         let socket_path = url.path();
         let socket_addr = SocketAddr::from_pathname(socket_path)?;
-        debug!(target: "net", "{} transport: dialing {}", url.scheme(), socket_path);
+        debug!(target: "net::unix", "{} transport: dialing {}", url.scheme(), socket_path);
         Ok(Box::pin(self.do_dial(socket_addr, timeout)))
     }
 

+ 6 - 6
src/raft/consensus.rs

@@ -89,7 +89,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
         seen_msgs: Arc<Mutex<HashMap<String, i64>>>,
     ) -> Result<Self> {
         if settings.datastore_path.to_str().is_none() {
-            error!(target: "raft", "datastore path is incorrect");
+            error!(target: "raft::consensus", "datastore path is incorrect");
             return Err(Error::ParseFailed("unable to parse pathbuf to str"))
         };
 
@@ -188,11 +188,11 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
             }
 
             if let Err(e) = result {
-                warn!(target: "raft", "warn: {}", e);
+                warn!(target: "raft::consensus", "warn: {}", e);
             }
         }
 
-        warn!(target: "raft", "Raft Terminating...");
+        warn!(target: "raft::consensus", "Raft Terminating...");
         p2p_send_task.cancel().await;
         prune_seen_messages_task.cancel().await;
         prune_nodes_id_task.cancel().await;
@@ -255,7 +255,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
             }
         }
 
-        debug!(target: "raft", "Role: {:?} Id: {:?}, broadcast a msg id: {:?} ", self.role, self.id, msg_id);
+        debug!(target: "raft::consensus", "Role: {:?} Id: {:?}, broadcast a msg id: {:?} ", self.role, self.id, msg_id);
 
         Ok(())
     }
@@ -292,7 +292,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
             }
         }
 
-        debug!(target: "raft", "Role: {:?} Id: {:?}, receive a msg with id: {}  recipient_id: {:?} method: {:?} ",
+        debug!(target: "raft::consensus", "Role: {:?} Id: {:?}, receive a msg with id: {}  recipient_id: {:?} method: {:?} ",
                self.role, self.id, msg.id, &msg.recipient_id, &msg.method);
         Ok(())
     }
@@ -306,7 +306,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
     ) -> Result<()> {
         let random_id = if msg_id.is_some() { msg_id.unwrap() } else { OsRng.next_u64() };
 
-        debug!(target: "raft","Role: {:?} Id: {:?}, send a msg with id: {}  recipient_id: {:?} method: {:?} ",
+        debug!(target: "raft::consensus","Role: {:?} Id: {:?}, send a msg with id: {}  recipient_id: {:?} method: {:?} ",
                self.role, self.id, random_id, &recipient_id, &method);
 
         let net_msg = NetMsg { id: random_id, recipient_id, payload: payload.to_vec(), method };

+ 2 - 2
src/raft/consensus_candidate.rs

@@ -42,7 +42,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
         self.set_current_term(&(self.current_term()? + 1))?;
 
         if self.role != Role::Candidate {
-            info!(target: "raft", "Set the node role as Candidate");
+            info!(target: "raft::consensus_candidate", "Set the node role as Candidate");
             self.role = Role::Candidate;
         }
 
@@ -75,7 +75,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
             drop(nodes);
 
             if self.votes_received.len() >= ((nodes_cloned.len() + 1) / 2) {
-                info!(target: "raft", "Set the node role as Leader");
+                info!(target: "raft::consensus_candidate", "Set the node role as Leader");
                 self.role = Role::Leader;
                 self.current_leader = self.id();
                 for node in nodes_cloned.iter() {

+ 2 - 2
src/raft/consensus_follower.rs

@@ -58,7 +58,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
     }
 
     pub(super) async fn receive_log_request(&mut self, lr: LogRequest) -> Result<()> {
-        debug!(target: "raft",
+        debug!(target: "raft::consensus_follower",
         "Receive LogRequest current_term: {} prefix_term: {} prefix_len: {} commit_length: {} suffixlen {}",
         lr.current_term, lr.prefix_term, lr.prefix_len, lr.commit_length, lr.suffix.len(),
         );
@@ -88,7 +88,7 @@ impl<T: Decodable + Encodable + Clone> Raft<T> {
         let response =
             LogResponse { node_id: self.id(), current_term: self.current_term()?, ack, ok };
 
-        debug!(target: "raft",
+        debug!(target: "raft::consensus_follower",
          "Send LogResponse current_term: {} ack: {} ok: {}",
          response.current_term, response.ack, response.ok
         );

+ 1 - 1
src/raft/datastore.rs

@@ -54,7 +54,7 @@ impl<T: Encodable + Decodable> DataStore<T> {
         Ok(Self { _db, logs, commits, voted_for, current_term, id })
     }
     pub async fn flush(&self) -> Result<()> {
-        debug!(target: "raft", "DataStore flush");
+        debug!(target: "raft::datastore", "DataStore flush");
         self._db.flush_async().await?;
         Ok(())
     }

+ 4 - 4
src/raft/protocol_raft.rs

@@ -63,7 +63,7 @@ impl ProtocolRaft {
     }
 
     async fn handle_receive_msg(self: Arc<Self>) -> Result<()> {
-        debug!(target: "protocol_raft", "ProtocolRaft::handle_receive_msg() [START]");
+        debug!(target: "raft::protocol_raft", "ProtocolRaft::handle_receive_msg() [START]");
 
         // on initialization send a NodeIdMsg
         let random_id = OsRng.next_u64();
@@ -83,7 +83,7 @@ impl ProtocolRaft {
             let msg = self.msg_sub.receive().await?;
 
             debug!(
-            target: "protocol_raft",
+            target: "raft::protocol_raft",
             "ProtocolRaft::handle_receive_msg() received id: {:?} method {:?}",
             &msg.id, &msg.method
             );
@@ -117,10 +117,10 @@ impl net::ProtocolBase for ProtocolRaft {
     /// protocol task manager, then queues the reply. Sends out a ping and
     /// waits for pong reply. Waits for ping and replies with a pong.
     async fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) -> Result<()> {
-        debug!(target: "protocol_raft", "ProtocolRaft::start() [START]");
+        debug!(target: "raft::protocol_raft", "ProtocolRaft::start() [START]");
         self.jobsman.clone().start(executor.clone());
         self.jobsman.clone().spawn(self.clone().handle_receive_msg(), executor.clone()).await;
-        debug!(target: "protocol_raft", "ProtocolRaft::start() [END]");
+        debug!(target: "raft::protocol_raft", "ProtocolRaft::start() [END]");
         Ok(())
     }
 

+ 14 - 14
src/rpc/client.rs

@@ -63,10 +63,10 @@ impl RpcClient {
         subscriber: SubscriberPtr<JsonResult>,
     ) -> Result<()> {
         // Perform initial request.
-        debug!(target: "jsonrpc-client", "--> {}", serde_json::to_string(&req)?);
+        debug!(target: "rpc::client", "--> {}", serde_json::to_string(&req)?);
         // If the connection is closed, the sender will get an error for sending to a closed channel.
         if let Err(e) = self.send.send((json!(req), false)).await {
-            error!(target: "jsonrpc-client", "JSON-RPC client unable to send to {} (channels closed): {}", self.url, e);
+            error!(target: "rpc::client", "JSON-RPC client unable to send to {} (channels closed): {}", self.url, e);
             return Err(Error::NetworkOperationFailed)
         }
 
@@ -74,13 +74,13 @@ impl RpcClient {
             // If the connection is closed, the receiver will get an error for waiting on a closed channel.
             let notification = self.recv.recv().await;
             if notification.is_err() {
-                error!(target: "jsonrpc-client", "JSON-RPC client unable to recv from {} (channels closed)", self.url);
+                error!(target: "rpc::client", "JSON-RPC client unable to recv from {} (channels closed)", self.url);
                 break
             }
 
             // Notify subscribed channels
             let notification = notification?;
-            debug!(target: "jsonrpc-client", "<-- {}", serde_json::to_string(&notification)?);
+            debug!(target: "rpc::client", "<-- {}", serde_json::to_string(&notification)?);
 
             subscriber.notify(notification.clone()).await;
 
@@ -92,7 +92,7 @@ impl RpcClient {
 
             // Triggering next consume
             if let Err(e) = self.send.send((json!(req), false)).await {
-                error!(target: "jsonrpc-client", "JSON-RPC client unable to send to {} (channels closed): {}", self.url, e);
+                error!(target: "rpc::client", "JSON-RPC client unable to send to {} (channels closed): {}", self.url, e);
                 break
             }
         }
@@ -105,12 +105,12 @@ impl RpcClient {
     pub async fn request(&self, value: JsonRequest) -> Result<Value> {
         let req_id = value.id.clone().as_u64().unwrap();
 
-        debug!(target: "jsonrpc-client", "--> {}", serde_json::to_string(&value)?);
+        debug!(target: "rpc::client", "--> {}", serde_json::to_string(&value)?);
 
         // If the connection is closed, the sender will get an error for
         // sending to a closed channel.
         if let Err(e) = self.send.send((json!(value), true)).await {
-            error!("JSON-RPC client unable to send to {} (channels closed): {}", self.url, e);
+            error!(target: "rpc::client", "JSON-RPC client unable to send to {} (channels closed): {}", self.url, e);
             return Err(Error::NetworkOperationFailed)
         }
 
@@ -118,7 +118,7 @@ impl RpcClient {
         // waiting on a closed channel.
         let reply = self.recv.recv().await;
         if reply.is_err() {
-            error!("JSON-RPC client unable to recv from {} (channels closed)", self.url);
+            error!(target: "rpc::client", "JSON-RPC client unable to recv from {} (channels closed)", self.url);
             return Err(Error::NetworkOperationFailed)
         }
 
@@ -136,15 +136,15 @@ impl RpcClient {
                     return Err(Error::JsonRpcError(e.error.message.to_string()))
                 }
 
-                debug!(target: "jsonrpc-client", "<-- {}", serde_json::to_string(&r)?);
+                debug!(target: "rpc::client", "<-- {}", serde_json::to_string(&r)?);
                 Ok(r.result)
             }
             JsonResult::Error(e) => {
-                debug!(target: "jsonrpc-client", "<-- {}", serde_json::to_string(&e)?);
+                debug!(target: "rpc::client", "<-- {}", serde_json::to_string(&e)?);
                 Err(Error::JsonRpcError(e.error.message.to_string()))
             }
             JsonResult::Notification(n) => {
-                debug!(target: "jsonrpc-client", "<-- {}", serde_json::to_string(&n)?);
+                debug!(target: "rpc::client", "<-- {}", serde_json::to_string(&n)?);
                 Err(Error::JsonRpcError("Unexpected reply".to_string()))
             }
             JsonResult::Subscriber(_) => Err(Error::JsonRpcError("Unexpected reply".to_string())),
@@ -176,13 +176,13 @@ impl RpcClient {
         macro_rules! reqrep {
             ($stream:expr, $transport:expr, $upgrade:expr) => {{
                 if let Err(err) = $stream {
-                    error!("JSON-RPC client setup for {} failed: {}", uri, err);
+                    error!(target: "rpc::client", "JSON-RPC client setup for {} failed: {}", uri, err);
                     return Err(Error::ConnectFailed)
                 }
 
                 let stream = $stream?.await;
                 if let Err(err) = stream {
-                    error!("JSON-RPC client connection to {} failed: {}", uri, err);
+                    error!(target: "rpc::client", "JSON-RPC client connection to {} failed: {}", uri, err);
                     return Err(Error::ConnectFailed)
                 }
 
@@ -263,7 +263,7 @@ impl RpcClient {
                                 result_send.send(reply).await?;
                                 break
                             },
-                            Err(e) => debug!("JSON-RPC client retrying failed convertion with error: {}", e),
+                            Err(e) => debug!(target: "rpc::client", "JSON-RPC client retrying failed convertion with error: {}", e),
                         }
                     }
                 }

+ 6 - 6
src/rpc/clock_sync.rs

@@ -82,18 +82,18 @@ pub async fn ntp_request() -> Result<Timestamp> {
 /// If all retries fail, system clock is considered invalid.
 /// TODO: 1. Add proxy functionality in order not to leak connections
 pub async fn check_clock(peers: &[Url]) -> Result<()> {
-    debug!("System clock check started...");
+    debug!(target: "rpc::clock_sync", "System clock check started...");
     let mut r = 0;
     while r < RETRIES {
         if let Err(e) = clock_check(peers).await {
-            debug!("Error during clock check: {:#?}", e);
+            debug!(target: "rpc::clock_sync", "Error during clock check: {:#?}", e);
             r += 1;
             continue
         };
         break
     }
 
-    debug!("System clock check finished. Retries: {}", r);
+    debug!(target: "rpc::clock_sync", "System clock check finished. Retries: {}", r);
     if r == RETRIES {
         return Err(Error::InvalidClock)
     }
@@ -130,9 +130,9 @@ async fn clock_check(peers: &[Url]) -> Result<()> {
         }
     };
 
-    debug!("peer_time: {:#?}", peer_time);
-    debug!("ntp_time: {:#?}", ntp_time);
-    debug!("system_time: {:#?}", system_time);
+    debug!(target: "rpc::clock_sync", "peer_time: {:#?}", peer_time);
+    debug!(target: "rpc::clock_sync", "ntp_time: {:#?}", ntp_time);
+    debug!(target: "rpc::clock_sync", "system_time: {:#?}", system_time);
 
     // We verify that system time is equal to peer (if exists) and ntp times
     let check = match peer_time {

+ 20 - 20
src/rpc/server.rs

@@ -53,25 +53,25 @@ async fn accept(
 
         let n = match stream.read(&mut buf).await {
             Ok(n) if n == 0 => {
-                debug!(target: "jsonrpc-server", "Closed connection for {}", peer_addr);
+                debug!(target: "rpc::server", "Closed connection for {}", peer_addr);
                 break
             }
             Ok(n) => n,
             Err(e) => {
-                error!("JSON-RPC server failed reading from {} socket: {}", peer_addr, e);
-                debug!(target: "jsonrpc-server", "Closed connection for {}", peer_addr);
+                error!(target: "rpc::server", "JSON-RPC server failed reading from {} socket: {}", peer_addr, e);
+                debug!(target: "rpc::server", "Closed connection for {}", peer_addr);
                 break
             }
         };
 
         let r: JsonRequest = match serde_json::from_slice(&buf[0..n]) {
             Ok(r) => {
-                debug!(target: "jsonrpc-server", "{} --> {}", peer_addr, String::from_utf8_lossy(&buf));
+                debug!(target: "rpc::server", "{} --> {}", peer_addr, String::from_utf8_lossy(&buf));
                 r
             }
             Err(e) => {
-                warn!("JSON-RPC server received invalid JSON from {}: {}", peer_addr, e);
-                debug!(target: "jsonrpc-server", "Closed connection for {}", peer_addr);
+                warn!(target: "rpc::server", "JSON-RPC server received invalid JSON from {}: {}", peer_addr, e);
+                debug!(target: "rpc::server", "Closed connection for {}", peer_addr);
                 break
             }
         };
@@ -86,11 +86,11 @@ async fn accept(
 
                     // Push notification
                     let j = serde_json::to_string(&notification).unwrap();
-                    debug!(target: "jsonrpc-server", "{} <-- {}", peer_addr, j);
+                    debug!(target: "rpc::server", "{} <-- {}", peer_addr, j);
 
                     if let Err(e) = stream.write_all(j.as_bytes()).await {
-                        error!(target: "jsonrpc-server", "JSON-RPC server failed writing to {} socket: {}", peer_addr, e);
-                        debug!(target: "jsonrpc-server", "Closed connection for {}", peer_addr);
+                        error!(target: "rpc::server", "JSON-RPC server failed writing to {} socket: {}", peer_addr, e);
+                        debug!(target: "rpc::server", "Closed connection for {}", peer_addr);
                         break
                     }
                 }
@@ -98,11 +98,11 @@ async fn accept(
             }
             _ => {
                 let j = serde_json::to_string(&reply).unwrap();
-                debug!(target: "jsonrpc-server", "{} <-- {}", peer_addr, j);
+                debug!(target: "rpc::server", "{} <-- {}", peer_addr, j);
 
                 if let Err(e) = stream.write_all(j.as_bytes()).await {
-                    error!(target: "jsonrpc-server", "JSON-RPC server failed writing to {} socket: {}", peer_addr, e);
-                    debug!(target: "jsonrpc-server", "Closed connection for {}", peer_addr);
+                    error!(target: "rpc::server", "JSON-RPC server failed writing to {} socket: {}", peer_addr, e);
+                    debug!(target: "rpc::server", "Closed connection for {}", peer_addr);
                     break
                 }
             }
@@ -120,12 +120,12 @@ async fn run_accept_loop(
     ex: Arc<smol::Executor<'_>>,
 ) -> Result<()> {
     while let Ok((stream, peer_addr)) = listener.next().await {
-        info!("JSON-RPC server accepted connection from {}", peer_addr);
+        info!(target: "rpc::server", "JSON-RPC server accepted connection from {}", peer_addr);
         // Detaching requests handling
         let _rh = rh.clone();
         ex.spawn(async move {
             if let Err(e) = accept(stream, peer_addr.clone(), _rh).await {
-                error!(target: "jsonrpc-server", "JSON-RPC server error on handling request of {}: {}", peer_addr, e);
+                error!(target: "rpc::server", "JSON-RPC server error on handling request of {}: {}", peer_addr, e);
             }
         }).detach();
     }
@@ -140,30 +140,30 @@ pub async fn listen_and_serve(
     rh: Arc<impl RequestHandler + 'static>,
     ex: Arc<smol::Executor<'_>>,
 ) -> Result<()> {
-    debug!(target: "jsonrpc-server", "Trying to bind listener on {}", accept_url);
+    debug!(target: "rpc::server", "Trying to bind listener on {}", accept_url);
 
     macro_rules! accept {
         ($listener:expr, $transport:expr, $upgrade:expr) => {{
             if let Err(err) = $listener {
-                error!("JSON-RPC server setup for {} failed: {}", accept_url, err);
+                error!(target: "rpc::server", "JSON-RPC server setup for {} failed: {}", accept_url, err);
                 return Err(Error::BindFailed(accept_url.as_str().into()))
             }
 
             let listener = $listener?.await;
             if let Err(err) = listener {
-                error!("JSON-RPC listener bind to {} failed: {}", accept_url, err);
+                error!(target: "rpc::server", "JSON-RPC listener bind to {} failed: {}", accept_url, err);
                 return Err(Error::BindFailed(accept_url.as_str().into()))
             }
 
             let listener = listener?;
             match $upgrade {
                 None => {
-                    info!("JSON-RPC listener bound to {}", accept_url);
+                    info!(target: "rpc::server", "JSON-RPC listener bound to {}", accept_url);
                     run_accept_loop(Box::new(listener), rh, ex.clone()).await?;
                 }
                 Some(u) if u == "tls" => {
                     let tls_listener = $transport.upgrade_listener(listener)?.await?;
-                    info!("JSON-RPC listener bound to {}", accept_url);
+                    info!(target: "rpc::server", "JSON-RPC listener bound to {}", accept_url);
                     run_accept_loop(Box::new(tls_listener), rh, ex.clone()).await?;
                 }
                 Some(u) => return Err(Error::UnsupportedTransportUpgrade(u)),
@@ -185,7 +185,7 @@ pub async fn listen_and_serve(
 
             // Generate EHS pointing to local address
             let hurl = transport.create_ehs(accept_url.clone())?;
-            info!("Created ephemeral hidden service: {}", hurl.to_string());
+            info!(target: "rpc::server", "Created ephemeral hidden service: {}", hurl.to_string());
 
             let listener = transport.clone().listen_on(accept_url.clone());
             accept!(listener, transport, upgrade);

+ 32 - 32
src/runtime/import/db.rs

@@ -84,7 +84,7 @@ pub(crate) fn db_init(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i
 
             let mut buf = vec![0_u8; len as usize];
             if let Err(e) = mem_slice.read_slice(&mut buf) {
-                error!(target: "wasm_runtime::db_init", "Failed to read from memory slice: {}", e);
+                error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
                 return DB_INIT_FAILED
             };
 
@@ -93,7 +93,7 @@ pub(crate) fn db_init(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i
             let cid: ContractId = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_init", "Failed to decode ContractId: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode ContractId: {}", e);
                     return DB_INIT_FAILED
                 }
             };
@@ -101,7 +101,7 @@ pub(crate) fn db_init(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i
             let db_name: String = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_init", "Failed to decode db_name: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode db_name: {}", e);
                     return DB_INIT_FAILED
                 }
             };
@@ -109,14 +109,14 @@ pub(crate) fn db_init(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i
             // TODO: Ensure we've read the entire buffer above.
 
             if &cid != contract_id {
-                error!(target: "wasm_runtime::db_init", "Unauthorized ContractId for db_init");
+                error!(target: "runtime::db::db_init()", "Unauthorized ContractId for db_init");
                 return CALLER_ACCESS_DENIED
             }
 
             let tree_handle = match contracts.init(db, &cid, &db_name) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime:db_lookup", "Failed to init db: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to init db: {}", e);
                     return DB_INIT_FAILED
                 }
             };
@@ -134,7 +134,7 @@ pub(crate) fn db_init(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i
             (db_handles.len() - 1) as i32
         }
         _ => {
-            error!(target: "wasm_runtime::db_init", "db_init called in unauthorized section");
+            error!(target: "runtime::db::db_init()", "db_init called in unauthorized section");
             CALLER_ACCESS_DENIED
         }
     }
@@ -153,13 +153,13 @@ pub(crate) fn db_lookup(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) ->
             let contracts = &env.blockchain.contracts;
 
             let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
-                error!(target: "wasm_runtime::db_lookup", "Failed to make slice from ptr");
+                error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
                 return DB_LOOKUP_FAILED
             };
 
             let mut buf = vec![0_u8; len as usize];
             if let Err(e) = mem_slice.read_slice(&mut buf) {
-                error!(target: "wasm_runtime::db_lookup", "Failed to read from memory slice: {}", e);
+                error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
                 return DB_LOOKUP_FAILED
             };
 
@@ -168,7 +168,7 @@ pub(crate) fn db_lookup(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) ->
             let cid: ContractId = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_lookup", "Failed to decode ContractId: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode ContractId: {}", e);
                     return DB_LOOKUP_FAILED
                 }
             };
@@ -176,7 +176,7 @@ pub(crate) fn db_lookup(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) ->
             let db_name: String = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_lookup", "Failed to decode db_name: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode db_name: {}", e);
                     return DB_LOOKUP_FAILED
                 }
             };
@@ -186,7 +186,7 @@ pub(crate) fn db_lookup(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) ->
             let tree_handle = match contracts.lookup(db, &cid, &db_name) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime:db_lookup", "Failed to lookup db: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to lookup db: {}", e);
                     return DB_LOOKUP_FAILED
                 }
             };
@@ -204,7 +204,7 @@ pub(crate) fn db_lookup(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) ->
             (db_handles.len() - 1) as i32
         }
         _ => {
-            error!(target: "wasm_runtime::db_lookup", "db_lookup called in unauthorized section");
+            error!(target: "runtime::db::db_init()", "db_lookup called in unauthorized section");
             CALLER_ACCESS_DENIED
         }
     }
@@ -218,13 +218,13 @@ pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i3
             let memory_view = env.memory_view(&ctx);
 
             let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
-                error!(target: "wasm_runtime::db_set", "Failed to make slice from ptr");
+                error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
                 return DB_SET_FAILED
             };
 
             let mut buf = vec![0_u8; len as usize];
             if let Err(e) = mem_slice.read_slice(&mut buf) {
-                error!(target: "wasm_runtime:db_set", "Failed to read from memory slice: {}", e);
+                error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
                 return DB_SET_FAILED
             };
 
@@ -234,7 +234,7 @@ pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i3
             let db_handle: u32 = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_set", "Failed to decode DbHandle: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode DbHandle: {}", e);
                     return DB_SET_FAILED
                 }
             };
@@ -243,7 +243,7 @@ pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i3
             let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_set", "Failed to decode key vec: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode key vec: {}", e);
                     return DB_SET_FAILED
                 }
             };
@@ -251,7 +251,7 @@ pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i3
             let value: Vec<u8> = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_set", "Failed to decode value vec: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode value vec: {}", e);
                     return DB_SET_FAILED
                 }
             };
@@ -262,7 +262,7 @@ pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i3
             let mut db_batches = env.db_batches.borrow_mut();
 
             if db_handles.len() <= db_handle || db_batches.len() <= db_handle {
-                error!(target: "wasm_runtime::db_set", "Requested DbHandle that is out of bounds");
+                error!(target: "runtime::db::db_init()", "Requested DbHandle that is out of bounds");
                 return DB_SET_FAILED
             }
 
@@ -271,7 +271,7 @@ pub(crate) fn db_set(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i3
             let db_batch = &mut db_batches[handle_idx];
 
             if db_handle.contract_id != env.contract_id {
-                error!(target: "wasm_runtime::db_set", "Unauthorized to write to DbHandle");
+                error!(target: "runtime::db::db_init()", "Unauthorized to write to DbHandle");
                 return CALLER_ACCESS_DENIED
             }
 
@@ -291,13 +291,13 @@ pub(crate) fn db_get(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i6
             let memory_view = env.memory_view(&ctx);
 
             let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
-                error!(target: "wasm_runtime::db_get", "Failed to make slice from ptr");
+                error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
                 return DB_GET_FAILED.into()
             };
 
             let mut buf = vec![0_u8; len as usize];
             if let Err(e) = mem_slice.read_slice(&mut buf) {
-                error!(target: "wasm_runtime::db_get", "Failed to read from memory slice: {}", e);
+                error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
                 return DB_GET_FAILED.into()
             };
 
@@ -307,7 +307,7 @@ pub(crate) fn db_get(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i6
             let db_handle: u32 = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_get", "Failed to decode DbHandle: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode DbHandle: {}", e);
                     return DB_GET_FAILED.into()
                 }
             };
@@ -316,7 +316,7 @@ pub(crate) fn db_get(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i6
             let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_get", "Failed to decode key from vec: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode key from vec: {}", e);
                     return DB_GET_FAILED.into()
                 }
             };
@@ -326,7 +326,7 @@ pub(crate) fn db_get(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i6
             let db_handles = env.db_handles.borrow();
 
             if db_handles.len() <= db_handle {
-                error!(target: "wasm_runtime::db_get", "Requested DbHandle that is out of bounds");
+                error!(target: "runtime::db::db_init()", "Requested DbHandle that is out of bounds");
                 return DB_GET_FAILED.into()
             }
 
@@ -336,13 +336,13 @@ pub(crate) fn db_get(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -> i6
             let ret = match db_handle.get(&key) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_get", "Internal error getting from tree: {}", e);
+                    error!(target: "runtime::db::db_init()", "Internal error getting from tree: {}", e);
                     return DB_GET_FAILED.into()
                 }
             };
 
             let Some(return_data) = ret else {
-                debug!("returned empty vec");
+                debug!(target: "runtime::db::db_init()", "returned empty vec");
                 return -127
             };
 
@@ -366,13 +366,13 @@ pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u
             let memory_view = env.memory_view(&ctx);
 
             let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
-                error!(target: "wasm_runtime::db_contains_key", "Failed to make slice from ptr");
+                error!(target: "runtime::db::db_init()", "Failed to make slice from ptr");
                 return DB_CONTAINS_KEY_FAILED
             };
 
             let mut buf = vec![0_u8; len as usize];
             if let Err(e) = mem_slice.read_slice(&mut buf) {
-                error!(target: "wasm_runtime:db_contains_key", "Failed to read from memory slice: {}", e);
+                error!(target: "runtime::db::db_init()", "Failed to read from memory slice: {}", e);
                 return DB_CONTAINS_KEY_FAILED
             };
 
@@ -382,7 +382,7 @@ pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u
             let db_handle: u32 = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_contains_key", "Failed to decode DbHandle: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode DbHandle: {}", e);
                     return DB_CONTAINS_KEY_FAILED
                 }
             };
@@ -391,7 +391,7 @@ pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u
             let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_contains_key", "Failed to decode key vec: {}", e);
+                    error!(target: "runtime::db::db_init()", "Failed to decode key vec: {}", e);
                     return DB_CONTAINS_KEY_FAILED
                 }
             };
@@ -401,7 +401,7 @@ pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u
             let db_handles = env.db_handles.borrow();
 
             if db_handles.len() <= db_handle {
-                error!(target: "wasm_runtime::db_contains_key", "Requested DbHandle that is out of bounds");
+                error!(target: "runtime::db::db_init()", "Requested DbHandle that is out of bounds");
                 return DB_CONTAINS_KEY_FAILED
             }
 
@@ -411,7 +411,7 @@ pub(crate) fn db_contains_key(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u
             match db_handle.contains_key(&key) {
                 Ok(v) => i32::from(v), // <- 0=false, 1=true
                 Err(e) => {
-                    error!(target: "wasm_runtime::db_contains_key", "sled.tree.contains_key failed: {}", e);
+                    error!(target: "runtime::db::db_init()", "sled.tree.contains_key failed: {}", e);
                     DB_CONTAINS_KEY_FAILED
                 }
             }

+ 17 - 17
src/runtime/import/merkle.rs

@@ -37,13 +37,13 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let memory_view = env.memory_view(&ctx);
 
             let Ok(mem_slice) = ptr.slice(&memory_view, len) else {
-                error!(target: "wasm_runtime::merkle_add", "Failed to make slice from ptr");
+                error!(target: "runtime::merkle", "Failed to make slice from ptr");
                 return -2
             };
 
             let mut buf = vec![0_u8; len as usize];
             if let Err(e) = mem_slice.read_slice(&mut buf) {
-                error!(target: "wasm_runtime:merkle_add", "Failed to read from memory slice: {}", e);
+                error!(target: "runtime::merkle", "Failed to read from memory slice: {}", e);
                 return -2
             };
 
@@ -57,7 +57,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let db_info: u32 = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::merkle_add", "Failed to decode db_info DbHandle: {}", e);
+                    error!(target: "runtime::merkle", "Failed to decode db_info DbHandle: {}", e);
                     return -2
                 }
             };
@@ -65,7 +65,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let db_roots: u32 = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::merkle_add", "Failed to decode db_roots DbHandle: {}", e);
+                    error!(target: "runtime::merkle", "Failed to decode db_roots DbHandle: {}", e);
                     return -2
                 }
             };
@@ -78,7 +78,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let n_bat = db_batches.len();
 
             if n_dbs <= db_info || n_bat <= db_info || n_dbs <= db_roots || n_bat <= db_roots {
-                error!(target: "wasm_runtime::merkle_add", "Requested DbHandle that is out of bounds");
+                error!(target: "runtime::merkle", "Requested DbHandle that is out of bounds");
                 return -2
             }
 
@@ -89,7 +89,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let db_roots = &db_handles[roots_handle_idx];
 
             if db_info.contract_id != env.contract_id || db_roots.contract_id != env.contract_id {
-                error!(target: "wasm_runtime::merkle_add", "Unauthorized to write to DbHandle");
+                error!(target: "runtime::merkle", "Unauthorized to write to DbHandle");
                 return -2
             }
 
@@ -97,7 +97,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let key: Vec<u8> = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::merkle_add", "Failed to decode key vec: {}", e);
+                    error!(target: "runtime::merkle", "Failed to decode key vec: {}", e);
                     return -2
                 }
             };
@@ -106,7 +106,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let coins: Vec<MerkleNode> = match Decodable::decode(&mut buf_reader) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::merkle_add", "Failed to decode MerkleNode: {}", e);
+                    error!(target: "runtime::merkle", "Failed to decode MerkleNode: {}", e);
                     return -2
                 }
             };
@@ -117,23 +117,23 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let ret = match db_info.get(&key) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::merkle_add", "Internal error getting from tree: {}", e);
+                    error!(target: "runtime::merkle", "Internal error getting from tree: {}", e);
                     return -2
                 }
             };
 
             let Some(return_data) = ret else {
-                error!(target: "wasm_runtime::merkle_add", "Return data is empty");
+                error!(target: "runtime::merkle", "Return data is empty");
                 return -2
             };
 
             debug!(
-                target: "wasm_runtime::merkle_add",
+                target: "runtime::merkle",
                 "Serialized tree: {} bytes",
                 return_data.len()
             );
             debug!(
-                target: "wasm_runtime::merkle_add",
+                target: "runtime::merkle",
                 "                 {:02x?}",
                 return_data
             );
@@ -143,7 +143,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let set_size: u32 = match Decodable::decode(&mut decoder) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::merkle_add", "Unable to read set size: {}", e);
+                    error!(target: "runtime::merkle", "Unable to read set size: {}", e);
                     return -2
                 }
             };
@@ -151,7 +151,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             let mut tree: MerkleTree = match Decodable::decode(&mut decoder) {
                 Ok(v) => v,
                 Err(e) => {
-                    error!(target: "wasm_runtime::merkle_add", "Unable to deserialize tree: {}", e);
+                    error!(target: "runtime::merkle", "Unable to deserialize tree: {}", e);
                     return -2
                 }
             };
@@ -162,7 +162,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             for coin in coins {
                 tree.append(&coin);
                 let Some(root) = tree.root(0) else {
-                    error!(target: "wasm_runtime::merkle_add", "Unable to read the root of tree");
+                    error!(target: "runtime::merkle", "Unable to read the root of tree");
                     return -2;
                 };
                 new_roots.push(root);
@@ -173,7 +173,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
             if tree_data.write_u32(set_size + new_roots.len() as u32).is_err() ||
                 tree.encode(&mut tree_data).is_err()
             {
-                error!(target: "wasm_runtime::merkle_add", "Couldn't reserialize modified tree");
+                error!(target: "runtime::merkle", "Couldn't reserialize modified tree");
                 return -2
             }
             let db_info_batch = &mut db_batches[info_handle_idx];
@@ -186,7 +186,7 @@ pub(crate) fn merkle_add(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) -
                 // FIXME: Why were we writing the set size here?
                 //let root_index: Vec<u8> = serialize(&(set_size as u32));
                 //assert_eq!(root_index.len(), 4);
-                debug!(target: "wasm_runtime::merkle_add", "Appending Merkle root to db: {:?}", root);
+                debug!(target: "runtime::merkle", "Appending Merkle root to db: {:?}", root);
                 let root_value: Vec<u8> = serialize(root);
                 // FIXME: This assert can be used to DoS nodes from contracts
                 assert_eq!(root_value.len(), 32);

+ 12 - 12
src/runtime/import/util.rs

@@ -34,7 +34,7 @@ pub(crate) fn drk_log(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len: u32) {
             std::mem::drop(logs);
         }
         Err(_) => {
-            error!(target: "wasm_runtime::drk_log", "Failed to read UTF-8 string from VM memory");
+            error!(target: "runtime::util", "Failed to read UTF-8 string from VM memory");
         }
     }
 }
@@ -68,18 +68,18 @@ pub(crate) fn put_object_bytes(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len:
     let env = ctx.data();
     let memory_view = env.memory_view(&ctx);
 
-    //debug!(target: "wasm_runtime::diagnostic", "diagnostic:");
+    //debug!(target: "runtime::util", "diagnostic:");
     //let pages = memory_view.size().0;
-    //debug!(target: "wasm_runtime::diagnostic", "    pages: {}", pages);
+    //debug!(target: "runtime::util", "    pages: {}", pages);
 
     let Ok(slice) = ptr.slice(&memory_view, len) else {
-        error!(target: "wasm_runtime::diagnostic", "Failed to make slice from ptr");
+        error!(target: "runtime::util", "Failed to make slice from ptr");
         return -2
     };
 
     let mut buf = vec![0_u8; len as usize];
     if let Err(e) = slice.read_slice(&mut buf) {
-        error!(target: "wasm_runtime::diagnostic", "Failed to read from memory slice: {}", e);
+        error!(target: "runtime::util", "Failed to read from memory slice: {}", e);
         return -2
     };
 
@@ -87,10 +87,10 @@ pub(crate) fn put_object_bytes(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, len:
     // The number of pages is calculated as a quantity X + 1 where X >= 0
     //assert!(pages > 0);
 
-    //debug!(target: "wasm_runtime::diagnostic", "    memory: {:02x?}", &buf[0..32]);
-    //debug!(target: "wasm_runtime::diagnostic", "            {:x?}", &buf[32..64]);
+    //debug!(target: "runtime::util", "    memory: {:02x?}", &buf[0..32]);
+    //debug!(target: "runtime::util", "            {:x?}", &buf[32..64]);
 
-    //debug!(target: "wasm_runtime::diagnostic", "    ptr location: {}", ptr.offset());
+    //debug!(target: "runtime::util", "    ptr location: {}", ptr.offset());
 
     let mut objects = env.objects.borrow_mut();
     objects.push(buf);
@@ -109,7 +109,7 @@ pub(crate) fn get_object_bytes(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, idx:
 
     let objects = env.objects.borrow();
     if idx as usize >= objects.len() {
-        error!(target: "wasm_runtime::get_object_bytes", "Tried to access object out of bounds");
+        error!(target: "runtime::util", "Tried to access object out of bounds");
         return -5
     }
     let obj = &objects[idx as usize];
@@ -118,13 +118,13 @@ pub(crate) fn get_object_bytes(ctx: FunctionEnvMut<Env>, ptr: WasmPtr<u8>, idx:
 
     // We need to re-read the slice, since in the first run, we just read n
     let Ok(slice) = ptr.slice(&memory_view, obj.len() as u32) else {
-        error!(target: "wasm_runtime::get_object_bytes", "Failed to make slice from ptr");
+        error!(target: "runtime::util", "Failed to make slice from ptr");
         return -2
     };
 
     // Put the result in the VM
     if let Err(e) = slice.write_slice(obj) {
-        error!(target: "wasm_runtime::get_object_bytes", "Failed to write to memory slice: {}", e);
+        error!(target: "runtime::util", "Failed to write to memory slice: {}", e);
         return -4
     };
 
@@ -141,7 +141,7 @@ pub(crate) fn get_object_size(ctx: FunctionEnvMut<Env>, idx: u32) -> i64 {
 
     let objects = env.objects.borrow();
     if idx as usize >= objects.len() {
-        error!(target: "wasm_runtime::get_object_bytes", "Tried to access object out of bounds");
+        error!(target: "runtime::util", "Tried to access object out of bounds");
         return -5
     }
 

+ 17 - 17
src/runtime/vm_runtime.rs

@@ -120,7 +120,7 @@ pub struct Runtime {
 impl Runtime {
     /// Create a new wasm runtime instance that contains the given wasm module.
     pub fn new(wasm_bytes: &[u8], blockchain: Blockchain, contract_id: ContractId) -> Result<Self> {
-        info!(target: "wasm_runtime::new", "Instantiating a new runtime");
+        info!(target: "runtime::vm_runtime", "Instantiating a new runtime");
         // This function will be called for each `Operator` encountered during
         // the wasm module execution. It should return the cost of the operator
         // that it received as its first argument.
@@ -144,7 +144,7 @@ impl Runtime {
         compiler_config.push_middleware(metering);
         let mut store = Store::new(compiler_config);
 
-        debug!(target: "wasm_runtime::new", "Compiling module");
+        debug!(target: "runtime::vm_runtime", "Compiling module");
         let module = Module::new(&store, wasm_bytes)?;
 
         // Initialize data
@@ -152,7 +152,7 @@ impl Runtime {
         let db_batches = RefCell::new(vec![]);
         let logs = RefCell::new(vec![]);
 
-        debug!(target: "wasm_runtime::new", "Importing functions");
+        debug!(target: "runtime::vm_runtime", "Importing functions");
 
         let ctx = FunctionEnv::new(
             &mut store,
@@ -240,7 +240,7 @@ impl Runtime {
             }
         };
 
-        debug!(target: "wasm_runtime::new", "Instantiating module");
+        debug!(target: "runtime::vm_runtime", "Instantiating module");
         let instance = Instance::new(&mut store, &module, &imports)?;
 
         let mut env_mut = ctx.as_mut(&mut store);
@@ -250,7 +250,7 @@ impl Runtime {
     }
 
     fn call(&mut self, section: ContractSection, payload: &[u8]) -> Result<Vec<u8>> {
-        debug!(target: "runtime", "Calling {} method", section.name());
+        debug!(target: "runtime::vm_runtime", "Calling {} method", section.name());
 
         let mut env_mut = self.ctx.as_mut(&mut self.store);
         env_mut.contract_section = section;
@@ -267,27 +267,27 @@ impl Runtime {
         self.set_memory_page_size(pages_required as u32)?;
         self.copy_to_memory(&payload)?;
 
-        debug!(target: "runtime", "Getting {} function", section.name());
+        debug!(target: "runtime::vm_runtime", "Getting {} function", section.name());
         let entrypoint = self.instance.exports.get_function(section.name())?;
 
-        debug!(target: "runtime", "Executing wasm");
+        debug!(target: "runtime::vm_runtime", "Executing wasm");
         let ret = match entrypoint.call(&mut self.store, &[Value::I32(0_i32)]) {
             Ok(retvals) => {
                 self.print_logs();
-                debug!(target: "runtime", "{}", self.gas_info());
+                debug!(target: "runtime::vm_runtime", "{}", self.gas_info());
                 retvals
             }
             Err(e) => {
                 self.print_logs();
-                debug!(target: "runtime", "{}", self.gas_info());
+                debug!(target: "runtime::vm_runtime", "{}", self.gas_info());
                 // WasmerRuntimeError panics are handled here. Return from run() immediately.
-                error!("Wasmer Runtime Error: {:#?}", e);
+                error!(target: "runtime::vm_runtime", "Wasmer Runtime Error: {:#?}", e);
                 return Err(e.into())
             }
         };
 
-        debug!(target: "runtime", "wasm executed successfully");
-        debug!(target: "runtime", "Contract returned: {:?}", ret[0]);
+        debug!(target: "runtime::vm_runtime", "wasm executed successfully");
+        debug!(target: "runtime::vm_runtime", "Contract returned: {:?}", ret[0]);
 
         let mut env_mut = self.ctx.as_mut(&mut self.store);
         env_mut.contract_section = ContractSection::Null;
@@ -321,8 +321,8 @@ impl Runtime {
     /// The permissions for this are handled by the `ContractId` in the sled db API so we
     /// assume that the contract is only able to do write operations on its own sled trees.
     pub fn deploy(&mut self, payload: &[u8]) -> Result<()> {
-        info!("[wasm-runtime] Running deploy");
-        debug!("[wasm-runtime] payload: {:?}", payload);
+        info!(target: "runtime::vm_runtime", "[wasm-runtime] Running deploy");
+        debug!(target: "runtime::vm_runtime", "[wasm-runtime] payload: {:?}", payload);
         let _ = self.call(ContractSection::Deploy, payload)?;
 
         // If the above didn't fail, we write the batches.
@@ -345,7 +345,7 @@ impl Runtime {
     /// execute it if found. A payload is also passed as an instruction that can
     /// be used inside the vm by the runtime.
     pub fn exec(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
-        debug!("exec: {:?}", payload);
+        debug!(target: "runtime::vm_runtime", "exec: {:?}", payload);
         self.call(ContractSection::Exec, payload)
     }
 
@@ -355,7 +355,7 @@ impl Runtime {
     /// it if found. The function does not take an arbitrary payload, but just takes
     /// a state update from `env` and passes it into the wasm runtime.
     pub fn apply(&mut self, update: &[u8]) -> Result<()> {
-        debug!("apply: {:?}", update);
+        debug!(target: "runtime::vm_runtime", "apply: {:?}", update);
         let _ = self.call(ContractSection::Update, update)?;
 
         // If the above didn't fail, we write the batches.
@@ -377,7 +377,7 @@ impl Runtime {
     fn print_logs(&self) {
         let logs = self.ctx.as_ref(&self.store).logs.borrow();
         for msg in logs.iter() {
-            debug!(target: "runtime", "Contract log: {}", msg);
+            debug!(target: "runtime::vm_runtime", "Contract log: {}", msg);
         }
     }
 

+ 1 - 0
src/sdk/src/crypto/constants/load.rs

@@ -271,3 +271,4 @@ impl From<[[[u8; 32]; H]; NUM_WINDOWS_SHORT]> for UShort {
         windows.into()
     }
 }
+

+ 2 - 2
src/system/subscriber.rs

@@ -86,7 +86,7 @@ impl<T: Clone> Subscriber<T> {
     pub async fn notify(&self, message_result: T) {
         for sub in (*self.subs.lock().await).values() {
             if let Err(e) = sub.send(message_result.clone()).await {
-                warn!("Error returned sending message in notify() call! {}", e);
+                warn!(target: "system::subscriber", "Error returned sending message in notify() call! {}", e);
             }
         }
     }
@@ -98,7 +98,7 @@ impl<T: Clone> Subscriber<T> {
             }
 
             if let Err(e) = sub.send(message_result.clone()).await {
-                warn!("Error returned sending message in notify_with_exclude() call! {}", e);
+                warn!(target: "system::subscriber", "Error returned sending message in notify_with_exclude() call! {}", e);
             }
         }
     }

+ 10 - 9
src/tx/mod.rs

@@ -75,21 +75,22 @@ impl Transaction {
                 if let Some(vks) = verifying_keys.read().await.get(&call.contract_id.to_bytes()) {
                     if let Some(vk) = vks.iter().find(|x| &x.0 == zk_ns) {
                         // We have a verifying key for this
-                        debug!("public inputs: {:#?}", public_vals);
+                        debug!(target: "", "public inputs: {:#?}", public_vals);
                         if let Err(e) = proof.verify(&vk.1, public_vals) {
                             error!(
+                                target: "",
                                 "Failed verifying {}::{} ZK proof: {:#?}",
                                 call.contract_id, zk_ns, e
                             );
                             return Err(VerifyFailed::ProofVerifyFailed(e.to_string()).into())
                         }
-                        debug!("Successfully verified {}::{} ZK proof", call.contract_id, zk_ns);
+                        debug!(target: "", "Successfully verified {}::{} ZK proof", call.contract_id, zk_ns);
                         continue
                     }
                 }
 
                 let e = format!("{}:{} circuit VK nonexistent", call.contract_id, zk_ns);
-                error!("{}", e);
+                error!(target: "", "{}", e);
                 return Err(VerifyFailed::ProofVerifyFailed(e).into())
             }
         }
@@ -101,19 +102,19 @@ impl Transaction {
     pub fn verify_sigs(&self, pub_table: Vec<Vec<PublicKey>>) -> Result<()> {
         let tx_data = self.encode_without_sigs()?;
         let data_hash = blake3::hash(&tx_data);
-        debug!("tx.verify_sigs: data_hash: {:?}", data_hash.as_bytes());
+        debug!(target: "", "tx.verify_sigs: data_hash: {:?}", data_hash.as_bytes());
 
         assert!(pub_table.len() == self.signatures.len());
 
         for (i, (sigs, pubkeys)) in self.signatures.iter().zip(pub_table.iter()).enumerate() {
             for (pubkey, signature) in pubkeys.iter().zip(sigs) {
-                debug!("Verifying signature with public key: {}", pubkey);
+                debug!(target: "", "Verifying signature with public key: {}", pubkey);
                 if !pubkey.verify(&data_hash.as_bytes()[..], signature) {
-                    error!("tx::verify_sigs[{}] failed to verify", i);
+                    error!(target: "", "tx::verify_sigs[{}] failed to verify", i);
                     return Err(Error::InvalidSignature)
                 }
             }
-            debug!("tx::verify_sigs[{}] passed", i);
+            debug!(target: "", "tx::verify_sigs[{}] passed", i);
         }
 
         Ok(())
@@ -127,11 +128,11 @@ impl Transaction {
     ) -> Result<Vec<Signature>> {
         let tx_data = self.encode_without_sigs()?;
         let data_hash = blake3::hash(&tx_data);
-        debug!("tx.create_sigs: data_hash: {:?}", data_hash.as_bytes());
+        debug!(target: "", "tx.create_sigs: data_hash: {:?}", data_hash.as_bytes());
 
         let mut sigs = vec![];
         for secret in secret_keys {
-            debug!("Creating signature with public key: {}", PublicKey::from_secret(*secret));
+            debug!(target: "", "Creating signature with public key: {}", PublicKey::from_secret(*secret));
             let signature = secret.sign(rng, &data_hash.as_bytes()[..]);
             sigs.push(signature);
         }

+ 24 - 23
src/wallet/cashierdb.rs

@@ -67,16 +67,16 @@ pub struct CashierDb {
 
 impl CashierDb {
     pub async fn new(path: &str, password: &str) -> Result<CashierDbPtr> {
-        debug!("new() Constructor called");
+        debug!(target: "wallet::cashierdb", "new() Constructor called");
         if password.trim().is_empty() {
-            error!("Password is empty. You must set a password to use the wallet.");
+            error!(target: "wallet::cashierdb", "Password is empty. You must set a password to use the wallet.");
             return Err(WalletEmptyPassword)
         }
 
         if path != "sqlite::memory:" {
             let p = Path::new(path.strip_prefix("sqlite://").unwrap());
             if let Some(dirname) = p.parent() {
-                info!("Creating path to database: {}", dirname.display());
+                info!(target: "wallet::cashierdb", "Creating path to database: {}", dirname.display());
                 create_dir_all(&dirname)?;
             }
         }
@@ -91,7 +91,7 @@ impl CashierDb {
 
         let conn = SqlitePoolOptions::new().connect_with(connect_opts).await?;
 
-        info!("Opened connection at path: {:?}", path);
+        info!(target: "wallet::cashierdb", "Opened connection at path: {:?}", path);
         Ok(Arc::new(CashierDb { conn }))
     }
 
@@ -102,24 +102,24 @@ impl CashierDb {
 
         let mut conn = self.conn.acquire().await?;
 
-        debug!("Initializing main keypairs table");
+        debug!(target: "wallet::cashierdb", "Initializing main keypairs table");
         sqlx::query(main_kps).execute(&mut conn).await?;
 
-        debug!("Initializing deposit keypairs table");
+        debug!(target: "wallet::cashierdb", "Initializing deposit keypairs table");
         sqlx::query(deposit_kps).execute(&mut conn).await?;
 
-        debug!("Initializing withdraw keypairs table");
+        debug!(target: "wallet::cashierdb", "Initializing withdraw keypairs table");
         sqlx::query(withdraw_kps).execute(&mut conn).await?;
         Ok(())
     }
 
     pub async fn tree_gen(&self) -> Result<()> {
-        debug!("Attempting to generate merkle tree");
+        debug!(target: "wallet::cashierdb", "Attempting to generate merkle tree");
         let mut conn = self.conn.acquire().await?;
 
         match sqlx::query("SELECT * FROM tree").fetch_one(&mut conn).await {
             Ok(_) => {
-                error!("Merkle tree already exists");
+                error!(target: "wallet::cashierdb", "Merkle tree already exists");
                 Err(WalletTreeExists)
             }
             Err(_) => {
@@ -131,7 +131,7 @@ impl CashierDb {
     }
 
     pub async fn get_tree(&self) -> Result<BridgeTree<MerkleNode, 32>> {
-        debug!("Getting merkle tree");
+        debug!(target: "wallet::cashierdb", "Getting merkle tree");
         let mut conn = self.conn.acquire().await?;
 
         let row = sqlx::query("SELECT tree FROM tree").fetch_one(&mut conn).await?;
@@ -140,7 +140,7 @@ impl CashierDb {
     }
 
     pub async fn put_tree(&self, tree: &BridgeTree<MerkleNode, 32>) -> Result<()> {
-        debug!("Attempting to write merkle tree");
+        debug!(target: "wallet::cashierdb", "Attempting to write merkle tree");
         let mut conn = self.conn.acquire().await?;
 
         let tree_bytes = bincode::serialize(tree)?;
@@ -153,7 +153,7 @@ impl CashierDb {
     }
 
     pub async fn put_main_keys(&self, token_key: &TokenKey, network: &NetworkName) -> Result<()> {
-        debug!("Writing main keys into the database");
+        debug!(target: "wallet::cashierdb", "Writing main keys into the database");
         let network = serialize(network);
 
         let mut conn = self.conn.acquire().await?;
@@ -173,7 +173,7 @@ impl CashierDb {
     }
 
     pub async fn get_main_keys(&self, network: &NetworkName) -> Result<Vec<TokenKey>> {
-        debug!("Returning main keypairs");
+        debug!(target: "wallet::cashierdb", "Returning main keypairs");
         let network = serialize(network);
 
         let mut conn = self.conn.acquire().await?;
@@ -197,7 +197,7 @@ impl CashierDb {
     }
 
     pub async fn remove_withdraw_and_deposit_keys(&self) -> Result<()> {
-        debug!("Removing withdraw and deposit keys");
+        debug!(target: "wallet::cashierdb", "Removing withdraw and deposit keys");
         let mut conn = self.conn.acquire().await?;
         sqlx::query("DROP TABLE deposit_keypairs;").execute(&mut conn).await?;
         sqlx::query("DROP TABLE withdraw_keypairs;").execute(&mut conn).await?;
@@ -214,7 +214,7 @@ impl CashierDb {
         token_id: TokenId,
         mint_address: String,
     ) -> Result<()> {
-        debug!("Writing withdraw keys to database");
+        debug!(target: "wallet::cashierdb", "Writing withdraw keys to database");
         let public = serialize(d_key_public);
         let secret = serialize(d_key_secret);
         let network = serialize(network);
@@ -252,7 +252,7 @@ impl CashierDb {
         token_id: TokenId,
         mint_address: String,
     ) -> Result<()> {
-        debug!("Writing deposit keys to database");
+        debug!(target: "wallet::cashierdb", "Writing deposit keys to database");
         let d_key_public = serialize(d_key_public);
         let token_id = serialize(token_id);
         let network = serialize(network);
@@ -281,7 +281,7 @@ impl CashierDb {
     }
 
     pub async fn get_withdraw_private_keys(&self) -> Result<Vec<SecretKey>> {
-        debug!("Getting withdraw private keys");
+        debug!(target: "wallet::cashierdb", "Getting withdraw private keys");
         let confirm = serialize(&false);
 
         let mut conn = self.conn.acquire().await?;
@@ -306,7 +306,7 @@ impl CashierDb {
         &self,
         pubkey: &PublicKey,
     ) -> Result<Option<WithdrawToken>> {
-        debug!("Get token address by pubkey");
+        debug!(target: "wallet::cashierdb", "Get token address by pubkey");
         let d_key_public = serialize(pubkey);
         let confirm = serialize(&false);
 
@@ -340,7 +340,7 @@ impl CashierDb {
         d_key_public: &PublicKey,
         network: &NetworkName,
     ) -> Result<Vec<TokenKey>> {
-        debug!("Checking for existing dkey");
+        debug!(target: "wallet::cashierdb", "Checking for existing dkey");
         let d_key_public = serialize(d_key_public);
         let network = serialize(network);
         let confirm = serialize(&false);
@@ -374,7 +374,7 @@ impl CashierDb {
         token_key_public: &[u8],
         network: &NetworkName,
     ) -> Result<Option<Keypair>> {
-        debug!("Checking for existing token address");
+        debug!(target: "wallet::cashierdb", "Checking for existing token address");
         let confirm = serialize(&false);
         let network = serialize(network);
 
@@ -406,7 +406,7 @@ impl CashierDb {
         token_address: &[u8],
         network: &NetworkName,
     ) -> Result<()> {
-        debug!("Confirm withdraw keys");
+        debug!(target: "wallet::cashierdb", "Confirm withdraw keys");
         let network = serialize(network);
         let confirm = serialize(&true);
 
@@ -431,7 +431,7 @@ impl CashierDb {
         d_key_public: &PublicKey,
         network: &NetworkName,
     ) -> Result<()> {
-        debug!("Confirm deposit keys");
+        debug!(target: "wallet::cashierdb", "Confirm deposit keys");
         let network = serialize(network);
         let confirm = serialize(&true);
         let d_key_public = serialize(d_key_public);
@@ -456,7 +456,7 @@ impl CashierDb {
         &self,
         network: &NetworkName,
     ) -> Result<Vec<DepositToken>> {
-        debug!("Checking for existing dkey");
+        debug!(target: "wallet::cashierdb", "Checking for existing dkey");
         let network = serialize(network);
         let confirm = serialize(&false);
 
@@ -590,3 +590,4 @@ mod tests {
         Ok(())
     }
 }
+

+ 5 - 5
src/wallet/walletdb.rs

@@ -67,14 +67,14 @@ pub struct WalletDb {
 impl WalletDb {
     pub async fn new(path: &str, password: &str) -> Result<WalletPtr> {
         if password.trim().is_empty() {
-            error!("Wallet password is empty. You must set a password to use the wallet.");
+            error!(target: "wallet::walletdb", "Wallet password is empty. You must set a password to use the wallet.");
             return Err(Error::WalletEmptyPassword)
         }
 
         if path != "sqlite::memory:" {
             let p = Path::new(path.strip_prefix("sqlite://").unwrap());
             if let Some(dirname) = p.parent() {
-                info!("Creating path to wallet database: {}", dirname.display());
+                info!(target: "wallet::walletdb", "Creating path to wallet database: {}", dirname.display());
                 create_dir_all(&dirname).await?;
             }
         }
@@ -89,15 +89,15 @@ impl WalletDb {
 
         let conn = SqlitePool::connect_with(connect_opts).await?;
 
-        info!("Opened wallet Sqlite connection at path {}", path);
+        info!(target: "wallet::walletdb", "Opened wallet Sqlite connection at path {}", path);
         Ok(Arc::new(WalletDb { conn }))
     }
 
     /// This function executes a given SQL query, but isn't able to return anything.
     /// Therefore it's best to use it for initializing a table or similar things.
     pub async fn exec_sql(&self, query: &str) -> Result<()> {
-        info!("walletdb: Executing SQL query");
-        debug!("\n{}", query);
+        info!(target: "wallet::walletdb", "walletdb: Executing SQL query");
+        debug!(target: "wallet::walletdb", "\n{}", query);
         let mut conn = self.conn.acquire().await?;
         sqlx::query(query).execute(&mut conn).await?;
         Ok(())

+ 54 - 54
src/zk/vm.rs

@@ -287,7 +287,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
         config: Self::Config,
         mut layouter: impl Layouter<pallas::Base>,
     ) -> std::result::Result<(), plonk::Error> {
-        trace!(target: L_TGT, "Entering synthesize()");
+        trace!(target: "zk::vm", "Entering synthesize()");
 
         // ===================
         // VM Setup
@@ -351,7 +351,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
         // Lookup and push constants onto the stack
         for constant in &self.constants {
             trace!(
-                target: L_TGT,
+                target: "zk::vm",
                 "Pushing constant `{}` to stack index {}",
                 constant.as_str(),
                 stack.len()
@@ -374,7 +374,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 _ => {
-                    error!(target: L_TGT, "Invalid constant name: {}", constant.as_str());
+                    error!(target: "zk::vm", "Invalid constant name: {}", constant.as_str());
                     return Err(plonk::Error::Synthesis)
                 }
             }
@@ -387,12 +387,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 LitType::Uint64 => match literal.1.parse::<u64>() {
                     Ok(v) => litstack.push(v),
                     Err(e) => {
-                        error!(target: L_TGT, "Failed converting u64 literal: {}", e);
+                        error!(target: "zk::vm", "Failed converting u64 literal: {}", e);
                         return Err(plonk::Error::Synthesis)
                     }
                 },
                 _ => {
-                    error!(target: L_TGT, "Invalid literal: {:?}", literal);
+                    error!(target: "zk::vm", "Invalid literal: {:?}", literal);
                     return Err(plonk::Error::Synthesis)
                 }
             }
@@ -404,43 +404,43 @@ impl Circuit<pallas::Base> for ZkCircuit {
         for witness in &self.witnesses {
             match witness {
                 Witness::EcPoint(w) => {
-                    trace!(target: L_TGT, "Witnessing EcPoint into circuit");
+                    trace!(target: "zk::vm", "Witnessing EcPoint into circuit");
                     let point = Point::new(
                         ecc_chip.clone(),
                         layouter.namespace(|| "Witness EcPoint"),
                         w.as_ref().map(|cm| cm.to_affine()),
                     )?;
 
-                    trace!(target: L_TGT, "Pushing EcPoint to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing EcPoint to stack index {}", stack.len());
                     stack.push(StackVar::EcPoint(point));
                 }
 
                 Witness::EcNiPoint(w) => {
-                    trace!(target: L_TGT, "Witnessing EcNiPoint into circuit");
+                    trace!(target: "zk::vm", "Witnessing EcNiPoint into circuit");
                     let point = NonIdentityPoint::new(
                         ecc_chip.clone(),
                         layouter.namespace(|| "Witness EcNiPoint"),
                         w.as_ref().map(|cm| cm.to_affine()),
                     )?;
 
-                    trace!(target: L_TGT, "Pushing EcNiPoint to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing EcNiPoint to stack index {}", stack.len());
                     stack.push(StackVar::EcNiPoint(point));
                 }
 
                 Witness::EcFixedPoint(_) => {
-                    error!(target: L_TGT, "Unable to witness EcFixedPoint, this is unimplemented.");
+                    error!(target: "zk::vm", "Unable to witness EcFixedPoint, this is unimplemented.");
                     return Err(plonk::Error::Synthesis)
                 }
 
                 Witness::Base(w) => {
-                    trace!(target: L_TGT, "Witnessing Base into circuit");
+                    trace!(target: "zk::vm", "Witnessing Base into circuit");
                     let base = assign_free_advice(
                         layouter.namespace(|| "Witness Base"),
                         config.advices[0],
                         *w,
                     )?;
 
-                    trace!(target: L_TGT, "Pushing Base to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing Base to stack index {}", stack.len());
                     stack.push(StackVar::Base(base));
                 }
 
@@ -448,26 +448,26 @@ impl Circuit<pallas::Base> for ZkCircuit {
                     // NOTE: Because the type in `halo2_gadgets` does not have a `Clone`
                     //       impl, we push scalars as-is to the stack. They get witnessed
                     //       when they get used.
-                    trace!(target: L_TGT, "Pushing Scalar to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing Scalar to stack index {}", stack.len());
                     stack.push(StackVar::Scalar(*w));
                 }
 
                 Witness::MerklePath(w) => {
-                    trace!(target: L_TGT, "Witnessing MerklePath into circuit");
+                    trace!(target: "zk::vm", "Witnessing MerklePath into circuit");
                     let path: Value<[pallas::Base; MERKLE_DEPTH_ORCHARD]> =
                         w.map(|typed_path| gen_const_array(|i| typed_path[i].inner()));
 
-                    trace!(target: L_TGT, "Pushing MerklePath to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing MerklePath to stack index {}", stack.len());
                     stack.push(StackVar::MerklePath(path));
                 }
 
                 Witness::Uint32(w) => {
-                    trace!(target: L_TGT, "Pushing Uint32 to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing Uint32 to stack index {}", stack.len());
                     stack.push(StackVar::Uint32(*w));
                 }
 
                 Witness::Uint64(w) => {
-                    trace!(target: L_TGT, "Pushing Uint64 to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing Uint64 to stack index {}", stack.len());
                     stack.push(StackVar::Uint64(*w));
                 }
             }
@@ -480,7 +480,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
         for opcode in &self.opcodes {
             match opcode.0 {
                 Opcode::EcAdd => {
-                    trace!(target: L_TGT, "Executing `EcAdd{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `EcAdd{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -491,12 +491,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let ret = lhs.add(layouter.namespace(|| "EcAdd()"), &rhs)?;
 
-                    trace!(target: L_TGT, "Pushing result to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::EcPoint(ret));
                 }
 
                 Opcode::EcMul => {
-                    trace!(target: L_TGT, "Executing `EcMul{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `EcMul{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs: FixedPoint<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -510,12 +510,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let (ret, _) = lhs.mul(layouter.namespace(|| "EcMul()"), rhs)?;
 
-                    trace!(target: L_TGT, "Pushing result to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::EcPoint(ret));
                 }
 
                 Opcode::EcMulVarBase => {
-                    trace!(target: L_TGT, "Executing `EcMulVarBase{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `EcMulVarBase{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs: NonIdentityPoint<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -530,12 +530,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let (ret, _) = lhs.mul(layouter.namespace(|| "EcMulVarBase()"), rhs)?;
 
-                    trace!(target: L_TGT, "Pushing result to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::EcPoint(ret));
                 }
 
                 Opcode::EcMulBase => {
-                    trace!(target: L_TGT, "Executing `EcMulBase{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `EcMulBase{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs: FixedPointBaseField<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -545,12 +545,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let ret = lhs.mul(layouter.namespace(|| "EcMulBase()"), rhs)?;
 
-                    trace!(target: L_TGT, "Pushing result to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::EcPoint(ret));
                 }
 
                 Opcode::EcMulShort => {
-                    trace!(target: L_TGT, "Executing `EcMulShort{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `EcMulShort{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs: FixedPointShort<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -564,12 +564,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let (ret, _) = lhs.mul(layouter.namespace(|| "EcMulShort()"), rhs)?;
 
-                    trace!(target: L_TGT, "Pushing result to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::EcPoint(ret));
                 }
 
                 Opcode::EcGetX => {
-                    trace!(target: L_TGT, "Executing `EcGetX{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `EcGetX{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let point: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -577,12 +577,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let ret = point.inner().x();
 
-                    trace!(target: L_TGT, "Pushing result to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::Base(ret));
                 }
 
                 Opcode::EcGetY => {
-                    trace!(target: L_TGT, "Executing `EcGetY{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `EcGetY{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let point: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -590,12 +590,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let ret = point.inner().y();
 
-                    trace!(target: L_TGT, "Pushing result to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing result to stack index {}", stack.len());
                     stack.push(StackVar::Base(ret));
                 }
 
                 Opcode::PoseidonHash => {
-                    trace!(target: L_TGT, "Executing `PoseidonHash{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `PoseidonHash{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let mut poseidon_message: Vec<AssignedCell<Fp, Fp>> =
@@ -626,7 +626,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                             let $cell: AssignedCell<Fp, Fp> = $output.into();
 
-                            trace!(target: L_TGT, "Pushing hash to stack index {}", stack.len());
+                            trace!(target: "zk::vm", "Pushing hash to stack index {}", stack.len());
                             stack.push(StackVar::Base($cell));
                         };
                     }
@@ -638,7 +638,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                                     poseidon_hash!($num, $a, $b, $c);
                                 })*
                                 _ => {
-                                    error!(target: L_TGT, "Unsupported poseidon hash for {} elements", $args.len());
+                                    error!(target: "zk::vm", "Unsupported poseidon hash for {} elements", $args.len());
                                     return Err(plonk::Error::Synthesis)
                                 }
                             }
@@ -649,7 +649,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 Opcode::MerkleRoot => {
-                    trace!(target: "zkvm", "Executing `MerkleRoot{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `MerkleRoot{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let leaf_pos = stack[args[0].1].clone().into();
@@ -666,12 +666,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
                     let root = merkle_inputs
                         .calculate_root(layouter.namespace(|| "MerkleRoot()"), leaf)?;
 
-                    trace!(target: L_TGT, "Pushing merkle root to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing merkle root to stack index {}", stack.len());
                     stack.push(StackVar::Base(root));
                 }
 
                 Opcode::BaseAdd => {
-                    trace!(target: L_TGT, "Executing `BaseAdd{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `BaseAdd{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs = &stack[args[0].1].clone().into();
@@ -679,12 +679,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let sum = arith_chip.add(layouter.namespace(|| "BaseAdd()"), lhs, rhs)?;
 
-                    trace!(target: L_TGT, "Pushing sum to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing sum to stack index {}", stack.len());
                     stack.push(StackVar::Base(sum));
                 }
 
                 Opcode::BaseMul => {
-                    trace!(target: L_TGT, "Executing `BaseSub{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `BaseSub{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs = &stack[args[0].1].clone().into();
@@ -692,12 +692,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
 
                     let product = arith_chip.mul(layouter.namespace(|| "BaseMul()"), lhs, rhs)?;
 
-                    trace!(target: L_TGT, "Pushing product to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing product to stack index {}", stack.len());
                     stack.push(StackVar::Base(product));
                 }
 
                 Opcode::BaseSub => {
-                    trace!(target: L_TGT, "Executing `BaseSub{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `BaseSub{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs = &stack[args[0].1].clone().into();
@@ -706,12 +706,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
                     let difference =
                         arith_chip.sub(layouter.namespace(|| "BaseSub()"), lhs, rhs)?;
 
-                    trace!(target: L_TGT, "Pushing difference to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing difference to stack index {}", stack.len());
                     stack.push(StackVar::Base(difference));
                 }
 
                 Opcode::WitnessBase => {
-                    trace!(target: L_TGT, "Executing `WitnessBase{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `WitnessBase{:?}` opcode", opcode.1);
                     //let args = &opcode.1;
 
                     let lit = litstack[literals_offset];
@@ -723,12 +723,12 @@ impl Circuit<pallas::Base> for ZkCircuit {
                         Value::known(pallas::Base::from(lit)),
                     )?;
 
-                    trace!(target: L_TGT, "Pushing assignment to stack index {}", stack.len());
+                    trace!(target: "zk::vm", "Pushing assignment to stack index {}", stack.len());
                     stack.push(StackVar::Base(witness));
                 }
 
                 Opcode::RangeCheck => {
-                    trace!(target: L_TGT, "Executing `RangeCheck{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `RangeCheck{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lit = litstack[literals_offset];
@@ -752,14 +752,14 @@ impl Circuit<pallas::Base> for ZkCircuit {
                             )?;
                         }
                         x => {
-                            error!(target: L_TGT, "Unsupported bit-range {} for range_check", x);
+                            error!(target: "zk::vm", "Unsupported bit-range {} for range_check", x);
                             return Err(plonk::Error::Synthesis)
                         }
                     }
                 }
 
                 Opcode::LessThanStrict => {
-                    trace!(target: L_TGT, "Executing `LessThanStrict{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `LessThanStrict{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let a = stack[args[0].1].clone().into();
@@ -775,7 +775,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 Opcode::LessThanLoose => {
-                    trace!(target: L_TGT, "Executing `LessThanLoose{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `LessThanLoose{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let a = stack[args[0].1].clone().into();
@@ -791,7 +791,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 Opcode::BoolCheck => {
-                    trace!(target: L_TGT, "Executing `BoolCheck{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `BoolCheck{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let w = stack[args[0].1].clone().into();
@@ -801,7 +801,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 Opcode::ConstrainEqualBase => {
-                    trace!(target: L_TGT, "Executing `ConstrainEqualBase{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `ConstrainEqualBase{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs: AssignedCell<Fp, Fp> = stack[args[0].1].clone().into();
@@ -814,7 +814,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 Opcode::ConstrainEqualPoint => {
-                    trace!(target: L_TGT, "Executing `ConstrainEqualPoint{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `ConstrainEqualPoint{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let lhs: Point<pallas::Affine, EccChip<OrchardFixedBases>> =
@@ -830,7 +830,7 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 Opcode::ConstrainInstance => {
-                    trace!(target: L_TGT, "Executing `ConstrainInstance{:?}` opcode", opcode.1);
+                    trace!(target: "zk::vm", "Executing `ConstrainInstance{:?}` opcode", opcode.1);
                     let args = &opcode.1;
 
                     let var: AssignedCell<Fp, Fp> = stack[args[0].1].clone().into();
@@ -845,13 +845,13 @@ impl Circuit<pallas::Base> for ZkCircuit {
                 }
 
                 _ => {
-                    error!(target: L_TGT, "Unsupported opcode");
+                    error!(target: "zk::vm", "Unsupported opcode");
                     return Err(plonk::Error::Synthesis)
                 }
             }
         }
 
-        trace!(target: L_TGT, "Exiting synthesize() successfully");
+        trace!(target: "zk::vm", "Exiting synthesize() successfully");
         Ok(())
     }
 }