block_store.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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::{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. /// BlockInfo 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 its parent hash is equal to the hash of the
  100. /// previous block and their slots are incremental.
  101. /// Additional validity rules can be applied.
  102. pub fn validate(&self, previous: &Self) -> Result<()> {
  103. let error = Err(Error::BlockIsInvalid(self.blockhash().to_string()));
  104. let previous_hash = previous.blockhash();
  105. // Check previous hash
  106. if self.header.previous != previous_hash {
  107. return error
  108. }
  109. // Check timestamps are incremental
  110. if self.header.timestamp <= previous.header.timestamp {
  111. return error
  112. }
  113. // Check slots are incremental
  114. if self.header.slot <= previous.header.slot {
  115. return error
  116. }
  117. // Verify slots exist
  118. let mut slots = self.slots.clone();
  119. if slots.is_empty() {
  120. return error
  121. }
  122. // Sort them just to be safe
  123. slots.sort_by(|a, b| b.id.cmp(&a.id));
  124. // Verify first slot increments from previous block
  125. if slots[0].id <= previous.header.slot {
  126. return error
  127. }
  128. // Check all slot cover same sequence
  129. for slot in &slots {
  130. if !slot.fork_hashes.contains(&previous_hash) {
  131. return error
  132. }
  133. if !slot.fork_previous_hashes.contains(&previous.header.previous) {
  134. return error
  135. }
  136. }
  137. // Check block slot is the last slot in the slice
  138. if slots.last().unwrap().id != self.header.slot {
  139. return error
  140. }
  141. // TODO: also validate slots etas and sigmas if we can derive them
  142. // from previous slots
  143. Ok(())
  144. }
  145. }
  146. impl From<BlockInfo> for Block {
  147. fn from(block_info: BlockInfo) -> Self {
  148. let txs = block_info.txs.iter().map(|x| blake3::hash(&serialize(x))).collect();
  149. let slots = block_info.slots.iter().map(|x| x.id).collect();
  150. Self {
  151. magic: block_info.magic,
  152. header: block_info.header.headerhash(),
  153. txs,
  154. producer: block_info.producer,
  155. slots,
  156. }
  157. }
  158. }
  159. /// [`Block`] sled tree
  160. const SLED_BLOCK_TREE: &[u8] = b"_blocks";
  161. /// The `BlockStore` is a `sled` tree storing all the blockchain's blocks
  162. /// where the key is the blocks' hash, and value is the serialized block.
  163. #[derive(Clone)]
  164. pub struct BlockStore(pub sled::Tree);
  165. impl BlockStore {
  166. /// Opens a new or existing `BlockStore` on the given sled database.
  167. pub fn new(db: &sled::Db) -> Result<Self> {
  168. let tree = db.open_tree(SLED_BLOCK_TREE)?;
  169. Ok(Self(tree))
  170. }
  171. /// Insert a slice of [`Block`] into the store.
  172. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  173. let (batch, ret) = self.insert_batch(blocks)?;
  174. self.0.apply_batch(batch)?;
  175. Ok(ret)
  176. }
  177. /// Generate the sled batch corresponding to an insert, so caller
  178. /// can handle the write operation.
  179. /// The blocks are hashed with BLAKE3 and this blockhash is used as
  180. /// the key, while value is the serialized [`Block`] itself.
  181. /// On success, the function returns the block hashes in the same order.
  182. pub fn insert_batch(&self, blocks: &[Block]) -> Result<(sled::Batch, Vec<blake3::Hash>)> {
  183. let mut ret = Vec::with_capacity(blocks.len());
  184. let mut batch = sled::Batch::default();
  185. for block in blocks {
  186. let serialized = serialize(block);
  187. let blockhash = blake3::hash(&serialized);
  188. batch.insert(blockhash.as_bytes(), serialized);
  189. ret.push(blockhash);
  190. }
  191. Ok((batch, ret))
  192. }
  193. /// Check if the blockstore contains a given blockhash.
  194. pub fn contains(&self, blockhash: &blake3::Hash) -> Result<bool> {
  195. Ok(self.0.contains_key(blockhash.as_bytes())?)
  196. }
  197. /// Fetch given block hashes from the blockstore.
  198. /// The resulting vector contains `Option`, which is `Some` if the block
  199. /// was found in the blockstore, and otherwise it is `None`, if it has not.
  200. /// The second parameter is a boolean which tells the function to fail in
  201. /// case at least one block was not found.
  202. pub fn get(&self, block_hashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  203. let mut ret = Vec::with_capacity(block_hashes.len());
  204. for hash in block_hashes {
  205. if let Some(found) = self.0.get(hash.as_bytes())? {
  206. let block = deserialize(&found)?;
  207. ret.push(Some(block));
  208. } else {
  209. if strict {
  210. let s = hash.to_hex().as_str().to_string();
  211. return Err(Error::BlockNotFound(s))
  212. }
  213. ret.push(None);
  214. }
  215. }
  216. Ok(ret)
  217. }
  218. /// Retrieve all blocks from the blockstore in the form of a tuple
  219. /// (`blockhash`, `block`).
  220. /// Be careful as this will try to load everything in memory.
  221. pub fn get_all(&self) -> Result<Vec<(blake3::Hash, Block)>> {
  222. let mut blocks = vec![];
  223. for block in self.0.iter() {
  224. let (key, value) = block.unwrap();
  225. let hash_bytes: [u8; 32] = key.as_ref().try_into().unwrap();
  226. let block = deserialize(&value)?;
  227. blocks.push((hash_bytes.into(), block));
  228. }
  229. Ok(blocks)
  230. }
  231. }
  232. /// Overlay structure over a [`BlockStore`] instance.
  233. pub struct BlockStoreOverlay(SledDbOverlayPtr);
  234. impl BlockStoreOverlay {
  235. pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
  236. overlay.lock().unwrap().open_tree(SLED_BLOCK_TREE)?;
  237. Ok(Self(overlay))
  238. }
  239. /// Insert a slice of [`Block`] into the overlay.
  240. /// The block are hashed with BLAKE3 and this blockhash is used as
  241. /// the key, while value is the serialized [`Block`] itself.
  242. /// On success, the function returns the block hashes in the same order.
  243. pub fn insert(&self, blocks: &[Block]) -> Result<Vec<blake3::Hash>> {
  244. let mut ret = Vec::with_capacity(blocks.len());
  245. let mut lock = self.0.lock().unwrap();
  246. for block in blocks {
  247. let serialized = serialize(block);
  248. let blockhash = blake3::hash(&serialized);
  249. lock.insert(SLED_BLOCK_TREE, blockhash.as_bytes(), &serialized)?;
  250. ret.push(blockhash);
  251. }
  252. Ok(ret)
  253. }
  254. /// Fetch given block hashes from the overlay.
  255. /// The resulting vector contains `Option`, which is `Some` if the block
  256. /// was found in the overlay, and otherwise it is `None`, if it has not.
  257. /// The second parameter is a boolean which tells the function to fail in
  258. /// case at least one block was not found.
  259. pub fn get(&self, block_hashes: &[blake3::Hash], strict: bool) -> Result<Vec<Option<Block>>> {
  260. let mut ret = Vec::with_capacity(block_hashes.len());
  261. let lock = self.0.lock().unwrap();
  262. for hash in block_hashes {
  263. if let Some(found) = lock.get(SLED_BLOCK_TREE, hash.as_bytes())? {
  264. let block = deserialize(&found)?;
  265. ret.push(Some(block));
  266. } else {
  267. if strict {
  268. let s = hash.to_hex().as_str().to_string();
  269. return Err(Error::BlockNotFound(s))
  270. }
  271. ret.push(None);
  272. }
  273. }
  274. Ok(ret)
  275. }
  276. }
  277. /// Auxiliary structure used to keep track of blocks order.
  278. #[derive(Debug, SerialEncodable, SerialDecodable)]
  279. pub struct BlockOrder {
  280. /// Slot UID
  281. pub slot: u64,
  282. /// Block headerhash of that slot
  283. pub block: blake3::Hash,
  284. }
  285. /// [`BlockOrder`] sled tree
  286. const SLED_BLOCK_ORDER_TREE: &[u8] = b"_block_order";
  287. /// The `BlockOrderStore` is a `sled` tree storing the order of the
  288. /// blockchain's slots, where the key is the slot uid, and the value is
  289. /// the blocks' hash. [`BlockStore`] can be queried with this hash.
  290. #[derive(Clone)]
  291. pub struct BlockOrderStore(pub sled::Tree);
  292. impl BlockOrderStore {
  293. /// Opens a new or existing `BlockOrderStore` on the given sled database.
  294. pub fn new(db: &sled::Db) -> Result<Self> {
  295. let tree = db.open_tree(SLED_BLOCK_ORDER_TREE)?;
  296. Ok(Self(tree))
  297. }
  298. /// Insert a slice of slots and blockhashes into the store.
  299. pub fn insert(&self, slots: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  300. let batch = self.insert_batch(slots, hashes)?;
  301. self.0.apply_batch(batch)?;
  302. Ok(())
  303. }
  304. /// Generate the sled batch corresponding to an insert, so caller
  305. /// can handle the write operation.
  306. /// The block slot is used as the key, and the blockhash is used as value.
  307. pub fn insert_batch(&self, slots: &[u64], hashes: &[blake3::Hash]) -> Result<sled::Batch> {
  308. if slots.len() != hashes.len() {
  309. return Err(Error::InvalidInputLengths)
  310. }
  311. let mut batch = sled::Batch::default();
  312. for (i, sl) in slots.iter().enumerate() {
  313. batch.insert(&sl.to_be_bytes(), hashes[i].as_bytes());
  314. }
  315. Ok(batch)
  316. }
  317. /// Check if the blockorderstore contains a given slot.
  318. pub fn contains(&self, slot: u64) -> Result<bool> {
  319. Ok(self.0.contains_key(slot.to_be_bytes())?)
  320. }
  321. /// Fetch given slots from the blockorderstore.
  322. /// The resulting vector contains `Option`, which is `Some` if the slot
  323. /// was found in the blockstore, and otherwise it is `None`, if it has not.
  324. /// The second parameter is a boolean which tells the function to fail in
  325. /// case at least one slot was not found.
  326. pub fn get(&self, slots: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  327. let mut ret = Vec::with_capacity(slots.len());
  328. for slot in slots {
  329. if let Some(found) = self.0.get(slot.to_be_bytes())? {
  330. let hash_bytes: [u8; 32] = found.as_ref().try_into().unwrap();
  331. let hash = blake3::Hash::from(hash_bytes);
  332. ret.push(Some(hash));
  333. } else {
  334. if strict {
  335. return Err(Error::BlockSlotNotFound(*slot))
  336. }
  337. ret.push(None);
  338. }
  339. }
  340. Ok(ret)
  341. }
  342. /// Retrieve all slots from the blockorderstore in the form of a tuple
  343. /// (`slot`, `blockhash`).
  344. /// Be careful as this will try to load everything in memory.
  345. pub fn get_all(&self) -> Result<Vec<(u64, blake3::Hash)>> {
  346. let mut slots = vec![];
  347. for slot in self.0.iter() {
  348. let (key, value) = slot.unwrap();
  349. let slot_bytes: [u8; 8] = key.as_ref().try_into().unwrap();
  350. let hash_bytes: [u8; 32] = value.as_ref().try_into().unwrap();
  351. let slot = u64::from_be_bytes(slot_bytes);
  352. let hash = blake3::Hash::from(hash_bytes);
  353. slots.push((slot, hash));
  354. }
  355. Ok(slots)
  356. }
  357. /// Fetch n hashes after given slot. In the iteration, if a slot is not
  358. /// found, the iteration stops and the function returns what it has found
  359. /// so far in the `BlockOrderStore`.
  360. pub fn get_after(&self, slot: u64, n: u64) -> Result<Vec<blake3::Hash>> {
  361. let mut ret = vec![];
  362. let mut key = slot;
  363. let mut counter = 0;
  364. while counter <= n {
  365. if let Some(found) = self.0.get_gt(key.to_be_bytes())? {
  366. let key_bytes: [u8; 8] = found.0.as_ref().try_into().unwrap();
  367. key = u64::from_be_bytes(key_bytes);
  368. let blockhash = deserialize(&found.1)?;
  369. ret.push(blockhash);
  370. counter += 1;
  371. continue
  372. }
  373. break
  374. }
  375. Ok(ret)
  376. }
  377. /// Fetch the first blockhash in the tree, based on the `Ord`
  378. /// implementation for `Vec<u8>`.
  379. pub fn get_first(&self) -> Result<(u64, blake3::Hash)> {
  380. let found = match self.0.first()? {
  381. Some(s) => s,
  382. None => return Err(Error::SlotNotFound(0)),
  383. };
  384. let slot_bytes: [u8; 8] = found.0.as_ref().try_into().unwrap();
  385. let hash_bytes: [u8; 32] = found.1.as_ref().try_into().unwrap();
  386. let slot = u64::from_be_bytes(slot_bytes);
  387. let hash = blake3::Hash::from(hash_bytes);
  388. Ok((slot, hash))
  389. }
  390. /// Fetch the last blockhash in the tree, based on the `Ord`
  391. /// implementation for `Vec<u8>`.
  392. pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
  393. let found = self.0.last()?.unwrap();
  394. let slot_bytes: [u8; 8] = found.0.as_ref().try_into().unwrap();
  395. let hash_bytes: [u8; 32] = found.1.as_ref().try_into().unwrap();
  396. let slot = u64::from_be_bytes(slot_bytes);
  397. let hash = blake3::Hash::from(hash_bytes);
  398. Ok((slot, hash))
  399. }
  400. /// Retrieve records count
  401. pub fn len(&self) -> usize {
  402. self.0.len()
  403. }
  404. /// Check if sled contains any records
  405. pub fn is_empty(&self) -> bool {
  406. self.0.is_empty()
  407. }
  408. }
  409. /// Overlay structure over a [`BlockOrderStore`] instance.
  410. pub struct BlockOrderStoreOverlay(SledDbOverlayPtr);
  411. impl BlockOrderStoreOverlay {
  412. pub fn new(overlay: SledDbOverlayPtr) -> Result<Self> {
  413. overlay.lock().unwrap().open_tree(SLED_BLOCK_ORDER_TREE)?;
  414. Ok(Self(overlay))
  415. }
  416. /// Insert a slice of slots and blockhashes into the store. With sled, the
  417. /// operation is done as a batch.
  418. /// The block slot is used as the key, and the blockhash is used as value.
  419. pub fn insert(&self, slots: &[u64], hashes: &[blake3::Hash]) -> Result<()> {
  420. if slots.len() != hashes.len() {
  421. return Err(Error::InvalidInputLengths)
  422. }
  423. let mut lock = self.0.lock().unwrap();
  424. for (i, sl) in slots.iter().enumerate() {
  425. lock.insert(SLED_BLOCK_ORDER_TREE, &sl.to_be_bytes(), hashes[i].as_bytes())?;
  426. }
  427. Ok(())
  428. }
  429. /// Fetch given slots from the overlay.
  430. /// The resulting vector contains `Option`, which is `Some` if the slot
  431. /// was found in the overlay, and otherwise it is `None`, if it has not.
  432. /// The second parameter is a boolean which tells the function to fail in
  433. /// case at least one slot was not found.
  434. pub fn get(&self, slots: &[u64], strict: bool) -> Result<Vec<Option<blake3::Hash>>> {
  435. let mut ret = Vec::with_capacity(slots.len());
  436. let lock = self.0.lock().unwrap();
  437. for slot in slots {
  438. if let Some(found) = lock.get(SLED_BLOCK_ORDER_TREE, &slot.to_be_bytes())? {
  439. let hash_bytes: [u8; 32] = found.as_ref().try_into().unwrap();
  440. let hash = blake3::Hash::from(hash_bytes);
  441. ret.push(Some(hash));
  442. } else {
  443. if strict {
  444. return Err(Error::BlockSlotNotFound(*slot))
  445. }
  446. ret.push(None);
  447. }
  448. }
  449. Ok(ret)
  450. }
  451. /// Fetch the last blockhash in the overlay, based on the `Ord`
  452. /// implementation for `Vec<u8>`.
  453. pub fn get_last(&self) -> Result<(u64, blake3::Hash)> {
  454. let found = self.0.lock().unwrap().last(SLED_BLOCK_ORDER_TREE)?.unwrap();
  455. let slot_bytes: [u8; 8] = found.0.as_ref().try_into().unwrap();
  456. let hash_bytes: [u8; 32] = found.1.as_ref().try_into().unwrap();
  457. let slot = u64::from_be_bytes(slot_bytes);
  458. let hash = blake3::Hash::from(hash_bytes);
  459. Ok((slot, hash))
  460. }
  461. /// Check if overlay contains any records
  462. pub fn is_empty(&self) -> Result<bool> {
  463. Ok(self.0.lock().unwrap().is_empty(SLED_BLOCK_ORDER_TREE)?)
  464. }
  465. }
  466. /// This struct represents [`Block`] producer information.
  467. #[derive(Debug, Clone, SerialEncodable, SerialDecodable)]
  468. pub struct BlockProducer {
  469. /// Block producer signature
  470. pub signature: Signature,
  471. /// Proposal transaction
  472. pub proposal: Transaction,
  473. }
  474. impl BlockProducer {
  475. pub fn new(signature: Signature, proposal: Transaction) -> Self {
  476. Self { signature, proposal }
  477. }
  478. }
  479. impl Default for BlockProducer {
  480. fn default() -> Self {
  481. let signature = Signature::dummy();
  482. let proposal = Transaction::default();
  483. Self { signature, proposal }
  484. }
  485. }