Browse Source

blockchain: changed block height from u64 to u32

skoupidi 2 năm trước cách đây
mục cha
commit
9f5e6aafc4
34 tập tin đã thay đổi với 150 bổ sung142 xóa
  1. 1 1
      bin/darkfid/genesis_block_localnet
  2. 1 1
      bin/darkfid/genesis_block_mainnet
  3. 1 1
      bin/darkfid/genesis_block_testnet
  4. 1 1
      bin/darkfid/src/proto/protocol_proposal.rs
  5. 2 2
      bin/darkfid/src/proto/protocol_sync.rs
  6. 1 1
      bin/darkfid/src/rpc_blockchain.rs
  7. 2 2
      bin/darkfid/src/task/miner.rs
  8. 2 2
      bin/drk/src/money.rs
  9. 3 3
      bin/drk/src/rpc.rs
  10. 64 64
      src/blockchain/block_store.rs
  11. 4 4
      src/blockchain/header_store.rs
  12. 17 8
      src/blockchain/mod.rs
  13. 4 4
      src/blockchain/tx_store.rs
  14. 1 1
      src/contract/money/src/client/pow_reward_v1.rs
  15. 3 3
      src/contract/money/src/entrypoint/pow_reward_v1.rs
  16. 2 2
      src/contract/test-harness/src/contract_deploy.rs
  17. 2 2
      src/contract/test-harness/src/dao_exec.rs
  18. 2 2
      src/contract/test-harness/src/dao_mint.rs
  19. 3 3
      src/contract/test-harness/src/dao_propose.rs
  20. 3 3
      src/contract/test-harness/src/dao_vote.rs
  21. 2 2
      src/contract/test-harness/src/lib.rs
  22. 2 2
      src/contract/test-harness/src/money_fee.rs
  23. 1 1
      src/contract/test-harness/src/money_genesis_mint.rs
  24. 2 2
      src/contract/test-harness/src/money_otc_swap.rs
  25. 4 4
      src/contract/test-harness/src/money_token.rs
  26. 2 2
      src/contract/test-harness/src/money_transfer.rs
  27. 3 3
      src/error.rs
  28. 2 3
      src/runtime/import/util.rs
  29. 2 2
      src/runtime/vm_runtime.rs
  30. 3 3
      src/sdk/src/blockchain.rs
  31. 1 1
      src/sdk/src/wasm/util.rs
  32. 2 2
      src/validator/consensus.rs
  33. 2 2
      src/validator/mod.rs
  34. 3 3
      src/validator/verification.rs

+ 1 - 1
bin/darkfid/genesis_block_localnet

@@ -1 +1 @@
-AYa7rEMKSzoYLxJbN6SG6cSGu/o02E70pmtKI+XwxiWxAAAAAAAAAAAfq8xlAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAI5SX/BDpM3cjKjfCsHUms/OAh2F68zs3tw48/GJChU8AAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
+AYa7rEMKSzoYLxJbN6SG6cSGu/o02E70pmtKI+XwxiWxAAAAAFDcE2YAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAjlJf8EOkzdyMqN8KwdSaz84CHYXrzOze3Djz8YkKFTwAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

+ 1 - 1
bin/darkfid/genesis_block_mainnet

@@ -1 +1 @@
-AYa7rEMKSzoYLxJbN6SG6cSGu/o02E70pmtKI+XwxiWxAAAAAAAAAAAfq8xlAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAI5SX/BDpM3cjKjfCsHUms/OAh2F68zs3tw48/GJChU8AAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
+AYa7rEMKSzoYLxJbN6SG6cSGu/o02E70pmtKI+XwxiWxAAAAAFDcE2YAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAjlJf8EOkzdyMqN8KwdSaz84CHYXrzOze3Djz8YkKFTwAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

+ 1 - 1
bin/darkfid/genesis_block_testnet

@@ -1 +1 @@
-AYa7rEMKSzoYLxJbN6SG6cSGu/o02E70pmtKI+XwxiWxAAAAAAAAAAAfq8xlAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAI5SX/BDpM3cjKjfCsHUms/OAh2F68zs3tw48/GJChU8AAAAAQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==
+AYa7rEMKSzoYLxJbN6SG6cSGu/o02E70pmtKI+XwxiWxAAAAAFDcE2YAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAjlJf8EOkzdyMqN8KwdSaz84CHYXrzOze3Djz8YkKFTwAAAABAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

+ 1 - 1
bin/darkfid/src/proto/protocol_proposal.rs

@@ -166,7 +166,7 @@ impl ProtocolProposal {
             }
             }
 
 
             // Sequence length must correspond to requested height
             // Sequence length must correspond to requested height
-            if response.proposals.len() as u64 != proposal_copy.0.block.header.height - last.0 {
+            if response.proposals.len() as u32 != proposal_copy.0.block.header.height - last.0 {
                 debug!(target: "darkfid::proto::protocol_proposal::handle_receive_proposal", "Response sequence length is erroneous");
                 debug!(target: "darkfid::proto::protocol_proposal::handle_receive_proposal", "Response sequence length is erroneous");
                 continue
                 continue
             }
             }

+ 2 - 2
bin/darkfid/src/proto/protocol_sync.rs

@@ -35,7 +35,7 @@ use darkfi::{
 use darkfi_serial::{SerialDecodable, SerialEncodable};
 use darkfi_serial::{SerialDecodable, SerialEncodable};
 
 
 // Constant defining how many blocks we send during syncing.
 // Constant defining how many blocks we send during syncing.
-const BATCH: u64 = 10;
+const BATCH: usize = 10;
 
 
 /// Auxiliary structure used for blockchain syncing.
 /// Auxiliary structure used for blockchain syncing.
 #[derive(Debug, SerialEncodable, SerialDecodable)]
 #[derive(Debug, SerialEncodable, SerialDecodable)]
@@ -56,7 +56,7 @@ impl_p2p_message!(IsSyncedResponse, "issyncedresponse");
 #[derive(Debug, SerialEncodable, SerialDecodable)]
 #[derive(Debug, SerialEncodable, SerialDecodable)]
 pub struct SyncRequest {
 pub struct SyncRequest {
     /// Block height
     /// Block height
-    pub height: u64,
+    pub height: u32,
 }
 }
 
 
 impl_p2p_message!(SyncRequest, "syncrequest");
 impl_p2p_message!(SyncRequest, "syncrequest");

+ 1 - 1
bin/darkfid/src/rpc_blockchain.rs

@@ -54,7 +54,7 @@ impl Darkfid {
             return JsonError::new(InvalidParams, None, id).into()
             return JsonError::new(InvalidParams, None, id).into()
         }
         }
 
 
-        let block_height = match params[0].get::<String>().unwrap().parse::<u64>() {
+        let block_height = match params[0].get::<String>().unwrap().parse::<u32>() {
             Ok(v) => v,
             Ok(v) => v,
             Err(_) => return JsonError::new(ParseError, None, id).into(),
             Err(_) => return JsonError::new(ParseError, None, id).into(),
         };
         };

+ 2 - 2
bin/darkfid/src/task/miner.rs

