block_store.rs 19 KB

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