block_store.rs 23 KB

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