block_store.rs 19 KB

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