postprocess.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package light
  17. import (
  18. "context"
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/common/bitutil"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/params"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/ethereum/go-ethereum/trie"
  34. )
  35. // IndexerConfig includes a set of configs for chain indexers.
  36. type IndexerConfig struct {
  37. // The block frequency for creating CHTs.
  38. ChtSize uint64
  39. // The number of confirmations needed to generate/accept a canonical hash help trie.
  40. ChtConfirms uint64
  41. // The block frequency for creating new bloom bits.
  42. BloomSize uint64
  43. // The number of confirmation needed before a bloom section is considered probably final and its rotated bits
  44. // are calculated.
  45. BloomConfirms uint64
  46. // The block frequency for creating BloomTrie.
  47. BloomTrieSize uint64
  48. // The number of confirmations needed to generate/accept a bloom trie.
  49. BloomTrieConfirms uint64
  50. }
  51. var (
  52. // DefaultServerIndexerConfig wraps a set of configs as a default indexer config for server side.
  53. DefaultServerIndexerConfig = &IndexerConfig{
  54. ChtSize: params.CHTFrequency,
  55. ChtConfirms: params.HelperTrieProcessConfirmations,
  56. BloomSize: params.BloomBitsBlocks,
  57. BloomConfirms: params.BloomConfirms,
  58. BloomTrieSize: params.BloomTrieFrequency,
  59. BloomTrieConfirms: params.HelperTrieProcessConfirmations,
  60. }
  61. // DefaultClientIndexerConfig wraps a set of configs as a default indexer config for client side.
  62. DefaultClientIndexerConfig = &IndexerConfig{
  63. ChtSize: params.CHTFrequency,
  64. ChtConfirms: params.HelperTrieConfirmations,
  65. BloomSize: params.BloomBitsBlocksClient,
  66. BloomConfirms: params.HelperTrieConfirmations,
  67. BloomTrieSize: params.BloomTrieFrequency,
  68. BloomTrieConfirms: params.HelperTrieConfirmations,
  69. }
  70. // TestServerIndexerConfig wraps a set of configs as a test indexer config for server side.
  71. TestServerIndexerConfig = &IndexerConfig{
  72. ChtSize: 128,
  73. ChtConfirms: 1,
  74. BloomSize: 16,
  75. BloomConfirms: 1,
  76. BloomTrieSize: 128,
  77. BloomTrieConfirms: 1,
  78. }
  79. // TestClientIndexerConfig wraps a set of configs as a test indexer config for client side.
  80. TestClientIndexerConfig = &IndexerConfig{
  81. ChtSize: 128,
  82. ChtConfirms: 8,
  83. BloomSize: 128,
  84. BloomConfirms: 8,
  85. BloomTrieSize: 128,
  86. BloomTrieConfirms: 8,
  87. }
  88. )
  89. var (
  90. errNoTrustedCht = errors.New("no trusted canonical hash trie")
  91. errNoTrustedBloomTrie = errors.New("no trusted bloom trie")
  92. errNoHeader = errors.New("header not found")
  93. chtPrefix = []byte("chtRootV2-") // chtPrefix + chtNum (uint64 big endian) -> trie root hash
  94. ChtTablePrefix = "cht-"
  95. )
  96. // ChtNode structures are stored in the Canonical Hash Trie in an RLP encoded format
  97. type ChtNode struct {
  98. Hash common.Hash
  99. Td *big.Int
  100. }
  101. // GetChtRoot reads the CHT root associated to the given section from the database
  102. func GetChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  103. var encNumber [8]byte
  104. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  105. data, _ := db.Get(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...))
  106. return common.BytesToHash(data)
  107. }
  108. // StoreChtRoot writes the CHT root associated to the given section into the database
  109. func StoreChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  110. var encNumber [8]byte
  111. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  112. db.Put(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  113. }
  114. // ChtIndexerBackend implements core.ChainIndexerBackend.
  115. type ChtIndexerBackend struct {
  116. diskdb, trieTable ethdb.Database
  117. odr OdrBackend
  118. triedb *trie.Database
  119. section, sectionSize uint64
  120. lastHash common.Hash
  121. trie *trie.Trie
  122. }
  123. // NewChtIndexer creates a Cht chain indexer
  124. func NewChtIndexer(db ethdb.Database, odr OdrBackend, size, confirms uint64) *core.ChainIndexer {
  125. trieTable := rawdb.NewTable(db, ChtTablePrefix)
  126. backend := &ChtIndexerBackend{
  127. diskdb: db,
  128. odr: odr,
  129. trieTable: trieTable,
  130. triedb: trie.NewDatabaseWithCache(trieTable, 1), // Use a tiny cache only to keep memory down
  131. sectionSize: size,
  132. }
  133. return core.NewChainIndexer(db, rawdb.NewTable(db, "chtIndexV2-"), backend, size, confirms, time.Millisecond*100, "cht")
  134. }
  135. // fetchMissingNodes tries to retrieve the last entry of the latest trusted CHT from the
  136. // ODR backend in order to be able to add new entries and calculate subsequent root hashes
  137. func (c *ChtIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
  138. batch := c.trieTable.NewBatch()
  139. r := &ChtRequest{ChtRoot: root, ChtNum: section - 1, BlockNum: section*c.sectionSize - 1, Config: c.odr.IndexerConfig()}
  140. for {
  141. err := c.odr.Retrieve(ctx, r)
  142. switch err {
  143. case nil:
  144. r.Proof.Store(batch)
  145. return batch.Write()
  146. case ErrNoPeers:
  147. // if there are no peers to serve, retry later
  148. select {
  149. case <-ctx.Done():
  150. return ctx.Err()
  151. case <-time.After(time.Second * 10):
  152. // stay in the loop and try again
  153. }
  154. default:
  155. return err
  156. }
  157. }
  158. }
  159. // Reset implements core.ChainIndexerBackend
  160. func (c *ChtIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
  161. var root common.Hash
  162. if section > 0 {
  163. root = GetChtRoot(c.diskdb, section-1, lastSectionHead)
  164. }
  165. var err error
  166. c.trie, err = trie.New(root, c.triedb)
  167. if err != nil && c.odr != nil {
  168. err = c.fetchMissingNodes(ctx, section, root)
  169. if err == nil {
  170. c.trie, err = trie.New(root, c.triedb)
  171. }
  172. }
  173. c.section = section
  174. return err
  175. }
  176. // Process implements core.ChainIndexerBackend
  177. func (c *ChtIndexerBackend) Process(ctx context.Context, header *types.Header) error {
  178. hash, num := header.Hash(), header.Number.Uint64()
  179. c.lastHash = hash
  180. td := rawdb.ReadTd(c.diskdb, hash, num)
  181. if td == nil {
  182. panic(nil)
  183. }
  184. var encNumber [8]byte
  185. binary.BigEndian.PutUint64(encNumber[:], num)
  186. data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
  187. c.trie.Update(encNumber[:], data)
  188. return nil
  189. }
  190. // Commit implements core.ChainIndexerBackend
  191. func (c *ChtIndexerBackend) Commit() error {
  192. root, err := c.trie.Commit(nil)
  193. if err != nil {
  194. return err
  195. }
  196. c.triedb.Commit(root, false)
  197. log.Info("Storing CHT", "section", c.section, "head", fmt.Sprintf("%064x", c.lastHash), "root", fmt.Sprintf("%064x", root))
  198. StoreChtRoot(c.diskdb, c.section, c.lastHash, root)
  199. return nil
  200. }
  201. var (
  202. bloomTriePrefix = []byte("bltRoot-") // bloomTriePrefix + bloomTrieNum (uint64 big endian) -> trie root hash
  203. BloomTrieTablePrefix = "blt-"
  204. )
  205. // GetBloomTrieRoot reads the BloomTrie root assoctiated to the given section from the database
  206. func GetBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  207. var encNumber [8]byte
  208. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  209. data, _ := db.Get(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...))
  210. return common.BytesToHash(data)
  211. }
  212. // StoreBloomTrieRoot writes the BloomTrie root assoctiated to the given section into the database
  213. func StoreBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  214. var encNumber [8]byte
  215. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  216. db.Put(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  217. }
  218. // BloomTrieIndexerBackend implements core.ChainIndexerBackend
  219. type BloomTrieIndexerBackend struct {
  220. diskdb, trieTable ethdb.Database
  221. triedb *trie.Database
  222. odr OdrBackend
  223. section uint64
  224. parentSize uint64
  225. size uint64
  226. bloomTrieRatio uint64
  227. trie *trie.Trie
  228. sectionHeads []common.Hash
  229. }
  230. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  231. func NewBloomTrieIndexer(db ethdb.Database, odr OdrBackend, parentSize, size uint64) *core.ChainIndexer {
  232. trieTable := rawdb.NewTable(db, BloomTrieTablePrefix)
  233. backend := &BloomTrieIndexerBackend{
  234. diskdb: db,
  235. odr: odr,
  236. trieTable: trieTable,
  237. triedb: trie.NewDatabaseWithCache(trieTable, 1), // Use a tiny cache only to keep memory down
  238. parentSize: parentSize,
  239. size: size,
  240. }
  241. backend.bloomTrieRatio = size / parentSize
  242. backend.sectionHeads = make([]common.Hash, backend.bloomTrieRatio)
  243. return core.NewChainIndexer(db, rawdb.NewTable(db, "bltIndex-"), backend, size, 0, time.Millisecond*100, "bloomtrie")
  244. }
  245. // fetchMissingNodes tries to retrieve the last entries of the latest trusted bloom trie from the
  246. // ODR backend in order to be able to add new entries and calculate subsequent root hashes
  247. func (b *BloomTrieIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
  248. indexCh := make(chan uint, types.BloomBitLength)
  249. type res struct {
  250. nodes *NodeSet
  251. err error
  252. }
  253. resCh := make(chan res, types.BloomBitLength)
  254. for i := 0; i < 20; i++ {
  255. go func() {
  256. for bitIndex := range indexCh {
  257. r := &BloomRequest{BloomTrieRoot: root, BloomTrieNum: section - 1, BitIdx: bitIndex, SectionIndexList: []uint64{section - 1}, Config: b.odr.IndexerConfig()}
  258. for {
  259. if err := b.odr.Retrieve(ctx, r); err == ErrNoPeers {
  260. // if there are no peers to serve, retry later
  261. select {
  262. case <-ctx.Done():
  263. resCh <- res{nil, ctx.Err()}
  264. return
  265. case <-time.After(time.Second * 10):
  266. // stay in the loop and try again
  267. }
  268. } else {
  269. resCh <- res{r.Proofs, err}
  270. break
  271. }
  272. }
  273. }
  274. }()
  275. }
  276. for i := uint(0); i < types.BloomBitLength; i++ {
  277. indexCh <- i
  278. }
  279. close(indexCh)
  280. batch := b.trieTable.NewBatch()
  281. for i := uint(0); i < types.BloomBitLength; i++ {
  282. res := <-resCh
  283. if res.err != nil {
  284. return res.err
  285. }
  286. res.nodes.Store(batch)
  287. }
  288. return batch.Write()
  289. }
  290. // Reset implements core.ChainIndexerBackend
  291. func (b *BloomTrieIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
  292. var root common.Hash
  293. if section > 0 {
  294. root = GetBloomTrieRoot(b.diskdb, section-1, lastSectionHead)
  295. }
  296. var err error
  297. b.trie, err = trie.New(root, b.triedb)
  298. if err != nil && b.odr != nil {
  299. err = b.fetchMissingNodes(ctx, section, root)
  300. if err == nil {
  301. b.trie, err = trie.New(root, b.triedb)
  302. }
  303. }
  304. b.section = section
  305. return err
  306. }
  307. // Process implements core.ChainIndexerBackend
  308. func (b *BloomTrieIndexerBackend) Process(ctx context.Context, header *types.Header) error {
  309. num := header.Number.Uint64() - b.section*b.size
  310. if (num+1)%b.parentSize == 0 {
  311. b.sectionHeads[num/b.parentSize] = header.Hash()
  312. }
  313. return nil
  314. }
  315. // Commit implements core.ChainIndexerBackend
  316. func (b *BloomTrieIndexerBackend) Commit() error {
  317. var compSize, decompSize uint64
  318. for i := uint(0); i < types.BloomBitLength; i++ {
  319. var encKey [10]byte
  320. binary.BigEndian.PutUint16(encKey[0:2], uint16(i))
  321. binary.BigEndian.PutUint64(encKey[2:10], b.section)
  322. var decomp []byte
  323. for j := uint64(0); j < b.bloomTrieRatio; j++ {
  324. data, err := rawdb.ReadBloomBits(b.diskdb, i, b.section*b.bloomTrieRatio+j, b.sectionHeads[j])
  325. if err != nil {
  326. return err
  327. }
  328. decompData, err2 := bitutil.DecompressBytes(data, int(b.parentSize/8))
  329. if err2 != nil {
  330. return err2
  331. }
  332. decomp = append(decomp, decompData...)
  333. }
  334. comp := bitutil.CompressBytes(decomp)
  335. decompSize += uint64(len(decomp))
  336. compSize += uint64(len(comp))
  337. if len(comp) > 0 {
  338. b.trie.Update(encKey[:], comp)
  339. } else {
  340. b.trie.Delete(encKey[:])
  341. }
  342. }
  343. root, err := b.trie.Commit(nil)
  344. if err != nil {
  345. return err
  346. }
  347. b.triedb.Commit(root, false)
  348. sectionHead := b.sectionHeads[b.bloomTrieRatio-1]
  349. log.Info("Storing bloom trie", "section", b.section, "head", fmt.Sprintf("%064x", sectionHead), "root", fmt.Sprintf("%064x", root), "compression", float64(compSize)/float64(decompSize))
  350. StoreBloomTrieRoot(b.diskdb, b.section, sectionHead, root)
  351. return nil
  352. }