@@ -260,7 +260,7 @@ async fn generate_next_block(
     // Next secret is the poseidon hash of:
     // Next secret is the poseidon hash of:
     //  [prefix, current(previous) secret, signing(block) height].
     //  [prefix, current(previous) secret, signing(block) height].
     let prefix = pallas::Base::from_raw([4, 0, 0, 0]);
     let prefix = pallas::Base::from_raw([4, 0, 0, 0]);
-    let next_secret = poseidon_hash([prefix, secret.inner(), next_block_height.into()]);
+    let next_secret = poseidon_hash([prefix, secret.inner(), (next_block_height as u64).into()]);
     *secret = SecretKey::from(next_secret);
     *secret = SecretKey::from(next_secret);
 
 
     // Generate reward transaction
     // Generate reward transaction
@@ -275,7 +275,7 @@ async fn generate_next_block(
 
 
 /// Auxiliary function to generate a Money::PoWReward transaction
 /// Auxiliary function to generate a Money::PoWReward transaction
 fn generate_transaction(
 fn generate_transaction(
-    block_height: u64,
+    block_height: u32,
     secret: &SecretKey,
     secret: &SecretKey,
     recipient: &PublicKey,
     recipient: &PublicKey,
     zkbin: &ZkBinary,
     zkbin: &ZkBinary,

+ 2 - 2
bin/drk/src/money.rs

@@ -611,7 +611,7 @@ impl Drk {
     }
     }
 
 
     /// Get the last scanned block height from the wallet.
     /// Get the last scanned block height from the wallet.
-    pub async fn last_scanned_block(&self) -> WalletDbResult<u64> {
+    pub async fn last_scanned_block(&self) -> WalletDbResult<u32> {
         let ret = self
         let ret = self
             .wallet
             .wallet
             .query_single(&MONEY_INFO_TABLE, &[MONEY_INFO_COL_LAST_SCANNED_BLOCK], &[])
             .query_single(&MONEY_INFO_TABLE, &[MONEY_INFO_COL_LAST_SCANNED_BLOCK], &[])
@@ -619,7 +619,7 @@ impl Drk {
         let Value::Integer(height) = ret[0] else {
         let Value::Integer(height) = ret[0] else {
             return Err(WalletDbError::ParseColumnValueError);
             return Err(WalletDbError::ParseColumnValueError);
         };
         };
-        let Ok(height) = u64::try_from(height) else {
+        let Ok(height) = u32::try_from(height) else {
             return Err(WalletDbError::ParseColumnValueError);
             return Err(WalletDbError::ParseColumnValueError);
         };
         };
 
 

+ 3 - 3
bin/drk/src/rpc.rs

@@ -54,7 +54,7 @@ impl Drk {
     ) -> Result<()> {
     ) -> Result<()> {
         let req = JsonRequest::new("blockchain.last_known_block", JsonValue::Array(vec![]));
         let req = JsonRequest::new("blockchain.last_known_block", JsonValue::Array(vec![]));
         let rep = self.rpc_client.request(req).await?;
         let rep = self.rpc_client.request(req).await?;
-        let last_known = *rep.get::<f64>().unwrap() as u64;
+        let last_known = *rep.get::<f64>().unwrap() as u32;
         let last_scanned = match self.last_scanned_block().await {
         let last_scanned = match self.last_scanned_block().await {
             Ok(l) => l,
             Ok(l) => l,
             Err(e) => {
             Err(e) => {
@@ -234,7 +234,7 @@ impl Drk {
                     return Err(WalletDbError::GenericError)
                     return Err(WalletDbError::GenericError)
                 }
                 }
             };
             };
-            let last = *rep.get::<f64>().unwrap() as u64;
+            let last = *rep.get::<f64>().unwrap() as u32;
 
 
             println!("Requested to scan from block number: {height}");
             println!("Requested to scan from block number: {height}");
             println!("Last known block number reported by darkfid: {last}");
             println!("Last known block number reported by darkfid: {last}");
@@ -268,7 +268,7 @@ impl Drk {
     }
     }
 
 
     // Queries darkfid for a block with given height
     // Queries darkfid for a block with given height
-    async fn get_block_by_height(&self, height: u64) -> Result<BlockInfo> {
+    async fn get_block_by_height(&self, height: u32) -> Result<BlockInfo> {
         let req = JsonRequest::new(
         let req = JsonRequest::new(
             "blockchain.get_block",
             "blockchain.get_block",
             JsonValue::Array(vec![JsonValue::String(height.to_string())]),
             JsonValue::Array(vec![JsonValue::String(height.to_string())]),

+ 64 - 64
src/blockchain/block_store.rs

@@ -32,7 +32,7 @@ use num_bigint::BigUint;
 
 
 use crate::{tx::Transaction, util::time::Timestamp, Error, Result};
 use crate::{tx::Transaction, util::time::Timestamp, Error, Result};
 
 
-use super::{parse_record, parse_u64_key_record, Header, HeaderHash, SledDbOverlayPtr};
+use super::{parse_record, parse_u32_key_record, Header, HeaderHash, SledDbOverlayPtr};
 
 
 /// This struct represents a tuple of the form (`header`, `txs`, `signature`).
 /// This struct represents a tuple of the form (`header`, `txs`, `signature`).
 /// The header and transactions are stored as hashes, serving as pointers to the actual data
 /// The header and transactions are stored as hashes, serving as pointers to the actual data
@@ -134,9 +134,9 @@ impl BlockInfo {
 /// Auxiliary structure used to keep track of blocks order.
 /// Auxiliary structure used to keep track of blocks order.
 #[derive(Debug, SerialEncodable, SerialDecodable)]
 #[derive(Debug, SerialEncodable, SerialDecodable)]
 pub struct BlockOrder {
 pub struct BlockOrder {
-    /// Order number
-    pub number: u64,
-    /// Block headerhash of that number
+    /// Block height
+    pub height: u32,
+    /// Block header hash of that height
     pub block: HeaderHash,
     pub block: HeaderHash,
 }
 }
 
 
@@ -202,7 +202,7 @@ impl darkfi_serial::Decodable for BlockRanks {
 #[derive(Debug)]
 #[derive(Debug)]
 pub struct BlockDifficulty {
 pub struct BlockDifficulty {
     /// Block height number
     /// Block height number
-    pub height: u64,
+    pub height: u32,
     /// Block creation timestamp
     /// Block creation timestamp
     pub timestamp: Timestamp,
     pub timestamp: Timestamp,
     /// Height difficulty
     /// Height difficulty
@@ -215,7 +215,7 @@ pub struct BlockDifficulty {
 
 
 impl BlockDifficulty {
 impl BlockDifficulty {
     pub fn new(
     pub fn new(
-        height: u64,
+        height: u32,
         timestamp: Timestamp,
         timestamp: Timestamp,
         difficulty: BigUint,
         difficulty: BigUint,
         cummulative_difficulty: BigUint,
         cummulative_difficulty: BigUint,
@@ -232,7 +232,7 @@ impl BlockDifficulty {
             BigUint::from(0u64),
             BigUint::from(0u64),
             BigUint::from(0u64),
             BigUint::from(0u64),
         );
         );
-        BlockDifficulty::new(0, timestamp, BigUint::from(0u64), BigUint::from(0u64), ranks)
+        BlockDifficulty::new(0u32, timestamp, BigUint::from(0u64), BigUint::from(0u64), ranks)
     }
     }
 }
 }
 
 
@@ -252,7 +252,7 @@ impl darkfi_serial::Encodable for BlockDifficulty {
 
 
 impl darkfi_serial::Decodable for BlockDifficulty {
 impl darkfi_serial::Decodable for BlockDifficulty {
     fn decode<D: std::io::Read>(mut d: D) -> std::io::Result<Self> {
     fn decode<D: std::io::Read>(mut d: D) -> std::io::Result<Self> {
-        let height: u64 = darkfi_serial::Decodable::decode(&mut d)?;
+        let height: u32 = darkfi_serial::Decodable::decode(&mut d)?;
         let timestamp: Timestamp = darkfi_serial::Decodable::decode(&mut d)?;
         let timestamp: Timestamp = darkfi_serial::Decodable::decode(&mut d)?;
         let bytes: Vec<u8> = darkfi_serial::Decodable::decode(&mut d)?;
         let bytes: Vec<u8> = darkfi_serial::Decodable::decode(&mut d)?;
         let difficulty: BigUint = BigUint::from_bytes_be(&bytes);
         let difficulty: BigUint = BigUint::from_bytes_be(&bytes);
@@ -276,7 +276,7 @@ pub struct BlockStore {
     /// key is the blocks' hash, and value is the serialized block.
     /// key is the blocks' hash, and value is the serialized block.
     pub main: sled::Tree,
     pub main: sled::Tree,
     /// The `sled` tree storing the order of the blockchain's blocks,
     /// The `sled` tree storing the order of the blockchain's blocks,
-    /// where the key is the order number, and the value is the blocks'
+    /// where the key is the height number, and the value is the blocks'
     /// hash.
     /// hash.
     pub order: sled::Tree,
     pub order: sled::Tree,
     /// The `sled` tree storing the the difficulty information of the
     /// The `sled` tree storing the the difficulty information of the
@@ -301,10 +301,10 @@ impl BlockStore {
         Ok(ret)
         Ok(ret)
     }
     }
 
 
-    /// Insert a slice of `u64` and block hashes into the store's
+    /// Insert a slice of `u32` and block hashes into the store's
     /// order tree.
     /// order tree.
-    pub fn insert_order(&self, order: &[u64], hashes: &[HeaderHash]) -> Result<()> {
-        let batch = self.insert_batch_order(order, hashes);
+    pub fn insert_order(&self, heights: &[u32], hashes: &[HeaderHash]) -> Result<()> {
+        let batch = self.insert_batch_order(heights, hashes);
         self.order.apply_batch(batch)?;
         self.order.apply_batch(batch)?;
         Ok(())
         Ok(())
     }
     }
@@ -337,12 +337,12 @@ impl BlockStore {
 
 
     /// Generate the sled batch corresponding to an insert to the order
     /// Generate the sled batch corresponding to an insert to the order
     /// tree, so caller can handle the write operation.
     /// tree, so caller can handle the write operation.
-    /// The block order number is used as the key, and the block hash is used as value.
-    pub fn insert_batch_order(&self, order: &[u64], hashes: &[HeaderHash]) -> sled::Batch {
+    /// The block height is used as the key, and the block hash is used as value.
+    pub fn insert_batch_order(&self, heights: &[u32], hashes: &[HeaderHash]) -> sled::Batch {
         let mut batch = sled::Batch::default();
         let mut batch = sled::Batch::default();
 
 
-        for (i, number) in order.iter().enumerate() {
-            batch.insert(&number.to_be_bytes(), hashes[i].inner());
+        for (i, height) in heights.iter().enumerate() {
+            batch.insert(&height.to_be_bytes(), hashes[i].inner());
         }
         }
 
 
         batch
         batch
@@ -367,9 +367,9 @@ impl BlockStore {
         Ok(self.main.contains_key(blockhash.inner())?)
         Ok(self.main.contains_key(blockhash.inner())?)
     }
     }
 
 
-    /// Check if the store's order tree contains a given order number.
-    pub fn contains_order(&self, number: u64) -> Result<bool> {
-        Ok(self.order.contains_key(number.to_be_bytes())?)
+    /// Check if the store's order tree contains a given height.
+    pub fn contains_order(&self, height: u32) -> Result<bool> {
+        Ok(self.order.contains_key(height.to_be_bytes())?)
     }
     }
 
 
     /// Fetch given block hashes from the store's main tree.
     /// Fetch given block hashes from the store's main tree.
@@ -395,22 +395,22 @@ impl BlockStore {
         Ok(ret)
         Ok(ret)
     }
     }
 
 
-    /// Fetch given order numbers from the store's order tree.
-    /// The resulting vector contains `Option`, which is `Some` if the number
+    /// Fetch given heights from the store's order tree.
+    /// The resulting vector contains `Option`, which is `Some` if the height
     /// was found in the block order store, and otherwise it is `None`, if it has not.
     /// was found in the block order store, and otherwise it is `None`, if it has not.
     /// The second parameter is a boolean which tells the function to fail in
     /// The second parameter is a boolean which tells the function to fail in
-    /// case at least one order number was not found.
-    pub fn get_order(&self, order: &[u64], strict: bool) -> Result<Vec<Option<HeaderHash>>> {
-        let mut ret = Vec::with_capacity(order.len());
+    /// case at least one height was not found.
+    pub fn get_order(&self, heights: &[u32], strict: bool) -> Result<Vec<Option<HeaderHash>>> {
+        let mut ret = Vec::with_capacity(heights.len());
 
 
-        for number in order {
-            if let Some(found) = self.order.get(number.to_be_bytes())? {
+        for height in heights {
+            if let Some(found) = self.order.get(height.to_be_bytes())? {
                 let block_hash = deserialize(&found)?;
                 let block_hash = deserialize(&found)?;
                 ret.push(Some(block_hash));
                 ret.push(Some(block_hash));
                 continue
                 continue
             }
             }
             if strict {
             if strict {
-                return Err(Error::BlockNumberNotFound(*number))
+                return Err(Error::BlockHeightNotFound(*height))
             }
             }
             ret.push(None);
             ret.push(None);
         }
         }
@@ -426,7 +426,7 @@ impl BlockStore {
     /// case at least one block height number was not found.
     /// case at least one block height number was not found.
     pub fn get_difficulty(
     pub fn get_difficulty(
         &self,
         &self,
-        heights: &[u64],
+        heights: &[u32],
         strict: bool,
         strict: bool,
     ) -> Result<Vec<Option<BlockDifficulty>>> {
     ) -> Result<Vec<Option<BlockDifficulty>>> {
         let mut ret = Vec::with_capacity(heights.len());
         let mut ret = Vec::with_capacity(heights.len());
@@ -460,13 +460,13 @@ impl BlockStore {
     }
     }
 
 
     /// Retrieve complete order from the store's order tree in the form
     /// Retrieve complete order from the store's order tree in the form
-    /// of a vector containing (`number`, `hash`) tuples.
+    /// of a vector containing (`height`, `hash`) tuples.
     /// Be careful as this will try to load everything in memory.
     /// Be careful as this will try to load everything in memory.
-    pub fn get_all_order(&self) -> Result<Vec<(u64, HeaderHash)>> {
+    pub fn get_all_order(&self) -> Result<Vec<(u32, HeaderHash)>> {
         let mut order = vec![];
         let mut order = vec![];
 
 
         for record in self.order.iter() {
         for record in self.order.iter() {
-            order.push(parse_u64_key_record(record.unwrap())?);
+            order.push(parse_u32_key_record(record.unwrap())?);
         }
         }
 
 
         Ok(order)
         Ok(order)
@@ -475,28 +475,28 @@ impl BlockStore {
     /// Retrieve all block difficulties from the store's difficulty tree in
     /// Retrieve all block difficulties from the store's difficulty tree in
     /// the form of a vector containing (`height`, `difficulty`) tuples.
     /// the form of a vector containing (`height`, `difficulty`) tuples.
     /// Be careful as this will try to load everything in memory.
     /// Be careful as this will try to load everything in memory.
-    pub fn get_all_difficulty(&self) -> Result<Vec<(u64, BlockDifficulty)>> {
+    pub fn get_all_difficulty(&self) -> Result<Vec<(u32, BlockDifficulty)>> {
         let mut block_difficulties = vec![];
         let mut block_difficulties = vec![];
 
 
         for record in self.difficulty.iter() {
         for record in self.difficulty.iter() {
-            block_difficulties.push(parse_u64_key_record(record.unwrap())?);
+            block_difficulties.push(parse_u32_key_record(record.unwrap())?);
         }
         }
 
 
         Ok(block_difficulties)
         Ok(block_difficulties)
     }
     }
 
 
-    /// Fetch n hashes after given order number. In the iteration, if an order
-    /// number is not found, the iteration stops and the function returns what
+    /// Fetch n hashes after given height. In the iteration, if an order
+    /// height is not found, the iteration stops and the function returns what
     /// it has found so far in the `BlockOrderStore`.
     /// it has found so far in the `BlockOrderStore`.
-    pub fn get_after(&self, number: u64, n: u64) -> Result<Vec<HeaderHash>> {
+    pub fn get_after(&self, height: u32, n: usize) -> Result<Vec<HeaderHash>> {
         let mut ret = vec![];
         let mut ret = vec![];
 
 
-        let mut key = number;
+        let mut key = height;
         let mut counter = 0;
         let mut counter = 0;
         while counter <= n {
         while counter <= n {
             if let Some(found) = self.order.get_gt(key.to_be_bytes())? {
             if let Some(found) = self.order.get_gt(key.to_be_bytes())? {
-                let (number, hash) = parse_u64_key_record(found)?;
-                key = number;
+                let (height, hash) = parse_u32_key_record(found)?;
+                key = height;
                 ret.push(hash);
                 ret.push(hash);
                 counter += 1;
                 counter += 1;
                 continue
                 continue
@@ -509,23 +509,23 @@ impl BlockStore {
 
 
     /// Fetch the first block hash in the order tree, based on the `Ord`
     /// Fetch the first block hash in the order tree, based on the `Ord`
     /// implementation for `Vec<u8>`.
     /// implementation for `Vec<u8>`.
-    pub fn get_first(&self) -> Result<(u64, HeaderHash)> {
+    pub fn get_first(&self) -> Result<(u32, HeaderHash)> {
         let found = match self.order.first()? {
         let found = match self.order.first()? {
             Some(s) => s,
             Some(s) => s,
-            None => return Err(Error::BlockNumberNotFound(0)),
+            None => return Err(Error::BlockHeightNotFound(0u32)),
         };
         };
-        let (number, hash) = parse_u64_key_record(found)?;
+        let (height, hash) = parse_u32_key_record(found)?;
 
 
-        Ok((number, hash))
+        Ok((height, hash))
     }
     }
 
 
     /// Fetch the last block hash in the order tree, based on the `Ord`
     /// Fetch the last block hash in the order tree, based on the `Ord`
     /// implementation for `Vec<u8>`.
     /// implementation for `Vec<u8>`.
-    pub fn get_last(&self) -> Result<(u64, HeaderHash)> {
+    pub fn get_last(&self) -> Result<(u32, HeaderHash)> {
         let found = self.order.last()?.unwrap();
         let found = self.order.last()?.unwrap();
-        let (number, hash) = parse_u64_key_record(found)?;
+        let (height, hash) = parse_u32_key_record(found)?;
 
 
-        Ok((number, hash))
+        Ok((height, hash))
     }
     }
 
 
     /// Fetch the last record in the difficulty tree, based on the `Ord`
     /// Fetch the last record in the difficulty tree, based on the `Ord`
@@ -590,17 +590,17 @@ impl BlockStoreOverlay {
         Ok(ret)
         Ok(ret)
     }
     }
 
 
-    /// Insert a slice of `u64` and block hashes into overlay's order tree.
-    /// The block order number is used as the key, and the blockhash is used as value.
-    pub fn insert_order(&self, order: &[u64], hashes: &[HeaderHash]) -> Result<()> {
-        if order.len() != hashes.len() {
+    /// Insert a slice of `u32` and block hashes into overlay's order tree.
+    /// The block height is used as the key, and the blockhash is used as value.
+    pub fn insert_order(&self, heights: &[u32], hashes: &[HeaderHash]) -> Result<()> {
+        if heights.len() != hashes.len() {
             return Err(Error::InvalidInputLengths)
             return Err(Error::InvalidInputLengths)
         }
         }
 
 
         let mut lock = self.0.lock().unwrap();
         let mut lock = self.0.lock().unwrap();
 
 
-        for (i, number) in order.iter().enumerate() {
-            lock.insert(SLED_BLOCK_ORDER_TREE, &number.to_be_bytes(), hashes[i].inner())?;
+        for (i, height) in heights.iter().enumerate() {
+            lock.insert(SLED_BLOCK_ORDER_TREE, &height.to_be_bytes(), hashes[i].inner())?;
         }
         }
 
 
         Ok(())
         Ok(())
@@ -645,23 +645,23 @@ impl BlockStoreOverlay {
         Ok(ret)
         Ok(ret)
     }
     }
 
 
-    /// Fetch given order numbers from the overlay's order tree.
-    /// The resulting vector contains `Option`, which is `Some` if the number
+    /// Fetch given heights from the overlay's order tree.
+    /// The resulting vector contains `Option`, which is `Some` if the height
     /// was found in the overlay, and otherwise it is `None`, if it has not.
     /// was found in the overlay, and otherwise it is `None`, if it has not.
     /// The second parameter is a boolean which tells the function to fail in
     /// The second parameter is a boolean which tells the function to fail in
-    /// case at least one number was not found.
-    pub fn get_order(&self, order: &[u64], strict: bool) -> Result<Vec<Option<HeaderHash>>> {
-        let mut ret = Vec::with_capacity(order.len());
+    /// case at least one height was not found.
+    pub fn get_order(&self, heights: &[u32], strict: bool) -> Result<Vec<Option<HeaderHash>>> {
+        let mut ret = Vec::with_capacity(heights.len());
         let lock = self.0.lock().unwrap();
         let lock = self.0.lock().unwrap();
 
 
-        for number in order {
-            if let Some(found) = lock.get(SLED_BLOCK_ORDER_TREE, &number.to_be_bytes())? {
+        for height in heights {
+            if let Some(found) = lock.get(SLED_BLOCK_ORDER_TREE, &height.to_be_bytes())? {
                 let block_hash = deserialize(&found)?;
                 let block_hash = deserialize(&found)?;
                 ret.push(Some(block_hash));
                 ret.push(Some(block_hash));
                 continue
                 continue
             }
             }
             if strict {
             if strict {
-                return Err(Error::BlockNumberNotFound(*number))
+                return Err(Error::BlockHeightNotFound(*height))
             }
             }
             ret.push(None);
             ret.push(None);
         }
         }
@@ -671,14 +671,14 @@ impl BlockStoreOverlay {
 
 
     /// Fetch the last block hash in the overlay's order tree, based on the `Ord`
     /// Fetch the last block hash in the overlay's order tree, based on the `Ord`
     /// implementation for `Vec<u8>`.
     /// implementation for `Vec<u8>`.
-    pub fn get_last(&self) -> Result<(u64, HeaderHash)> {
+    pub fn get_last(&self) -> Result<(u32, HeaderHash)> {
         let found = match self.0.lock().unwrap().last(SLED_BLOCK_ORDER_TREE)? {
         let found = match self.0.lock().unwrap().last(SLED_BLOCK_ORDER_TREE)? {
             Some(b) => b,
             Some(b) => b,
-            None => return Err(Error::BlockNumberNotFound(0)),
+            None => return Err(Error::BlockHeightNotFound(0u32)),
         };
         };
-        let (number, hash) = parse_u64_key_record(found)?;
+        let (height, hash) = parse_u32_key_record(found)?;
 
 
-        Ok((number, hash))
+        Ok((height, hash))
     }
     }
 
 
     /// Check if overlay's order tree contains any records.
     /// Check if overlay's order tree contains any records.

+ 4 - 4
src/blockchain/header_store.rs

@@ -61,7 +61,7 @@ pub struct Header {
     /// Previous block hash
     /// Previous block hash
     pub previous: HeaderHash,
     pub previous: HeaderHash,
     /// Block height
     /// Block height
-    pub height: u64,
+    pub height: u32,
     /// Block creation timestamp
     /// Block creation timestamp
     pub timestamp: Timestamp,
     pub timestamp: Timestamp,
     /// The block's nonce. This value changes arbitrarily with mining.
     /// The block's nonce. This value changes arbitrarily with mining.
@@ -71,7 +71,7 @@ pub struct Header {
 }
 }
 
 
 impl Header {
 impl Header {
-    pub fn new(previous: HeaderHash, height: u64, timestamp: Timestamp, nonce: u64) -> Self {
+    pub fn new(previous: HeaderHash, height: u32, timestamp: Timestamp, nonce: u64) -> Self {
         let version = block_version(height);
         let version = block_version(height);
         let tree = MerkleTree::new(1);
         let tree = MerkleTree::new(1);
         Self { version, previous, height, timestamp, nonce, tree }
         Self { version, previous, height, timestamp, nonce, tree }
@@ -100,9 +100,9 @@ impl Default for Header {
     fn default() -> Self {
     fn default() -> Self {
         Header::new(
         Header::new(
             HeaderHash::new(blake3::hash(b"Let there be dark!").into()),
             HeaderHash::new(blake3::hash(b"Let there be dark!").into()),
-            0,
+            0u32,
             Timestamp::current_time(),
             Timestamp::current_time(),
-            0,
+            0u64,
         )
         )
     }
     }
 }
 }

+ 17 - 8
src/blockchain/mod.rs

@@ -159,7 +159,7 @@ impl Blockchain {
     }
     }
 
 
     /// Retrieve [`BlockInfo`]s by given heights. Does not fail if any of them are not found.
     /// Retrieve [`BlockInfo`]s by given heights. Does not fail if any of them are not found.
-    pub fn get_blocks_by_heights(&self, heights: &[u64]) -> Result<Vec<BlockInfo>> {
+    pub fn get_blocks_by_heights(&self, heights: &[u32]) -> Result<Vec<BlockInfo>> {
         debug!(target: "blockchain", "get_blocks_by_heights(): {:?}", heights);
         debug!(target: "blockchain", "get_blocks_by_heights(): {:?}", heights);
         let blockhashes = self.blocks.get_order(heights, false)?;
         let blockhashes = self.blocks.get_order(heights, false)?;
 
 
@@ -172,7 +172,7 @@ impl Blockchain {
     }
     }
 
 
     /// Retrieve n blocks after given start block height.
     /// Retrieve n blocks after given start block height.
-    pub fn get_blocks_after(&self, height: u64, n: u64) -> Result<Vec<BlockInfo>> {
+    pub fn get_blocks_after(&self, height: u32, n: usize) -> Result<Vec<BlockInfo>> {
         debug!(target: "blockchain", "get_blocks_after(): {} -> {}", height, n);
         debug!(target: "blockchain", "get_blocks_after(): {} -> {}", height, n);
         let hashes = self.blocks.get_after(height, n)?;
         let hashes = self.blocks.get_after(height, n)?;
         self.get_blocks_by_hash(&hashes)
         self.get_blocks_by_hash(&hashes)
@@ -194,7 +194,7 @@ impl Blockchain {
     }
     }
 
 
     /// Retrieve genesis (first) block height and hash.
     /// Retrieve genesis (first) block height and hash.
-    pub fn genesis(&self) -> Result<(u64, HeaderHash)> {
+    pub fn genesis(&self) -> Result<(u32, HeaderHash)> {
         self.blocks.get_first()
         self.blocks.get_first()
     }
     }
 
 
@@ -205,7 +205,7 @@ impl Blockchain {
     }
     }
 
 
     /// Retrieve the last block height and hash.
     /// Retrieve the last block height and hash.
-    pub fn last(&self) -> Result<(u64, HeaderHash)> {
+    pub fn last(&self) -> Result<(u32, HeaderHash)> {
         self.blocks.get_last()
         self.blocks.get_last()
     }
     }
 
 
@@ -227,7 +227,7 @@ impl Blockchain {
     }
     }
 
 
     /// Check if block order for the given height is in the database.
     /// Check if block order for the given height is in the database.
-    pub fn has_height(&self, height: u64) -> Result<bool> {
+    pub fn has_height(&self, height: u32) -> Result<bool> {
         let vec = match self.blocks.get_order(&[height], true) {
         let vec = match self.blocks.get_order(&[height], true) {
             Ok(v) => v,
             Ok(v) => v,
             Err(_) => return Ok(false),
             Err(_) => return Ok(false),
@@ -357,7 +357,7 @@ impl BlockchainOverlay {
     }
     }
 
 
     /// Retrieve the last block height and hash.
     /// Retrieve the last block height and hash.
-    pub fn last(&self) -> Result<(u64, HeaderHash)> {
+    pub fn last(&self) -> Result<(u32, HeaderHash)> {
         self.blocks.get_last()
         self.blocks.get_last()
     }
     }
 
 
@@ -368,7 +368,7 @@ impl BlockchainOverlay {
     }
     }
 
 
     /// Retrieve the last block height.
     /// Retrieve the last block height.
-    pub fn last_block_height(&self) -> Result<u64> {
+    pub fn last_block_height(&self) -> Result<u32> {
         Ok(self.last()?.0)
         Ok(self.last()?.0)
     }
     }
 
 
@@ -488,7 +488,16 @@ impl BlockchainOverlay {
     }
     }
 }
 }
 
 
-/// Parse a sled record with a u64 keyin the form of a tuple (`key`, `value`).
+/// Parse a sled record with a u32 key in the form of a tuple (`key`, `value`).
+pub fn parse_u32_key_record<T: Decodable>(record: (sled::IVec, sled::IVec)) -> Result<(u32, T)> {
+    let key_bytes: [u8; 4] = record.0.as_ref().try_into().unwrap();
+    let key = u32::from_be_bytes(key_bytes);
+    let value = deserialize(&record.1)?;
+
+    Ok((key, value))
+}
+
+/// Parse a sled record with a u64 key in the form of a tuple (`key`, `value`).
 pub fn parse_u64_key_record<T: Decodable>(record: (sled::IVec, sled::IVec)) -> Result<(u64, T)> {
 pub fn parse_u64_key_record<T: Decodable>(record: (sled::IVec, sled::IVec)) -> Result<(u64, T)> {
     let key_bytes: [u8; 8] = record.0.as_ref().try_into().unwrap();
     let key_bytes: [u8; 8] = record.0.as_ref().try_into().unwrap();
     let key = u64::from_be_bytes(key_bytes);
     let key = u64::from_be_bytes(key_bytes);

+ 4 - 4
src/blockchain/tx_store.rs

@@ -71,7 +71,7 @@ impl TxStore {
     }
     }
 
 
     /// Insert a slice of [`TransactionHash`] into the store's location tree.
     /// Insert a slice of [`TransactionHash`] into the store's location tree.
-    pub fn insert_location(&self, txs_hashes: &[TransactionHash], block_height: u64) -> Result<()> {
+    pub fn insert_location(&self, txs_hashes: &[TransactionHash], block_height: u32) -> Result<()> {
         let batch = self.insert_batch_location(txs_hashes, block_height);
         let batch = self.insert_batch_location(txs_hashes, block_height);
         self.location.apply_batch(batch)?;
         self.location.apply_batch(batch)?;
         Ok(())
         Ok(())
@@ -121,7 +121,7 @@ impl TxStore {
     pub fn insert_batch_location(
     pub fn insert_batch_location(
         &self,
         &self,
         txs_hashes: &[TransactionHash],
         txs_hashes: &[TransactionHash],
-        block_height: u64,
+        block_height: u32,
     ) -> sled::Batch {
     ) -> sled::Batch {
         let mut batch = sled::Batch::default();
         let mut batch = sled::Batch::default();
 
 
@@ -285,7 +285,7 @@ impl TxStore {
     /// Retrieve all transactions locations from the store's location tree in
     /// Retrieve all transactions locations from the store's location tree in
     /// the form of a tuple (`tx_hash`, (`block_height`, `index`)).
     /// the form of a tuple (`tx_hash`, (`block_height`, `index`)).
     /// Be careful as this will try to load everything in memory.
     /// Be careful as this will try to load everything in memory.
-    pub fn get_all_location(&self) -> Result<Vec<(TransactionHash, (u64, u16))>> {
+    pub fn get_all_location(&self) -> Result<Vec<(TransactionHash, (u32, u16))>> {
         let mut locations = vec![];
         let mut locations = vec![];
 
 
         for location in self.location.iter() {
         for location in self.location.iter() {
@@ -403,7 +403,7 @@ impl TxStoreOverlay {
     /// Insert a slice of [`TransactionHash`] into the overlay's location tree.
     /// Insert a slice of [`TransactionHash`] into the overlay's location tree.
     /// The location tuple is built using the index of each transaction hash
     /// The location tuple is built using the index of each transaction hash
     /// in the slice, along with the provided block height
     /// in the slice, along with the provided block height
-    pub fn insert_location(&self, txs_hashes: &[TransactionHash], block_height: u64) -> Result<()> {
+    pub fn insert_location(&self, txs_hashes: &[TransactionHash], block_height: u32) -> Result<()> {
         let mut lock = self.0.lock().unwrap();
         let mut lock = self.0.lock().unwrap();
 
 
         for (index, tx_hash) in txs_hashes.iter().enumerate() {
         for (index, tx_hash) in txs_hashes.iter().enumerate() {

+ 1 - 1
src/contract/money/src/client/pow_reward_v1.rs

@@ -67,7 +67,7 @@ pub struct PoWRewardCallBuilder {
     /// Reward recipient's public key
     /// Reward recipient's public key
     pub recipient: PublicKey,
     pub recipient: PublicKey,
     /// Rewarded block height
     /// Rewarded block height
-    pub block_height: u64,
+    pub block_height: u32,
     /// Merkle tree of coins used to create inclusion proofs
     /// Merkle tree of coins used to create inclusion proofs
     /// Spend hook for the output
     /// Spend hook for the output
     pub spend_hook: FuncId,
     pub spend_hook: FuncId,

+ 3 - 3
src/contract/money/src/entrypoint/pow_reward_v1.rs

@@ -92,8 +92,8 @@ pub(crate) fn money_pow_reward_process_instruction_v1(
         msg!("[PoWRewardV1] Error: Could not receive last block height from db");
         msg!("[PoWRewardV1] Error: Could not receive last block height from db");
         return Err(MoneyError::PoWRewardRetrieveLastBlockHeightError.into())
         return Err(MoneyError::PoWRewardRetrieveLastBlockHeightError.into())
     };
     };
-    let last_block_height: u64 = deserialize(&last_block_height)?;
-    if verifying_block_height != last_block_height as u32 + 1 {
+    let last_block_height: u32 = deserialize(&last_block_height)?;
+    if verifying_block_height != last_block_height + 1 {
         msg!(
         msg!(
             "[PoWRewardV1] Error: Call is executed for block height {}, not next one: {}",
             "[PoWRewardV1] Error: Call is executed for block height {}, not next one: {}",
             verifying_block_height,
             verifying_block_height,
@@ -109,7 +109,7 @@ pub(crate) fn money_pow_reward_process_instruction_v1(
     }
     }
 
 
     // Verify reward value matches the expected one for this block height
     // Verify reward value matches the expected one for this block height
-    let expected_reward = expected_reward(verifying_block_height as u64);
+    let expected_reward = expected_reward(verifying_block_height);
     if params.input.value != expected_reward {
     if params.input.value != expected_reward {
         msg!(
         msg!(
             "[PoWRewardV1] Error: Reward value({}) is not the block height({}) expected one: {}",
             "[PoWRewardV1] Error: Reward value({}) is not the block height({}) expected one: {}",

+ 2 - 2
src/contract/test-harness/src/contract_deploy.rs

@@ -43,7 +43,7 @@ impl TestHarness {
         &mut self,
         &mut self,
         holder: &Holder,
         holder: &Holder,
         wasm_bincode: Vec<u8>,
         wasm_bincode: Vec<u8>,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, DeployParamsV1, Option<MoneyFeeParamsV1>)> {
     ) -> Result<(Transaction, DeployParamsV1, Option<MoneyFeeParamsV1>)> {
         let wallet = self.holders.get(holder).unwrap();
         let wallet = self.holders.get(holder).unwrap();
         let deploy_keypair = wallet.contract_deploy_authority;
         let deploy_keypair = wallet.contract_deploy_authority;
@@ -97,7 +97,7 @@ impl TestHarness {
         tx: Transaction,
         tx: Transaction,
         _params: &DeployParamsV1,
         _params: &DeployParamsV1,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 2 - 2
src/contract/test-harness/src/dao_exec.rs

@@ -59,7 +59,7 @@ impl TestHarness {
         all_vote_value: u64,
         all_vote_value: u64,
         yes_vote_blind: ScalarBlind,
         yes_vote_blind: ScalarBlind,
         all_vote_blind: ScalarBlind,
         all_vote_blind: ScalarBlind,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, MoneyTransferParamsV1, DaoExecParams, Option<MoneyFeeParamsV1>)> {
     ) -> Result<(Transaction, MoneyTransferParamsV1, DaoExecParams, Option<MoneyFeeParamsV1>)> {
         let dao_wallet = self.holders.get(&Holder::Dao).unwrap();
         let dao_wallet = self.holders.get(&Holder::Dao).unwrap();
 
 
@@ -254,7 +254,7 @@ impl TestHarness {
         xfer_params: &MoneyTransferParamsV1,
         xfer_params: &MoneyTransferParamsV1,
         _exec_params: &DaoExecParams,
         _exec_params: &DaoExecParams,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 2 - 2
src/contract/test-harness/src/dao_mint.rs

@@ -48,7 +48,7 @@ impl TestHarness {
         holder: &Holder,
         holder: &Holder,
         dao_info: &Dao,
         dao_info: &Dao,
         dao_kp: &Keypair,
         dao_kp: &Keypair,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, DaoMintParams, Option<MoneyFeeParamsV1>)> {
     ) -> Result<(Transaction, DaoMintParams, Option<MoneyFeeParamsV1>)> {
         let (dao_mint_pk, dao_mint_zkbin) =
         let (dao_mint_pk, dao_mint_zkbin) =
             self.proving_keys.get(DAO_CONTRACT_ZKAS_DAO_MINT_NS).unwrap();
             self.proving_keys.get(DAO_CONTRACT_ZKAS_DAO_MINT_NS).unwrap();
@@ -101,7 +101,7 @@ impl TestHarness {
         tx: Transaction,
         tx: Transaction,
         params: &DaoMintParams,
         params: &DaoMintParams,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 3 - 3
src/contract/test-harness/src/dao_propose.rs

@@ -54,7 +54,7 @@ impl TestHarness {
         user_data: pallas::Base,
         user_data: pallas::Base,
         dao: &Dao,
         dao: &Dao,
         dao_bulla: &DaoBulla,
         dao_bulla: &DaoBulla,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, (DaoProposeParams, Option<MoneyFeeParamsV1>), DaoProposal)> {
     ) -> Result<(Transaction, (DaoProposeParams, Option<MoneyFeeParamsV1>), DaoProposal)> {
         let wallet = self.holders.get(proposer).unwrap();
         let wallet = self.holders.get(proposer).unwrap();
 
 
@@ -121,7 +121,7 @@ impl TestHarness {
             },
             },
         ];
         ];
 
 
-        let creation_day = blockwindow(block_height as u32);
+        let creation_day = blockwindow(block_height);
         let proposal = DaoProposal {
         let proposal = DaoProposal {
             auth_calls,
             auth_calls,
             creation_day,
             creation_day,
@@ -194,7 +194,7 @@ impl TestHarness {
         tx: Transaction,
         tx: Transaction,
         params: &DaoProposeParams,
         params: &DaoProposeParams,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 3 - 3
src/contract/test-harness/src/dao_vote.rs

@@ -51,7 +51,7 @@ impl TestHarness {
         dao_keypair: &Keypair,
         dao_keypair: &Keypair,
         proposal: &DaoProposal,
         proposal: &DaoProposal,
         proposal_bulla: &DaoProposalBulla,
         proposal_bulla: &DaoProposalBulla,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, DaoVoteParams, Option<MoneyFeeParamsV1>)> {
     ) -> Result<(Transaction, DaoVoteParams, Option<MoneyFeeParamsV1>)> {
         let wallet = self.holders.get(voter).unwrap();
         let wallet = self.holders.get(voter).unwrap();
 
 
@@ -81,7 +81,7 @@ impl TestHarness {
             signature_secret,
             signature_secret,
         };
         };
 
 
-        let current_day = blockwindow(block_height as u32);
+        let current_day = blockwindow(block_height);
         let call = DaoVoteCall {
         let call = DaoVoteCall {
             money_null_smt: wallet.money_null_smt_snapshot.as_ref().unwrap(),
             money_null_smt: wallet.money_null_smt_snapshot.as_ref().unwrap(),
             inputs: vec![input],
             inputs: vec![input],
@@ -143,7 +143,7 @@ impl TestHarness {
         tx: Transaction,
         tx: Transaction,
         _params: &DaoVoteParams,
         _params: &DaoVoteParams,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 2 - 2
src/contract/test-harness/src/lib.rs

@@ -203,7 +203,7 @@ impl Wallet {
         &mut self,
         &mut self,
         callname: &str,
         callname: &str,
         tx: Transaction,
         tx: Transaction,
-        block_height: u64,
+        block_height: u32,
         verify_fees: bool,
         verify_fees: bool,
     ) -> Result<()> {
     ) -> Result<()> {
         if self.bench_wasm {
         if self.bench_wasm {
@@ -304,7 +304,7 @@ fn benchmark_wasm_calls(
     callname: &str,
     callname: &str,
     validator: &Validator,
     validator: &Validator,
     tx: &Transaction,
     tx: &Transaction,
-    block_height: u64,
+    block_height: u32,
 ) {
 ) {
     let mut file = std::fs::OpenOptions::new().create(true).append(true).open("bench.csv").unwrap();
     let mut file = std::fs::OpenOptions::new().create(true).append(true).open("bench.csv").unwrap();
 
 

+ 2 - 2
src/contract/test-harness/src/money_fee.rs

@@ -159,7 +159,7 @@ impl TestHarness {
         holder: &Holder,
         holder: &Holder,
         tx: Transaction,
         tx: Transaction,
         params: &MoneyFeeParamsV1,
         params: &MoneyFeeParamsV1,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();
 
 
@@ -211,7 +211,7 @@ impl TestHarness {
         &mut self,
         &mut self,
         holder: &Holder,
         holder: &Holder,
         tx: Transaction,
         tx: Transaction,
-        block_height: u64,
+        block_height: u32,
         spent_coins: &[OwnCoin],
         spent_coins: &[OwnCoin],
     ) -> Result<(ContractCall, Vec<Proof>, Vec<SecretKey>, Vec<OwnCoin>, MoneyFeeParamsV1)> {
     ) -> Result<(ContractCall, Vec<Proof>, Vec<SecretKey>, Vec<OwnCoin>, MoneyFeeParamsV1)> {
         // First we verify the fee-less transaction to see how much gas it uses for execution
         // First we verify the fee-less transaction to see how much gas it uses for execution

+ 1 - 1
src/contract/test-harness/src/money_genesis_mint.rs

@@ -84,7 +84,7 @@ impl TestHarness {
         holder: &Holder,
         holder: &Holder,
         tx: Transaction,
         tx: Transaction,
         params: &MoneyGenesisMintParamsV1,
         params: &MoneyGenesisMintParamsV1,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 2 - 2
src/contract/test-harness/src/money_otc_swap.rs

@@ -47,7 +47,7 @@ impl TestHarness {
         owncoin0: &OwnCoin,
         owncoin0: &OwnCoin,
         holder1: &Holder,
         holder1: &Holder,
         owncoin1: &OwnCoin,
         owncoin1: &OwnCoin,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, MoneyTransferParamsV1, Option<MoneyFeeParamsV1>)> {
     ) -> Result<(Transaction, MoneyTransferParamsV1, Option<MoneyFeeParamsV1>)> {
         let wallet0 = self.holders.get(holder0).unwrap();
         let wallet0 = self.holders.get(holder0).unwrap();
         let wallet1 = self.holders.get(holder1).unwrap();
         let wallet1 = self.holders.get(holder1).unwrap();
@@ -180,7 +180,7 @@ impl TestHarness {
         tx: Transaction,
         tx: Transaction,
         swap_params: &MoneyTransferParamsV1,
         swap_params: &MoneyTransferParamsV1,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 4 - 4
src/contract/test-harness/src/money_token.rs

@@ -56,7 +56,7 @@ impl TestHarness {
         token_blind: BaseBlind,
         token_blind: BaseBlind,
         spend_hook: Option<FuncId>,
         spend_hook: Option<FuncId>,
         user_data: Option<pallas::Base>,
         user_data: Option<pallas::Base>,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(
     ) -> Result<(
         Transaction,
         Transaction,
         MoneyTokenMintParamsV1,
         MoneyTokenMintParamsV1,
@@ -177,7 +177,7 @@ impl TestHarness {
         mint_params: &MoneyTokenMintParamsV1,
         mint_params: &MoneyTokenMintParamsV1,
         auth_params: &MoneyAuthTokenMintParamsV1,
         auth_params: &MoneyAuthTokenMintParamsV1,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();
@@ -250,7 +250,7 @@ impl TestHarness {
     pub async fn token_freeze(
     pub async fn token_freeze(
         &mut self,
         &mut self,
         holder: &Holder,
         holder: &Holder,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, MoneyTokenFreezeParamsV1, Option<MoneyFeeParamsV1>)> {
     ) -> Result<(Transaction, MoneyTokenFreezeParamsV1, Option<MoneyFeeParamsV1>)> {
         let wallet = self.holders.get(holder).unwrap();
         let wallet = self.holders.get(holder).unwrap();
         let mint_authority = wallet.token_mint_authority;
         let mint_authority = wallet.token_mint_authority;
@@ -329,7 +329,7 @@ impl TestHarness {
         tx: Transaction,
         tx: Transaction,
         _freeze_params: &MoneyTokenFreezeParamsV1,
         _freeze_params: &MoneyTokenFreezeParamsV1,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 2 - 2
src/contract/test-harness/src/money_transfer.rs

@@ -43,7 +43,7 @@ impl TestHarness {
         recipient: &Holder,
         recipient: &Holder,
         owncoins: &[OwnCoin],
         owncoins: &[OwnCoin],
         token_id: TokenId,
         token_id: TokenId,
-        block_height: u64,
+        block_height: u32,
     ) -> Result<(Transaction, (MoneyTransferParamsV1, Option<MoneyFeeParamsV1>), Vec<OwnCoin>)>
     ) -> Result<(Transaction, (MoneyTransferParamsV1, Option<MoneyFeeParamsV1>), Vec<OwnCoin>)>
     {
     {
         let wallet = self.holders.get(holder).unwrap();
         let wallet = self.holders.get(holder).unwrap();
@@ -120,7 +120,7 @@ impl TestHarness {
         tx: Transaction,
         tx: Transaction,
         call_params: &MoneyTransferParamsV1,
         call_params: &MoneyTransferParamsV1,
         fee_params: &Option<MoneyFeeParamsV1>,
         fee_params: &Option<MoneyFeeParamsV1>,
-        block_height: u64,
+        block_height: u32,
         append: bool,
         append: bool,
     ) -> Result<Vec<OwnCoin>> {
     ) -> Result<Vec<OwnCoin>> {
         let wallet = self.holders.get_mut(holder).unwrap();
         let wallet = self.holders.get_mut(holder).unwrap();

+ 3 - 3
src/error.rs

@@ -370,11 +370,11 @@ pub enum Error {
     #[error("Block {0} not found in database")]
     #[error("Block {0} not found in database")]
     BlockNotFound(String),
     BlockNotFound(String),
 
 
-    #[error("Block with order number {0} not found in database")]
-    BlockNumberNotFound(u64),
+    #[error("Block with height number {0} not found in database")]
+    BlockHeightNotFound(u32),
 
 
     #[error("Block difficulty for height number {0} not found in database")]
     #[error("Block difficulty for height number {0} not found in database")]
-    BlockDifficultyNotFound(u64),
+    BlockDifficultyNotFound(u32),
 
 
     #[error("Block {0} contains 0 transactions")]
     #[error("Block {0} contains 0 transactions")]
     BlockContainsNoTransactions(String),
     BlockContainsNoTransactions(String),

+ 2 - 3
src/runtime/import/util.rs

@@ -212,10 +212,9 @@ pub(crate) fn get_verifying_block_height(mut ctx: FunctionEnvMut<Env>) -> i64 {
     }
     }
 
 
     // Subtract used gas. Here we count the size of the object.
     // Subtract used gas. Here we count the size of the object.
-    // u64 is 8 bytes.
-    env.subtract_gas(&mut store, 8);
+    // u32 is 4 bytes.
+    env.subtract_gas(&mut store, 4);
 
 
-    assert!(env.verifying_block_height <= i64::MAX as u64);
     env.verifying_block_height as i64
     env.verifying_block_height as i64
 }
 }
 
 

+ 2 - 2
src/runtime/vm_runtime.rs

@@ -96,7 +96,7 @@ pub struct Env {
     pub objects: RefCell<Vec<Vec<u8>>>,
     pub objects: RefCell<Vec<Vec<u8>>>,
     /// Block height number runtime verifies against.
     /// Block height number runtime verifies against.
     /// For unconfirmed txs, this will be the current max height in the chain.
     /// For unconfirmed txs, this will be the current max height in the chain.
-    pub verifying_block_height: u64,
+    pub verifying_block_height: u32,
     /// The hash for this transaction the runtime is being run against.
     /// The hash for this transaction the runtime is being run against.
     pub tx_hash: TransactionHash,
     pub tx_hash: TransactionHash,
     /// The index for this call in the transaction
     /// The index for this call in the transaction
@@ -155,7 +155,7 @@ impl Runtime {
         wasm_bytes: &[u8],
         wasm_bytes: &[u8],
         blockchain: BlockchainOverlayPtr,
         blockchain: BlockchainOverlayPtr,
         contract_id: ContractId,
         contract_id: ContractId,
-        verifying_block_height: u64,
+        verifying_block_height: u32,
         tx_hash: TransactionHash,
         tx_hash: TransactionHash,
         call_idx: u8,
         call_idx: u8,
     ) -> Result<Self> {
     ) -> Result<Self> {

+ 3 - 3
src/sdk/src/blockchain.rs

@@ -18,14 +18,14 @@
 
 
 /// Auxiliary function to calculate provided block height block version.
 /// Auxiliary function to calculate provided block height block version.
 /// Currently, a single version(1) exists.
 /// Currently, a single version(1) exists.
-pub fn block_version(_height: u64) -> u8 {
+pub fn block_version(_height: u32) -> u8 {
     1
     1
 }
 }
 
 
 /// Auxiliary function to calculate provided block height epoch.
 /// Auxiliary function to calculate provided block height epoch.
 /// Each epoch is defined by the fixed intervals rewards change.
 /// Each epoch is defined by the fixed intervals rewards change.
 /// Genesis block is on epoch 0.
 /// Genesis block is on epoch 0.
-pub fn block_epoch(height: u64) -> u64 {
+pub fn block_epoch(height: u32) -> u8 {
     match height {
     match height {
         0 => 0,
         0 => 0,
         1..=1000 => 1,
         1..=1000 => 1,
@@ -45,7 +45,7 @@ pub fn block_epoch(height: u64) -> u64 {
 /// Auxiliary function to calculate provided block height expected reward value.
 /// Auxiliary function to calculate provided block height expected reward value.
 /// Genesis block always returns reward value 0. Rewards are halfed at fixed intervals,
 /// Genesis block always returns reward value 0. Rewards are halfed at fixed intervals,
 /// called epochs. After last epoch has started, reward value is based on DARK token-economics.
 /// called epochs. After last epoch has started, reward value is based on DARK token-economics.
-pub fn expected_reward(height: u64) -> u64 {
+pub fn expected_reward(height: u32) -> u64 {
     // Grab block height epoch
     // Grab block height epoch
     let epoch = block_epoch(height);
     let epoch = block_epoch(height);
 
 

+ 1 - 1
src/sdk/src/wasm/util.rs

@@ -171,7 +171,7 @@ pub fn get_tx(hash: &TransactionHash) -> GenericResult<Option<Vec<u8>>> {
 /// ```
 /// ```
 /// (block_height, tx_index) = get_tx_location(hash)?;
 /// (block_height, tx_index) = get_tx_location(hash)?;
 /// ```
 /// ```
-pub fn get_tx_location(hash: &TransactionHash) -> GenericResult<(u64, u16)> {
+pub fn get_tx_location(hash: &TransactionHash) -> GenericResult<(u32, u16)> {
     let mut buf = vec![];
     let mut buf = vec![];
     hash.encode(&mut buf)?;
     hash.encode(&mut buf)?;
 
 

+ 2 - 2
src/validator/consensus.rs

@@ -592,7 +592,7 @@ impl Fork {
     }
     }
 
 
     /// Auxiliary function to compute forks' next block height.
     /// Auxiliary function to compute forks' next block height.
-    pub fn get_next_block_height(&self) -> Result<u64> {
+    pub fn get_next_block_height(&self) -> Result<u32> {
         let proposal = self.last_proposal()?;
         let proposal = self.last_proposal()?;
         Ok(proposal.block.header.height + 1)
         Ok(proposal.block.header.height + 1)
     }
     }
@@ -601,7 +601,7 @@ impl Fork {
     pub async fn unproposed_txs(
     pub async fn unproposed_txs(
         &self,
         &self,
         blockchain: &Blockchain,
         blockchain: &Blockchain,
-        verifying_block_height: u64,
+        verifying_block_height: u32,
     ) -> Result<Vec<Transaction>> {
     ) -> Result<Vec<Transaction>> {
         // Check if our mempool is not empty
         // Check if our mempool is not empty
         if self.mempool.is_empty() {
         if self.mempool.is_empty() {

+ 2 - 2
src/validator/mod.rs

@@ -488,7 +488,7 @@ impl Validator {
     pub async fn add_transactions(
     pub async fn add_transactions(
         &self,
         &self,
         txs: &[Transaction],
         txs: &[Transaction],
-        verifying_block_height: u64,
+        verifying_block_height: u32,
         write: bool,
         write: bool,
         verify_fees: bool,
         verify_fees: bool,
     ) -> Result<u64> {
     ) -> Result<u64> {
@@ -534,7 +534,7 @@ impl Validator {
     pub async fn add_test_producer_transaction(
     pub async fn add_test_producer_transaction(
         &self,
         &self,
         tx: &Transaction,
         tx: &Transaction,
-        verifying_block_height: u64,
+        verifying_block_height: u32,
         write: bool,
         write: bool,
     ) -> Result<()> {
     ) -> Result<()> {
         debug!(target: "validator::add_test_producer_transaction", "Instantiating BlockchainOverlay");
         debug!(target: "validator::add_test_producer_transaction", "Instantiating BlockchainOverlay");

+ 3 - 3
src/validator/verification.rs

@@ -239,7 +239,7 @@ pub fn verify_producer_signature(block: &BlockInfo, public_key: &PublicKey) -> R
 /// Additionally, append its hash to the provided Merkle tree.
 /// Additionally, append its hash to the provided Merkle tree.
 pub async fn verify_producer_transaction(
 pub async fn verify_producer_transaction(
     overlay: &BlockchainOverlayPtr,
     overlay: &BlockchainOverlayPtr,
-    verifying_block_height: u64,
+    verifying_block_height: u32,
     tx: &Transaction,
     tx: &Transaction,
     tree: &mut MerkleTree,
     tree: &mut MerkleTree,
 ) -> Result<PublicKey> {
 ) -> Result<PublicKey> {
@@ -375,7 +375,7 @@ pub async fn verify_producer_transaction(
 /// provided Merkle tree.
 /// provided Merkle tree.
 pub async fn verify_transaction(
 pub async fn verify_transaction(
     overlay: &BlockchainOverlayPtr,
     overlay: &BlockchainOverlayPtr,
-    verifying_block_height: u64,
+    verifying_block_height: u32,
     tx: &Transaction,
     tx: &Transaction,
     tree: &mut MerkleTree,
     tree: &mut MerkleTree,
     verifying_keys: &mut HashMap<[u8; 32], HashMap<String, VerifyingKey>>,
     verifying_keys: &mut HashMap<[u8; 32], HashMap<String, VerifyingKey>>,
@@ -620,7 +620,7 @@ pub async fn verify_transaction(
 /// all the transactions. Additionally, their hash is appended to the provided Merkle tree.
 /// all the transactions. Additionally, their hash is appended to the provided Merkle tree.
 pub async fn verify_transactions(
 pub async fn verify_transactions(
     overlay: &BlockchainOverlayPtr,
     overlay: &BlockchainOverlayPtr,
-    verifying_block_height: u64,
+    verifying_block_height: u32,
     txs: &[Transaction],
     txs: &[Transaction],
     tree: &mut MerkleTree,
     tree: &mut MerkleTree,
     verify_fees: bool,
     verify_fees: bool,