Source: indexer/filterindexer.js

  1. /*!
  2. * filterindexer.js - filter indexer
  3. * Copyright (c) 2018, the bcoin developers (MIT License).
  4. * https://github.com/bcoin-org/bcoin
  5. */
  6. 'use strict';
  7. const bdb = require('bdb');
  8. const assert = require('bsert');
  9. const Indexer = require('./indexer');
  10. const consensus = require('../protocol/consensus');
  11. const Filter = require('../primitives/filter');
  12. /**
  13. * FilterIndexer
  14. * @alias module:indexer.FilterIndexer
  15. * @extends Indexer
  16. */
  17. class FilterIndexer extends Indexer {
  18. /**
  19. * Create a indexer
  20. * @constructor
  21. * @param {Object} options
  22. */
  23. constructor(options) {
  24. super('filter', options);
  25. this.db = bdb.create(this.options);
  26. }
  27. /**
  28. * Store genesis previous filter header.
  29. * @private
  30. * @returns {Promise}
  31. */
  32. async saveGenesis() {
  33. const prevHash = this.network.genesis.prevBlock;
  34. // Genesis prev filter headers are defined to be zero hashes
  35. const filter = new Filter();
  36. filter.header = consensus.ZERO_HASH;
  37. await this.blocks.writeFilter(prevHash, filter.toRaw());
  38. await super.saveGenesis();
  39. }
  40. /**
  41. * Index compact filters.
  42. * @private
  43. * @param {BlockMeta} meta
  44. * @param {Block} block
  45. * @param {CoinView} view
  46. */
  47. async indexBlock(meta, block, view) {
  48. const hash = block.hash();
  49. const prev = await this.getFilterHeader(block.prevBlock);
  50. const basic = block.toFilter(view);
  51. const filter = new Filter();
  52. filter.header = basic.header(prev);
  53. filter.filter = basic.toRaw();
  54. await this.blocks.writeFilter(hash, filter.toRaw());
  55. }
  56. /**
  57. * Prune compact filters.
  58. * @private
  59. * @param {BlockMeta} meta
  60. */
  61. async pruneBlock(meta) {
  62. await this.blocks.pruneFilter(meta.hash);
  63. }
  64. /**
  65. * Retrieve compact filter by hash.
  66. * @param {Hash} hash
  67. * @param {Number} type
  68. * @returns {Promise} - Returns {@link Filter}.
  69. */
  70. async getFilter(hash) {
  71. assert(hash);
  72. const filter = await this.blocks.readFilter(hash);
  73. if (!filter)
  74. return null;
  75. return Filter.fromRaw(filter);
  76. }
  77. /**
  78. * Retrieve compact filter header by hash.
  79. * @param {Hash} hash
  80. * @returns {Promise} - Returns {@link Hash}.
  81. */
  82. async getFilterHeader(hash) {
  83. assert(hash);
  84. return this.blocks.readFilterHeader(hash);
  85. }
  86. }
  87. module.exports = FilterIndexer;