diff --git a/src/new_index/schema.rs b/src/new_index/schema.rs index 1cef91200..24590aea8 100644 --- a/src/new_index/schema.rs +++ b/src/new_index/schema.rs @@ -643,6 +643,9 @@ impl Indexer { ); let total = to_process.len(); let mut count = 0; + let mut deferred = 0; + // Only the blk*.dat fetcher can deliver a block before the block that funds it. + let defer_missing = matches!(from, FetchFrom::BlkFiles); start_fetcher( from, daemon, @@ -661,14 +664,33 @@ impl Indexer { ); } count += 1; - self.process_block_batch(&blocks, tip_height); + deferred += self.process_block_batch(&blocks, tip_height, defer_missing)?; Ok(()) - }) + })?; + if deferred > 0 { + // Every block has been added by now, so the RPC fallback (which only fetches + // blocks that are not both added and indexed) can index the deferred ones. + bail!( + "{} block(s) in blk*.dat spend outputs from blocks stored in a later file", + deferred + ); + } + Ok(()) } // Keep add and index adjacent: the output rows are still in RocksDB's write buffer // when history indexing looks up prevouts. Done-markers make retries idempotent. - fn process_block_batch(&self, blocks: &[BlockEntry], tip_height: usize) { + // + // blk*.dat files hold blocks in download order, so a block can spend an output from + // a block stored in a later file (#214). With `defer_missing`, such blocks are left + // added but unindexed instead of failing, and their count is returned. + fn process_block_batch( + &self, + blocks: &[BlockEntry], + tip_height: usize, + defer_missing: bool, + ) -> Result { + let mut deferred = 0; let to_add: Vec<_> = { let added = self.store.added_blockhashes.read().unwrap(); blocks @@ -691,7 +713,13 @@ impl Indexer { self.add(&to_add); } if !to_index.is_empty() { - self.index(&to_index); + match self.index(&to_index) { + Ok(()) => {} + Err(e) if defer_missing && is_missing_txo(&e) => { + deferred = self.index_each(&to_index)?; + } + Err(e) => return Err(e), + } } } if let Some(last) = blocks.last() { @@ -702,6 +730,28 @@ impl Indexer { .set(height as f64 / tip_height as f64 * 100.0); } } + Ok(deferred) + } + + // Index blocks one at a time, so one block with a prevout that is not added yet does + // not hold back the others. Returns how many blocks were left unindexed. + fn index_each(&self, blocks: &[BlockEntry]) -> Result { + let mut deferred = 0; + for block in blocks { + match self.index(std::slice::from_ref(block)) { + Ok(()) => {} + Err(e) if is_missing_txo(&e) => { + debug!( + "deferring block {} to the RPC fallback: {}", + block.entry.hash(), + e + ); + deferred += 1; + } + Err(e) => return Err(e), + } + } + Ok(deferred) } fn add(&self, blocks: &[BlockEntry]) { @@ -722,9 +772,9 @@ impl Indexer { .extend(blocks.iter().map(|b| b.entry.hash())); } - fn index(&self, blocks: &[BlockEntry]) { + fn index(&self, blocks: &[BlockEntry]) -> Result<()> { let mut batch = rocksdb::WriteBatch::default(); - let mut rows = self._index(blocks); + let mut rows = self._index(blocks)?; rows.par_sort_unstable_by(|a, b| a.key.cmp(&b.key)); for row in rows { batch.put(row.key, row.value); @@ -736,12 +786,13 @@ impl Indexer { let mut indexed_blockhashes = self.store.indexed_blockhashes.write().unwrap(); indexed_blockhashes.extend(blocks.iter().map(|b| b.entry.hash())); + Ok(()) } - fn _index(&self, blocks: &[BlockEntry]) -> Vec { + fn _index(&self, blocks: &[BlockEntry]) -> Result> { let previous_txos_map = { let _timer = self.start_timer("index_lookup"); - lookup_txos(&self.store.txstore_db, get_previous_txos(blocks)).unwrap() + lookup_txos(&self.store.txstore_db, get_previous_txos(blocks))? }; let rows = { let _timer = self.start_timer("index_process"); @@ -755,7 +806,7 @@ impl Indexer { } index_blocks(blocks, &previous_txos_map, &self.iconfig) }; - rows + Ok(rows) } pub fn fetch_from(&mut self, from: FetchFrom) { @@ -1711,6 +1762,10 @@ fn get_previous_txos(block_entries: &[BlockEntry]) -> BTreeSet { .collect() } +fn is_missing_txo(e: &Error) -> bool { + matches!(e.kind(), ErrorKind::MissingTxo(_)) +} + fn lookup_txos(txstore_db: &DB, outpoints: BTreeSet) -> Result> { let keys = outpoints.iter().map(TxOutRow::key).collect::>(); txstore_db diff --git a/src/new_index/schema/reorg.rs b/src/new_index/schema/reorg.rs index 39e9fc8eb..00d619783 100644 --- a/src/new_index/schema/reorg.rs +++ b/src/new_index/schema/reorg.rs @@ -1138,7 +1138,7 @@ mod tests { let mut indexer = test_indexer(&store, test_config()); let common = test_block(0, BlockHash::all_zeros(), 0, vec![]); indexer.add(&[common.clone()]); - indexer.index(&[common.clone()]); + indexer.index(&[common.clone()]).unwrap(); store .advance_synced_tip(vec![common.entry.clone()]) .unwrap(); @@ -1207,7 +1207,7 @@ mod tests { let mut indexer = test_indexer(&store, test_config()); let common = test_block(0, BlockHash::all_zeros(), 0, vec![]); indexer.add(&[common.clone()]); - indexer.index(&[common.clone()]); + indexer.index(&[common.clone()]).unwrap(); store .advance_synced_tip(vec![common.entry.clone()]) .unwrap(); diff --git a/tests/index.rs b/tests/index.rs index 6e61ad2da..14e5b33ae 100644 --- a/tests/index.rs +++ b/tests/index.rs @@ -155,14 +155,25 @@ impl Fixture { } fn write_file(&self, heights: &[usize]) { - let mut data = Vec::new(); - for &height in heights { - let raw = serialize(&self.chain.lock().unwrap().active[height]); - data.extend(self.config.network_type.magic().to_le_bytes()); - data.extend((raw.len() as u32).to_le_bytes()); - data.extend(raw); + self.write_files(&[heights]); + } + + // One blk*.dat file per entry, each holding the blocks at the given heights in order. + fn write_files(&self, files: &[&[usize]]) { + for (n, heights) in files.iter().enumerate() { + let mut data = Vec::new(); + for &height in heights.iter() { + let raw = serialize(&self.chain.lock().unwrap().active[height]); + data.extend(self.config.network_type.magic().to_le_bytes()); + data.extend((raw.len() as u32).to_le_bytes()); + data.extend(raw); + } + std::fs::write( + self.config.blocks_dir.join(format!("blk{:05}.dat", n)), + data, + ) + .unwrap(); } - std::fs::write(self.config.blocks_dir.join("blk00000.dat"), data).unwrap(); } fn prepare_gap(&self) { @@ -1181,3 +1192,54 @@ fn partial_file_import_fetches_only_the_gap_over_rpc() { assert_eq!(tip, chain.active[3].block_hash()); assert_eq!(chain.fetched, vec![chain.active[2].block_hash()]); } + +// bitcoind writes blocks to blk*.dat in download order, not height order, so a block can +// be stored in an earlier file than the block that funds one of its inputs (#214). The file +// import must not panic: it defers such blocks and the RPC fallback indexes them in order. +#[test] +fn file_import_defers_blocks_that_spend_outputs_stored_later() { + let fixture = Fixture::new(); + let (funding, spending) = { + let mut chain = fixture.chain.lock().unwrap(); + let mut active = chain.active.clone(); + let funding = active[3].txdata[0].compute_txid(); + let mut next = active[3].clone(); + next.header.prev_blockhash = active[3].block_hash(); + next.header.time += 1; + next.txdata[0].lock_time = bitcoin::absolute::LockTime::from_consensus(4); + let mut spend = next.txdata[0].clone(); + spend.input[0].previous_output = bitcoin::OutPoint { + txid: funding, + vout: 0, + }; + spend.output[0].script_pubkey = ScriptBuf::from_bytes(vec![0x54]); + let spending = spend.compute_txid(); + next.txdata.push(spend); + next.header.merkle_root = next.compute_merkle_root().unwrap(); + active.push(next); + chain.set_active(active); + (funding, spending) + }; + // The fetcher sends one batch per file, so the funding block 3 must be in a later + // file than the spending block 4 for the spend to be indexed before it is added. + fixture.write_files(&[&[0, 1, 2, 4], &[3]]); + let (store, mut indexer, daemon, metrics) = fixture.open(FetchFrom::BlkFiles); + + let tip = fixture.chain.lock().unwrap().active[4].block_hash(); + assert_eq!(indexer.update(&daemon).unwrap(), tip); + assert_eq!(store.headers().len(), 5); + assert!(store.done_initial_sync()); + // Only the deferred block goes over RPC; everything else came from the file. + assert_eq!(fixture.chain.lock().unwrap().fetched, vec![tip]); + + let query = ChainQuery::new(Arc::clone(&store), daemon, &fixture.config, &metrics); + let spent = query + .lookup_spend(&bitcoin::OutPoint { + txid: funding, + vout: 0, + }) + .unwrap(); + assert_eq!(spent.txid, spending); + let hash = sha256::Hash::hash(&[0x54]).to_byte_array(); + assert_eq!(query.stats(&hash).unwrap().tx_count, 1); +}