block_store.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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::{blockchain::Slot, crypto::schnorr::Signature};
  19. use darkfi_serial::{deserialize, serialize, SerialDecodable, SerialEncodable};
  20. use crate::{tx::Transaction, Error, Result};
  21. use super::{parse_record, validate_slot, Header, SledDbOverlayPtr};
  22. /// Block version number
  23. pub const BLOCK_VERSION: u8 = 1;
  24. /// Block magic bytes
  25. const BLOCK_MAGIC_BYTES: [u8; 4] = [0x11, 0x6d, 0x75, 0x1f];
  26. /// This struct represents a tuple of the form (`magic`, `header`, `txs`, `producer`, `slots`).
  27. /// The header and transactions are stored as hashes, while slots are stored as integers,
  28. /// serving as pointers to the actual data in the sled database.
  29. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  30. pub struct Block {
  31. /// Block magic bytes
  32. pub magic: [u8; 4],
  33. /// Block header
  34. pub header: blake3::Hash,
  35. /// Trasaction hashes
  36. pub txs: Vec<blake3::Hash>,
  37. /// Block producer info
  38. pub producer: BlockProducer,
  39. /// Slots up until this block
  40. pub slots: Vec<u64>,
  41. }
  42. impl Block {
  43. pub fn new(
  44. header: blake3::Hash,
  45. txs: Vec<blake3::Hash>,
  46. producer: BlockProducer,
  47. slots: Vec<u64>,
  48. ) -> Self {
  49. let magic = BLOCK_MAGIC_BYTES;
  50. Self { magic, header, txs, producer, slots }
  51. }
  52. /// Calculate the block hash
  53. pub fn blockhash(&self) -> blake3::Hash {
  54. blake3::hash(&serialize(self))
  55. }
  56. }
  57. /// Structure representing full block data.
  58. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  59. pub struct BlockInfo {
  60. /// Block magic bytes
  61. pub magic: [u8; 4],
  62. /// Block header data
  63. pub header: Header,
  64. /// Transactions payload
  65. pub txs: Vec<Transaction>,
  66. /// Block producer info
  67. pub producer: BlockProducer,
  68. /// Slots payload
  69. pub slots: Vec<Slot>,
  70. }
  71. impl Default for BlockInfo {
  72. /// Represents the genesis block on current timestamp
  73. fn default() -> Self {
  74. let magic = BLOCK_MAGIC_BYTES;
  75. Self {
  76. magic,
  77. header: Header::default(),
  78. txs: vec![],
  79. producer: BlockProducer::default(),
  80. slots: vec![Slot::default()],
  81. }
  82. }
  83. }
  84. impl BlockInfo {
  85. pub fn new(
  86. header: Header,
  87. txs: Vec<Transaction>,
  88. producer: BlockProducer,
  89. slots: Vec<Slot>,
  90. ) -> Self {
  91. let magic = BLOCK_MAGIC_BYTES;
  92. Self { magic, header, txs, producer, slots }
  93. }
  94. /// Calculate the block hash
  95. pub fn blockhash(&self) -> blake3::Hash {
  96. let block: Block = self.clone().into();
  97. block.blockhash()
  98. }
  99. /// A block is considered valid when the following rules apply:
  100. /// 1. Parent hash is equal to the hash of the previous block
  101. /// 2. Timestamp increments previous block timestamp
  102. /// 3. Slot increments previous block slot
  103. /// 4. Slots vector is not empty and all its slots are valid
  104. /// 5. Slot is the same as the slots vector last slot id
  105. /// Additional validity rules can be applied.
  106. pub fn validate(&self, previous: &Self) -> Result<()> {
  107. let error = Err(Error::BlockIsInvalid(self.blockhash().to_string()));
  108. let previous_hash = previous.blockhash();
  109. // Check previous hash (1)
  110. if self.header.previous != previous_hash {
  111. return error
  112. }
  113. // Check timestamps are incremental (2)
  114. if self.header.timestamp <= previous.header.timestamp {
  115. return error
  116. }
  117. // Check slots are incremental (3)
  118. if self.header.slot <= previous.header.slot {
  119. return error
  120. }
  121. // Verify slots (4)
  122. if self.slots.is_empty() {
  123. return error
  124. }
  125. // Retrieve previous block last slot
  126. let mut previous_slot = previous.slots.last().unwrap();
  127. // Slots must already be in correct order (sorted by id)
  128. for slot in &self.slots {
  129. validate_slot(slot, previous_slot, &previous_hash, &previous.header.previous)?;
  130. previous_slot = slot;
  131. }
  132. // Check block slot is the last slot id (5)
  133. if self.slots.last().unwrap().id != self.header.slot {
  134. return error
  135. }
  136. Ok(())
  137. }
  138. }
  139. impl From<BlockInfo> for Block {
  140. fn from(block_info: BlockInfo) -> Self {
  141. let txs = block_info.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  142. let slots = block_info.slots.iter().map(|x| x.id).collect();
  143. Self {
  144. magic: block_info.magic,
  145. header: block_info.header.headerhash(),
  146. txs,
  147. producer: block_info.producer,
  148. slots,
  149. }
  150. }
  151. }
  152. /// [`Block`] sled tree
  153. const SLED_BLOCK_TREE: &[u8] = b"_blocks";
  154. /// The `BlockStore` is a `sled` tree storing all the blockchain's blocks
  155. /// where the key is the blocks' hash, and value is the serialized block.
  156. #[derive(Clone)]
  157. pub struct BlockStore(pub sled::Tree);
  158. impl BlockStore {
  159. /// Opens a new or existing `BlockStore` on the given sled database.
  160. pub fn new(db: &sled::Db) -> Result<Self> {
  161. let tree = db.open_tree(SLED_BLOCK_TREE)?;
  162. Ok(Self(tree))
  163. }
  164. /// Insert a slice of [`Block`] into the store.
  165. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  166. let (batch, ret) = self.insert_batch(blocks)?;
  167. self.0.apply_batch(batch)?;
  168. Ok(ret)
  169. }
  170. /// Generate the sled batch corresponding to an insert, so caller
  171. /// can handle the write operation.
  172. /// The blocks are hashed with BLAKE3 and this block hash is used as
  173. /// the key, while value is the serialized [`Block`] itself.
  174. /// On success, the function returns the block hashes in the same order.
  175. pub fn insert_batch(&self, blocks: &[Block]) -> Result<(sled::Batch, Vec<blake3::Hash>)> {
  176. let mut ret = Vec::with_capacity(blocks.len());
  177. let mut batch = sled::Batch::default();
  178. for block in blocks {
  179. let serialized = serialize(block);
  180. let blockhash = blake3::hash(&serialized);
  181. batch.insert(blockhash.as_bytes(), serialized);
  182. ret.push(blockhash);
  183. }
  184. Ok((batch, ret))
  185. }
  186. /// Check if the block store contains a given block hash.
  187. pub fn contains(&self, blockhash: &blake3::Hash) -> Result<bool> {
  188. Ok(self.0.contains_key(blockhash.as_bytes())?)
  189. }
  190. /// Fetch given block hashes from the block store.
  191. /// The resulting vector contains `Option`, which is `Some` if the block
  192. /// was found in the block store, and otherwise it is `None`, if it has not.
  193. /// The second parameter is a boolean which tells the function to fail in
  194. /// case at least one block was not found.
  195. pub fn get(&self, block_hashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  196. let mut ret = Vec::with_capacity(block_hashes.len());
  197. for hash in block_hashes {
  198. if let Some(found) = self.0.get(hash.as_bytes())? {
  199. let block = deserialize(&found)?;
  200. ret.push(Some(block));
  201. } else {
  202. if strict {
  203. let s = hash.to_hex().as_str().to_string();
  204. return Err(Error::BlockNotFound(s))
  205. }
  206. ret.push(None);
  207. }
  208. }
  209. Ok(ret)
  210. }
  211. /// Retrieve all blocks from the block store in the form of a tuple
  212. /// (`hash`, `block`).
  213. /// Be careful as this will try to load everything in memory.
  214. pub fn get_all(&self) -> Result<Vec<(blake3::Hash, Block)>> {
  215. let mut blocks = vec![];
  216. for block in self.0.iter() {
  217. blocks.push(parse_record(block.unwrap())?);
  218. }
  219. Ok(blocks)
  220. }
  221. }
  222. /// Overlay structure over a [`BlockStore`] instance.
  223. pub struct BlockStoreOverlay(SledDbOverlayPtr);
  224. impl BlockStoreOverlay {
  225. pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
  226. overlay.lock().unwrap().open_tree(SLED_BLOCK_TREE)?;
  227. Ok(Self(overlay.clone()))
  228. }
  229. /// Insert a slice of [`Block`] into the overlay.
  230. /// The block are hashed with BLAKE3 and this block hash is used as
  231. /// the key, while value is the serialized [`Block`] itself.
  232. /// On success, the function returns the block hashes in the same order.
  233. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  234. let mut ret = Vec::with_capacity(blocks.len());
  235. let mut lock = self.0.lock().unwrap();
  236. for block in blocks {
  237. let serialized = serialize(block);
  238. let blockhash = blake3::hash(&serialized);
  239. lock.insert(SLED_BLOCK_TREE, blockhash.as_bytes(), &serialized)?;
  240. ret.push(blockhash);
  241. }
  242. Ok(ret)
  243. }
  244. /// Fetch given block hashes from the overlay.
  245. /// The resulting vector contains `Option`, which is `Some` if the block
  246. /// was found in the overlay, and otherwise it is `None`, if it has not.
  247. /// The second parameter is a boolean which tells the function to fail in
  248. /// case at least one block was not found.
  249. pub fn get(&self, block_hashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  250. let mut ret = Vec::with_capacity(block_hashes.len());
  251. let lock = self.0.lock().unwrap();
  252. for hash in block_hashes {
  253. if let Some(found) = lock.get(SLED_BLOCK_TREE, hash.as_bytes())? {
  254. let block = deserialize(&found)?;
  255. ret.push(Some(block));
  256. } else {
  257. if strict {
  258. let s = hash.to_hex().as_str().to_string();
  259. return Err(Error::BlockNotFound(s))
  260. }
  261. ret.push(None);
  262. }
  263. }
  264. Ok(ret)
  265. }
  266. }
  267. /// Auxiliary structure used to keep track of blocks order.
  268. #[derive(Debug, SerialEncodable, SerialDecodable)]
  269. pub struct BlockOrder {
  270. /// Order number
  271. pub number: u64,
  272. /// Block headerhash of that number
  273. pub block: blake3::Hash,
  274. }
  275. /// [`BlockOrder`] sled tree
  276. const SLED_BLOCK_ORDER_TREE: &[u8] = b"_block_order";
  277. /// The `BlockOrderStore` is a `sled` tree storing the order of the
  278. /// blockchain's blocks, where the key is the order number, and the value is
  279. /// the blocks' hash. [`BlockStore`] can be queried with this hash.
  280. #[derive(Clone)]
  281. pub struct BlockOrderStore(pub sled::Tree);
  282. impl BlockOrderStore {
  283. /// Opens a new or existing `BlockOrderStore` on the given sled database.
  284. pub fn new(db: &sled::Db) -> Result<Self> {
  285. let tree = db.open_tree(SLED_BLOCK_ORDER_TREE)?;
  286. Ok(Self(tree))
  287. }
  288. /// Insert a slice of `u64` and block hashes into the store.
  289. pub fn insert(&self, order: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  290. let batch = self.insert_batch(order, hashes)?;
  291. self.0.apply_batch(batch)?;
  292. Ok(())
  293. }
  294. /// Generate the sled batch corresponding to an insert, so caller
  295. /// can handle the write operation.
  296. /// The block order number is used as the key, and the block hash is used as value.
  297. pub fn insert_batch(&self, order: &[u64], hashes: &[blake3::Hash]) -> Result<sled::Batch> {
  298. if order.len() != hashes.len() {
  299. return Err(Error::InvalidInputLengths)
  300. }
  301. let mut batch = sled::Batch::default();
  302. for (i, number) in order.iter().enumerate() {
  303. batch.insert(&number.to_be_bytes(), hashes[i].as_bytes());
  304. }
  305. Ok(batch)
  306. }
  307. /// Check if the block order store contains a given order number.
  308. pub fn contains(&self, number: u64) -> Result<bool> {
  309. Ok(self.0.contains_key(number.to_be_bytes())?)
  310. }
  311. /// Fetch given order numbers from the block order store.
  312. /// The resulting vector contains `Option`, which is `Some` if the number
  313. /// was found in the block order store, and otherwise it is `None`, if it has not.
  314. /// The second parameter is a boolean which tells the function to fail in
  315. /// case at least one order number was not found.
  316. pub fn get(&self, order: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  317. let mut ret = Vec::with_capacity(order.len());
  318. for number in order {
  319. if let Some(found) = self.0.get(number.to_be_bytes())? {
  320. let block_hash = deserialize(&found)?;
  321. ret.push(Some(block_hash));
  322. } else {
  323. if strict {
  324. return Err(Error::BlockNumberNotFound(*number))
  325. }
  326. ret.push(None);
  327. }
  328. }
  329. Ok(ret)
  330. }
  331. /// Retrieve complete order from the block order store in the form of
  332. /// a vector containing (`number`, `hash`) tuples.
  333. /// Be careful as this will try to load everything in memory.
  334. pub fn get_all(&self) -> Result<Vec<(u64, blake3::Hash)>> {
  335. let mut order = vec![];
  336. for record in self.0.iter() {
  337. order.push(parse_record(record.unwrap())?);
  338. }
  339. Ok(order)
  340. }
  341. /// Fetch n hashes after given order number. In the iteration, if an order
  342. /// number is not found, the iteration stops and the function returns what
  343. /// it has found so far in the `BlockOrderStore`.
  344. pub fn get_after(&self, number: u64, n: u64) -> Result<Vec<blake3::Hash>> {
  345. let mut ret = vec![];
  346. let mut key = number;
  347. let mut counter = 0;
  348. while counter <= n {
  349. if let Some(found) = self.0.get_gt(key.to_be_bytes())? {
  350. let (number, hash) = parse_record(found)?;
  351. key = number;
  352. ret.push(hash);
  353. counter += 1;
  354. continue
  355. }
  356. break
  357. }
  358. Ok(ret)
  359. }
  360. /// Fetch the first block hash in the tree, based on the `Ord`
  361. /// implementation for `Vec<u8>`.
  362. pub fn get_first(&self) -> Result<(u64, blake3::Hash)> {
  363. let found = match self.0.first()? {
  364. Some(s) => s,
  365. None => return Err(Error::BlockNumberNotFound(0)),
  366. };
  367. let (number, hash) = parse_record(found)?;
  368. Ok((number, hash))
  369. }
  370. /// Fetch the last block hash in the tree, based on the `Ord`
  371. /// implementation for `Vec<u8>`.
  372. pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
  373. let found = self.0.last()?.unwrap();
  374. let (number, hash) = parse_record(found)?;
  375. Ok((number, hash))
  376. }
  377. /// Retrieve records count
  378. pub fn len(&self) -> usize {
  379. self.0.len()
  380. }
  381. /// Check if sled contains any records
  382. pub fn is_empty(&self) -> bool {
  383. self.0.is_empty()
  384. }
  385. }
  386. /// Overlay structure over a [`BlockOrderStore`] instance.
  387. pub struct BlockOrderStoreOverlay(SledDbOverlayPtr);
  388. impl BlockOrderStoreOverlay {
  389. pub fn new(overlay: &SledDbOverlayPtr) -> Result<Self> {
  390. overlay.lock().unwrap().open_tree(SLED_BLOCK_ORDER_TREE)?;
  391. Ok(Self(overlay.clone()))
  392. }
  393. /// Insert a slice of `u64` and block hashes into the store. With sled, the
  394. /// operation is done as a batch.
  395. /// The block order number is used as the key, and the blockhash is used as value.
  396. pub fn insert(&self, order: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  397. if order.len() != hashes.len() {
  398. return Err(Error::InvalidInputLengths)
  399. }
  400. let mut lock = self.0.lock().unwrap();
  401. for (i, number) in order.iter().enumerate() {
  402. lock.insert(SLED_BLOCK_ORDER_TREE, &number.to_be_bytes(), hashes[i].as_bytes())?;
  403. }
  404. Ok(())
  405. }
  406. /// Fetch given order numbers from the overlay.
  407. /// The resulting vector contains `Option`, which is `Some` if the number
  408. /// was found in the overlay, and otherwise it is `None`, if it has not.
  409. /// The second parameter is a boolean which tells the function to fail in
  410. /// case at least one number was not found.
  411. pub fn get(&self, order: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  412. let mut ret = Vec::with_capacity(order.len());
  413. let lock = self.0.lock().unwrap();
  414. for number in order {
  415. if let Some(found) = lock.get(SLED_BLOCK_ORDER_TREE, &number.to_be_bytes())? {
  416. let block_hash = deserialize(&found)?;
  417. ret.push(Some(block_hash));
  418. } else {
  419. if strict {
  420. return Err(Error::BlockNumberNotFound(*number))
  421. }
  422. ret.push(None);
  423. }
  424. }
  425. Ok(ret)
  426. }
  427. /// Fetch the last block hash in the overlay, based on the `Ord`
  428. /// implementation for `Vec<u8>`.
  429. pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
  430. let found = self.0.lock().unwrap().last(SLED_BLOCK_ORDER_TREE)?.unwrap();
  431. let (number, hash) = parse_record(found)?;
  432. Ok((number, hash))
  433. }
  434. /// Check if overlay contains any records
  435. pub fn is_empty(&self) -> Result<bool> {
  436. Ok(self.0.lock().unwrap().is_empty(SLED_BLOCK_ORDER_TREE)?)
  437. }
  438. }
  439. /// This struct represents [`Block`] producer information.
  440. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  441. pub struct BlockProducer {
  442. /// Block producer signature
  443. pub signature: Signature,
  444. /// Proposal transaction
  445. pub proposal: Transaction,
  446. }
  447. impl BlockProducer {
  448. pub fn new(signature: Signature, proposal: Transaction) -> Self {
  449. Self { signature, proposal }
  450. }
  451. }
  452. impl Default for BlockProducer {
  453. fn default() -> Self {
  454. let signature = Signature::dummy();
  455. let proposal = Transaction::default();
  456. Self { signature, proposal }
  457. }
  458. }