block_store.rs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use darkfi_sdk::{
  19. blockchain::Slot,
  20. crypto::{
  21. schnorr::{SchnorrSecret, Signature},
  22. SecretKey,
  23. },
  24. pasta::{group::ff::FromUniformBytes, pallas},
  25. };
  26. #[cfg(feature = "async-serial")]
  27. use darkfi_serial::async_trait;
  28. use darkfi_serial::{deserialize, serialize, Encodable, SerialDecodable, SerialEncodable};
  29. use num_bigint::BigUint;
  30. use rand::rngs::OsRng;
  31. use crate::{tx::Transaction, Error, Result};
  32. use super::{parse_record, parse_u64_key_record, Header, SledDbOverlayPtr};
  33. /// This struct represents a tuple of the form (`header`, `txs`, `signature`).
  34. /// The header and transactions are stored as hashes, serving as pointers to the actual data
  35. /// in the sled database.
  36. /// NOTE: This struct fields are considered final, as it represents a blockchain block.
  37. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  38. pub struct Block {
  39. /// Block header
  40. pub header: blake3::Hash,
  41. /// Trasaction hashes
  42. pub txs: Vec<blake3::Hash>,
  43. /// Block producer signature
  44. pub signature: Signature,
  45. }
  46. impl Block {
  47. pub fn new(header: blake3::Hash, txs: Vec<blake3::Hash>, signature: Signature) -> Self {
  48. Self { header, txs, signature }
  49. }
  50. /// A block's hash is the same as the hash of its header
  51. pub fn hash(&self) -> blake3::Hash {
  52. self.header
  53. }
  54. /// Generate a `Block` from a `BlockInfo`
  55. pub fn from_block_info(block_info: &BlockInfo) -> Result<Self> {
  56. let header = block_info.header.hash()?;
  57. let txs = block_info.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  58. let signature = block_info.signature;
  59. Ok(Self { header, txs, signature })
  60. }
  61. }
  62. /// Structure representing full block data, acting as
  63. /// a wrapper struct over `Block`, enabling us to include
  64. /// more information that might be used in different block
  65. /// version, without affecting the original struct.
  66. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  67. pub struct BlockInfo {
  68. /// Block header data
  69. pub header: Header,
  70. /// Transactions payload
  71. pub txs: Vec<Transaction>,
  72. /// Block producer signature
  73. pub signature: Signature,
  74. /// Slots payload
  75. pub slots: Vec<Slot>,
  76. }
  77. impl Default for BlockInfo {
  78. /// Represents the genesis block on current timestamp
  79. fn default() -> Self {
  80. Self {
  81. header: Header::default(),
  82. txs: vec![Transaction::default()],
  83. signature: Signature::dummy(),
  84. slots: vec![Slot::default()],
  85. }
  86. }
  87. }
  88. impl BlockInfo {
  89. pub fn new(
  90. header: Header,
  91. txs: Vec<Transaction>,
  92. signature: Signature,
  93. slots: Vec<Slot>,
  94. ) -> Self {
  95. Self { header, txs, signature, slots }
  96. }
  97. /// Generate an empty block for provided Header
  98. /// and slots vector. Transactions and the producer
  99. /// signature must be added after.
  100. pub fn new_empty(header: Header, slots: Vec<Slot>) -> Self {
  101. let txs = vec![];
  102. let signature = Signature::dummy();
  103. Self { header, txs, signature, slots }
  104. }
  105. /// A block's hash is the same as the hash of its header
  106. pub fn hash(&self) -> Result<blake3::Hash> {
  107. self.header.hash()
  108. }
  109. /// Compute the block's full hash
  110. pub fn full_hash(&self) -> Result<blake3::Hash> {
  111. let mut hasher = blake3::Hasher::new();
  112. self.encode(&mut hasher)?;
  113. Ok(hasher.finalize())
  114. }
  115. /// Append a transaction to the block. Also adds it to the Merkle tree.
  116. pub fn append_tx(&mut self, tx: Transaction) -> Result<()> {
  117. let mut buf = [0u8; 64];
  118. buf[..blake3::OUT_LEN].copy_from_slice(tx.hash()?.as_bytes());
  119. let leaf = pallas::Base::from_uniform_bytes(&buf);
  120. self.header.tree.append(leaf.into());
  121. self.txs.push(tx);
  122. Ok(())
  123. }
  124. /// Append a vector of transactions to the block. Also adds them to the
  125. /// Merkle tree.
  126. pub fn append_txs(&mut self, txs: Vec<Transaction>) -> Result<()> {
  127. for tx in txs {
  128. self.append_tx(tx)?;
  129. }
  130. Ok(())
  131. }
  132. /// Sign block header using provided secret key
  133. // TODO: sign more stuff?
  134. pub fn sign(&mut self, secret_key: &SecretKey) -> Result<()> {
  135. self.signature = secret_key.sign(&mut OsRng, &self.hash()?.as_bytes()[..]);
  136. Ok(())
  137. }
  138. }
  139. /// [`Block`] sled tree
  140. const SLED_BLOCK_TREE: &[u8] = b"_blocks";
  141. /// The `BlockStore` is a `sled` tree storing all the blockchain's blocks
  142. /// where the key is the blocks' hash, and value is the serialized block.
  143. #[derive(Clone)]
  144. pub struct BlockStore(pub sled::Tree);
  145. impl BlockStore {
  146. /// Opens a new or existing `BlockStore` on the given sled database.
  147. pub fn new(db: &sled::Db) -> Result<Self> {
  148. let tree = db.open_tree(SLED_BLOCK_TREE)?;
  149. Ok(Self(tree))
  150. }
  151. /// Insert a slice of [`Block`] into the store.
  152. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  153. let (batch, ret) = self.insert_batch(blocks)?;
  154. self.0.apply_batch(batch)?;
  155. Ok(ret)
  156. }
  157. /// Generate the sled batch corresponding to an insert, so caller
  158. /// can handle the write operation.
  159. /// The block's hash() function output is used as the key,
  160. /// while value is the serialized [`Block`] itself.
  161. /// On success, the function returns the block hashes in the same order.
  162. pub fn insert_batch(&self, blocks: &[Block]) -> Result<(sled::Batch, Vec<blake3::Hash>)> {
  163. let mut ret = Vec::with_capacity(blocks.len());
  164. let mut batch = sled::Batch::default();
  165. for block in blocks {
  166. let blockhash = block.hash();
  167. batch.insert(blockhash.as_bytes(), serialize(block));
  168. ret.push(blockhash);
  169. }
  170. Ok((batch, ret))
  171. }
  172. /// Check if the block store contains a given block hash.
  173. pub fn contains(&self, blockhash: &blake3::Hash) -> Result<bool> {
  174. Ok(self.0.contains_key(blockhash.as_bytes())?)
  175. }
  176. /// Fetch given block hashes from the block store.
  177. /// The resulting vector contains `Option`, which is `Some` if the block
  178. /// was found in the block store, and otherwise it is `None`, if it has not.
  179. /// The second parameter is a boolean which tells the function to fail in
  180. /// case at least one block was not found.
  181. pub fn get(&self, block_hashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  182. let mut ret = Vec::with_capacity(block_hashes.len());
  183. for hash in block_hashes {
  184. if let Some(found) = self.0.get(hash.as_bytes())? {
  185. let block = deserialize(&found)?;
  186. ret.push(Some(block));
  187. } else {
  188. if strict {
  189. let s = hash.to_hex().as_str().to_string();
  190. return Err(Error::BlockNotFound(s))
  191. }
  192. ret.push(None);
  193. }
  194. }
  195. Ok(ret)
  196. }
  197. /// Retrieve all blocks from the block store in the form of a tuple
  198. /// (`hash`, `block`).
  199. /// Be careful as this will try to load everything in memory.
  200. pub fn get_all(&self) -> Result<Vec<(blake3::Hash, Block)>> {
  201. let mut blocks = vec![];
  202. for block in self.0.iter() {
  203. blocks.push(parse_record(block.unwrap())?);
  204. }
  205. Ok(blocks)
  206. }
  207. }
  208. /// Overlay structure over a [`BlockStore`] instance.
  209. pub struct BlockStoreOverlay(SledDbOverlayPtr);
  210. impl BlockStoreOverlay {
  211. pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
  212. overlay.lock().unwrap().open_tree(SLED_BLOCK_TREE)?;
  213. Ok(Self(overlay.clone()))
  214. }
  215. /// Insert a slice of [`Block`] into the overlay.
  216. /// The block's hash() function output is used as the key,
  217. /// while value is the serialized [`Block`] itself.
  218. /// On success, the function returns the block hashes in the same order.
  219. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  220. let mut ret = Vec::with_capacity(blocks.len());
  221. let mut lock = self.0.lock().unwrap();
  222. for block in blocks {
  223. let blockhash = block.hash();
  224. lock.insert(SLED_BLOCK_TREE, blockhash.as_bytes(), &serialize(block))?;
  225. ret.push(blockhash);
  226. }
  227. Ok(ret)
  228. }
  229. /// Fetch given block hashes from the overlay.
  230. /// The resulting vector contains `Option`, which is `Some` if the block
  231. /// was found in the overlay, and otherwise it is `None`, if it has not.
  232. /// The second parameter is a boolean which tells the function to fail in
  233. /// case at least one block was not found.
  234. pub fn get(&self, block_hashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  235. let mut ret = Vec::with_capacity(block_hashes.len());
  236. let lock = self.0.lock().unwrap();
  237. for hash in block_hashes {
  238. if let Some(found) = lock.get(SLED_BLOCK_TREE, hash.as_bytes())? {
  239. let block = deserialize(&found)?;
  240. ret.push(Some(block));
  241. } else {
  242. if strict {
  243. let s = hash.to_hex().as_str().to_string();
  244. return Err(Error::BlockNotFound(s))
  245. }
  246. ret.push(None);
  247. }
  248. }
  249. Ok(ret)
  250. }
  251. }
  252. /// Auxiliary structure used to keep track of blocks order.
  253. #[derive(Debug, SerialEncodable, SerialDecodable)]
  254. pub struct BlockOrder {
  255. /// Order number
  256. pub number: u64,
  257. /// Block headerhash of that number
  258. pub block: blake3::Hash,
  259. }
  260. /// [`BlockOrder`] sled tree
  261. const SLED_BLOCK_ORDER_TREE: &[u8] = b"_block_order";
  262. /// The `BlockOrderStore` is a `sled` tree storing the order of the
  263. /// blockchain's blocks, where the key is the order number, and the value is
  264. /// the blocks' hash. [`BlockOrderStore`] can be queried with this order number.
  265. #[derive(Clone)]
  266. pub struct BlockOrderStore(pub sled::Tree);
  267. impl BlockOrderStore {
  268. /// Opens a new or existing `BlockOrderStore` on the given sled database.
  269. pub fn new(db: &sled::Db) -> Result<Self> {
  270. let tree = db.open_tree(SLED_BLOCK_ORDER_TREE)?;
  271. Ok(Self(tree))
  272. }
  273. /// Insert a slice of `u64` and block hashes into the store.
  274. pub fn insert(&self, order: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  275. let batch = self.insert_batch(order, hashes)?;
  276. self.0.apply_batch(batch)?;
  277. Ok(())
  278. }
  279. /// Generate the sled batch corresponding to an insert, so caller
  280. /// can handle the write operation.
  281. /// The block order number is used as the key, and the block hash is used as value.
  282. pub fn insert_batch(&self, order: &[u64], hashes: &[blake3::Hash]) -> Result<sled::Batch> {
  283. if order.len() != hashes.len() {
  284. return Err(Error::InvalidInputLengths)
  285. }
  286. let mut batch = sled::Batch::default();
  287. for (i, number) in order.iter().enumerate() {
  288. batch.insert(&number.to_be_bytes(), hashes[i].as_bytes());
  289. }
  290. Ok(batch)
  291. }
  292. /// Check if the block order store contains a given order number.
  293. pub fn contains(&self, number: u64) -> Result<bool> {
  294. Ok(self.0.contains_key(number.to_be_bytes())?)
  295. }
  296. /// Fetch given order numbers from the block order store.
  297. /// The resulting vector contains `Option`, which is `Some` if the number
  298. /// was found in the block order store, and otherwise it is `None`, if it has not.
  299. /// The second parameter is a boolean which tells the function to fail in
  300. /// case at least one order number was not found.
  301. pub fn get(&self, order: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  302. let mut ret = Vec::with_capacity(order.len());
  303. for number in order {
  304. if let Some(found) = self.0.get(number.to_be_bytes())? {
  305. let block_hash = deserialize(&found)?;
  306. ret.push(Some(block_hash));
  307. } else {
  308. if strict {
  309. return Err(Error::BlockNumberNotFound(*number))
  310. }
  311. ret.push(None);
  312. }
  313. }
  314. Ok(ret)
  315. }
  316. /// Retrieve complete order from the block order store in the form of
  317. /// a vector containing (`number`, `hash`) tuples.
  318. /// Be careful as this will try to load everything in memory.
  319. pub fn get_all(&self) -> Result<Vec<(u64, blake3::Hash)>> {
  320. let mut order = vec![];
  321. for record in self.0.iter() {
  322. order.push(parse_u64_key_record(record.unwrap())?);
  323. }
  324. Ok(order)
  325. }
  326. /// Fetch n hashes after given order number. In the iteration, if an order
  327. /// number is not found, the iteration stops and the function returns what
  328. /// it has found so far in the `BlockOrderStore`.
  329. pub fn get_after(&self, number: u64, n: u64) -> Result<Vec<blake3::Hash>> {
  330. let mut ret = vec![];
  331. let mut key = number;
  332. let mut counter = 0;
  333. while counter <= n {
  334. if let Some(found) = self.0.get_gt(key.to_be_bytes())? {
  335. let (number, hash) = parse_u64_key_record(found)?;
  336. key = number;
  337. ret.push(hash);
  338. counter += 1;
  339. continue
  340. }
  341. break
  342. }
  343. Ok(ret)
  344. }
  345. /// Fetch the first block hash in the tree, based on the `Ord`
  346. /// implementation for `Vec<u8>`.
  347. pub fn get_first(&self) -> Result<(u64, blake3::Hash)> {
  348. let found = match self.0.first()? {
  349. Some(s) => s,
  350. None => return Err(Error::BlockNumberNotFound(0)),
  351. };
  352. let (number, hash) = parse_u64_key_record(found)?;
  353. Ok((number, hash))
  354. }
  355. /// Fetch the last block hash in the tree, based on the `Ord`
  356. /// implementation for `Vec<u8>`.
  357. pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
  358. let found = self.0.last()?.unwrap();
  359. let (number, hash) = parse_u64_key_record(found)?;
  360. Ok((number, hash))
  361. }
  362. /// Retrieve records count
  363. pub fn len(&self) -> usize {
  364. self.0.len()
  365. }
  366. /// Check if sled contains any records
  367. pub fn is_empty(&self) -> bool {
  368. self.0.is_empty()
  369. }
  370. }
  371. /// Overlay structure over a [`BlockOrderStore`] instance.
  372. pub struct BlockOrderStoreOverlay(SledDbOverlayPtr);
  373. impl BlockOrderStoreOverlay {
  374. pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
  375. overlay.lock().unwrap().open_tree(SLED_BLOCK_ORDER_TREE)?;
  376. Ok(Self(overlay.clone()))
  377. }
  378. /// Insert a slice of `u64` and block hashes into the store. With sled, the
  379. /// operation is done as a batch.
  380. /// The block order number is used as the key, and the blockhash is used as value.
  381. pub fn insert(&self, order: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  382. if order.len() != hashes.len() {
  383. return Err(Error::InvalidInputLengths)
  384. }
  385. let mut lock = self.0.lock().unwrap();
  386. for (i, number) in order.iter().enumerate() {
  387. lock.insert(SLED_BLOCK_ORDER_TREE, &number.to_be_bytes(), hashes[i].as_bytes())?;
  388. }
  389. Ok(())
  390. }
  391. /// Fetch given order numbers from the overlay.
  392. /// The resulting vector contains `Option`, which is `Some` if the number
  393. /// was found in the overlay, and otherwise it is `None`, if it has not.
  394. /// The second parameter is a boolean which tells the function to fail in
  395. /// case at least one number was not found.
  396. pub fn get(&self, order: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  397. let mut ret = Vec::with_capacity(order.len());
  398. let lock = self.0.lock().unwrap();
  399. for number in order {
  400. if let Some(found) = lock.get(SLED_BLOCK_ORDER_TREE, &number.to_be_bytes())? {
  401. let block_hash = deserialize(&found)?;
  402. ret.push(Some(block_hash));
  403. } else {
  404. if strict {
  405. return Err(Error::BlockNumberNotFound(*number))
  406. }
  407. ret.push(None);
  408. }
  409. }
  410. Ok(ret)
  411. }
  412. /// Fetch the last block hash in the overlay, based on the `Ord`
  413. /// implementation for `Vec<u8>`.
  414. pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
  415. let found = self.0.lock().unwrap().last(SLED_BLOCK_ORDER_TREE)?.unwrap();
  416. let (number, hash) = parse_u64_key_record(found)?;
  417. Ok((number, hash))
  418. }
  419. /// Check if overlay contains any records
  420. pub fn is_empty(&self) -> Result<bool> {
  421. Ok(self.0.lock().unwrap().is_empty(SLED_BLOCK_ORDER_TREE)?)
  422. }
  423. }
  424. /// Auxiliary structure used to keep track of block PoW difficulty information.
  425. /// Note: we only need height cummulative difficulty, but we also keep its actual
  426. /// difficulty, so we can verify the sequence and/or know specific block height
  427. /// difficulty, if ever needed.
  428. #[derive(Debug)]
  429. pub struct BlockDifficulty {
  430. /// Block height number
  431. pub height: u64,
  432. /// Block creation timestamp
  433. pub timestamp: u64,
  434. /// Height difficulty
  435. pub difficulty: BigUint,
  436. /// Height cummulative difficulty (total + height difficulty)
  437. pub cummulative_difficulty: BigUint,
  438. }
  439. impl BlockDifficulty {
  440. pub fn new(
  441. height: u64,
  442. timestamp: u64,
  443. difficulty: BigUint,
  444. cummulative_difficulty: BigUint,
  445. ) -> Self {
  446. Self { height, timestamp, difficulty, cummulative_difficulty }
  447. }
  448. }
  449. // Note: Doing all the imports here as this might get obselete if
  450. // we implemented Encodable/Decodable for num_bigint::BigUint.
  451. impl darkfi_serial::Encodable for BlockDifficulty {
  452. fn encode<S: std::io::Write>(&self, mut s: S) -> std::io::Result<usize> {
  453. let mut len = 0;
  454. len += self.height.encode(&mut s)?;
  455. len += self.timestamp.encode(&mut s)?;
  456. len += self.difficulty.to_bytes_be().encode(&mut s)?;
  457. len += self.cummulative_difficulty.to_bytes_be().encode(&mut s)?;
  458. Ok(len)
  459. }
  460. }
  461. impl darkfi_serial::Decodable for BlockDifficulty {
  462. fn decode<D: std::io::Read>(mut d: D) -> std::io::Result<Self> {
  463. let height: u64 = darkfi_serial::Decodable::decode(&mut d)?;
  464. let timestamp: u64 = darkfi_serial::Decodable::decode(&mut d)?;
  465. let bytes: Vec<u8> = darkfi_serial::Decodable::decode(&mut d)?;
  466. let difficulty: BigUint = BigUint::from_bytes_be(&bytes);
  467. let bytes: Vec<u8> = darkfi_serial::Decodable::decode(&mut d)?;
  468. let cummulative_difficulty: BigUint = BigUint::from_bytes_be(&bytes);
  469. let ret = Self { height, timestamp, difficulty, cummulative_difficulty };
  470. Ok(ret)
  471. }
  472. }
  473. /// [`BlockDifficulty`] sled tree
  474. const SLED_BLOCK_DIFFICULTY_TREE: &[u8] = b"_block_difficulty";
  475. /// The `BlockDifficultyStore` is a `sled` tree storing the difficulty information
  476. /// of the blockchain's blocks, where the key is the block height number, and the
  477. /// value is the blocks' hash. [`BlockDifficultyStore`] can be queried with this
  478. /// height number.
  479. #[derive(Clone)]
  480. pub struct BlockDifficultyStore(pub sled::Tree);
  481. impl BlockDifficultyStore {
  482. /// Opens a new or existing `BlockDifficultyStore` on the given sled database.
  483. pub fn new(db: &sled::Db) -> Result<Self> {
  484. let tree = db.open_tree(SLED_BLOCK_DIFFICULTY_TREE)?;
  485. Ok(Self(tree))
  486. }
  487. /// Insert a slice of [`BlockDifficulty`] into the store.
  488. pub fn insert(&self, block_difficulties: &[BlockDifficulty]) -> Result<()> {
  489. let batch = self.insert_batch(block_difficulties)?;
  490. self.0.apply_batch(batch)?;
  491. Ok(())
  492. }
  493. /// Generate the sled batch corresponding to an insert, so caller
  494. /// can handle the write operation.
  495. /// The block's height number is used as the key, while value is
  496. // the serialized [`BlockDifficulty`] itself.
  497. pub fn insert_batch(&self, block_difficulties: &[BlockDifficulty]) -> Result<sled::Batch> {
  498. let mut batch = sled::Batch::default();
  499. for block_difficulty in block_difficulties {
  500. batch.insert(&block_difficulty.height.to_be_bytes(), serialize(block_difficulty));
  501. }
  502. Ok(batch)
  503. }
  504. /// Fetch given block height numbers from the block difficulties store.
  505. /// The resulting vector contains `Option`, which is `Some` if the block
  506. /// height number was found in the block difficulties store, and otherwise
  507. /// it is `None`, if it has not.
  508. /// The second parameter is a boolean which tells the function to fail in
  509. /// case at least one block height number was not found.
  510. pub fn get(&self, heights: &[u64], strict: bool) -> Result<Vec<Option<BlockDifficulty>>> {
  511. let mut ret = Vec::with_capacity(heights.len());
  512. for height in heights {
  513. if let Some(found) = self.0.get(height.to_be_bytes())? {
  514. let block_difficulty = deserialize(&found)?;
  515. ret.push(Some(block_difficulty));
  516. } else {
  517. if strict {
  518. return Err(Error::BlockDifficultyNotFound(*height))
  519. }
  520. ret.push(None);
  521. }
  522. }
  523. Ok(ret)
  524. }
  525. /// Fetch the last N records from the block difficulties store, in order.
  526. pub fn get_last_n(&self, n: usize) -> Result<Vec<BlockDifficulty>> {
  527. // Build an iterator to retrieve last N records
  528. let records = self.0.iter().rev().take(n);
  529. // Since the iterator grabs in right -> left order,
  530. // we deserialize found records, and push them in reverse order
  531. let mut last_n = vec![];
  532. for record in records {
  533. last_n.insert(0, deserialize(&record?.1)?);
  534. }
  535. Ok(last_n)
  536. }
  537. /// Retrieve all blockdifficulties from the block difficulties store in
  538. /// the form of a vector containing (`height`, `difficulty`) tuples.
  539. /// Be careful as this will try to load everything in memory.
  540. pub fn get_all(&self) -> Result<Vec<(u64, BlockDifficulty)>> {
  541. let mut block_difficulties = vec![];
  542. for record in self.0.iter() {
  543. block_difficulties.push(parse_u64_key_record(record.unwrap())?);
  544. }
  545. Ok(block_difficulties)
  546. }
  547. }
  548. /// Overlay structure over a [`BlockDifficultyStore`] instance.
  549. pub struct BlockDifficultyStoreOverlay(SledDbOverlayPtr);
  550. impl BlockDifficultyStoreOverlay {
  551. pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
  552. overlay.lock().unwrap().open_tree(SLED_BLOCK_DIFFICULTY_TREE)?;
  553. Ok(Self(overlay.clone()))
  554. }
  555. /// Insert a slice of [`BlockDifficulty`] into the overlay.
  556. pub fn insert(&self, block_difficulties: &[BlockDifficulty]) -> Result<()> {
  557. let mut lock = self.0.lock().unwrap();
  558. for block_difficulty in block_difficulties {
  559. lock.insert(
  560. SLED_BLOCK_DIFFICULTY_TREE,
  561. &block_difficulty.height.to_be_bytes(),
  562. &serialize(block_difficulty),
  563. )?;
  564. }
  565. Ok(())
  566. }
  567. }