postprocess.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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: 512,
  73. ChtConfirms: 4,
  74. BloomSize: 64,
  75. BloomConfirms: 4,
  76. BloomTrieSize: 512,
  77. BloomTrieConfirms: 4,
  78. }
  79. // TestClientIndexerConfig wraps a set of configs as a test indexer config for client side.
  80. TestClientIndexerConfig = &IndexerConfig{
  81. ChtSize: 512,
  82. ChtConfirms: 32,
  83. BloomSize: 512,
  84. BloomConfirms: 32,
  85. BloomTrieSize: 512,
  86. BloomTrieConfirms: 32,
  87. }
  88. )
  89. // trustedCheckpoints associates each known checkpoint with the genesis hash of the chain it belongs to
  90. var trustedCheckpoints = map[common.Hash]*params.TrustedCheckpoint{
  91. params.MainnetGenesisHash: params.MainnetTrustedCheckpoint,
  92. params.TestnetGenesisHash: params.TestnetTrustedCheckpoint,
  93. params.RinkebyGenesisHash: params.RinkebyTrustedCheckpoint,
  94. params.GoerliGenesisHash: params.GoerliTrustedCheckpoint,
  95. }
  96. var (
  97. ErrNoTrustedCht = errors.New("no trusted canonical hash trie")
  98. ErrNoTrustedBloomTrie = errors.New("no trusted bloom trie")
  99. ErrNoHeader = errors.New("header not found")
  100. chtPrefix = []byte("chtRootV2-") // chtPrefix + chtNum (uint64 big endian) -> trie root hash
  101. ChtTablePrefix = "cht-"
  102. )
  103. // ChtNode structures are stored in the Canonical Hash Trie in an RLP encoded format
  104. type ChtNode struct {
  105. Hash common.Hash
  106. Td *big.Int
  107. }
  108. // GetChtRoot reads the CHT root associated to the given section from the database
  109. func GetChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  110. var encNumber [8]byte
  111. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  112. data, _ := db.Get(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...))
  113. return common.BytesToHash(data)
  114. }
  115. // StoreChtRoot writes the CHT root associated to the given section into the database
  116. func StoreChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  117. var encNumber [8]byte
  118. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  119. db.Put(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  120. }
  121. // ChtIndexerBackend implements core.ChainIndexerBackend.
  122. type ChtIndexerBackend struct {
  123. diskdb, trieTable ethdb.Database
  124. odr OdrBackend
  125. triedb *trie.Database
  126. section, sectionSize uint64
  127. lastHash common.Hash
  128. trie *trie.Trie
  129. }
  130. // NewChtIndexer creates a Cht chain indexer
  131. func NewChtIndexer(db ethdb.Database, odr OdrBackend, size, confirms uint64) *core.ChainIndexer {
  132. trieTable := rawdb.NewTable(db, ChtTablePrefix)
  133. backend := &ChtIndexerBackend{
  134. diskdb: db,
  135. odr: odr,
  136. trieTable: trieTable,
  137. triedb: trie.NewDatabaseWithCache(trieTable, 1), // Use a tiny cache only to keep memory down
  138. sectionSize: size,
  139. }
  140. return core.NewChainIndexer(db, rawdb.NewTable(db, "chtIndexV2-"), backend, size, confirms, time.Millisecond*100, "cht")
  141. }
  142. // fetchMissingNodes tries to retrieve the last entry of the latest trusted CHT from the
  143. // ODR backend in order to be able to add new entries and calculate subsequent root hashes
  144. func (c *ChtIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
  145. batch := c.trieTable.NewBatch()
  146. r := &ChtRequest{ChtRoot: root, ChtNum: section - 1, BlockNum: section*c.sectionSize - 1, Config: c.odr.IndexerConfig()}
  147. for {
  148. err := c.odr.Retrieve(ctx, r)
  149. switch err {
  150. case nil:
  151. r.Proof.Store(batch)
  152. return batch.Write()
  153. case ErrNoPeers:
  154. // if there are no peers to serve, retry later
  155. select {
  156. case <-ctx.Done():
  157. return ctx.Err()
  158. case <-time.After(time.Second * 10):
  159. // stay in the loop and try again
  160. }
  161. default:
  162. return err
  163. }
  164. }
  165. }
  166. // Reset implements core.ChainIndexerBackend
  167. func (c *ChtIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
  168. var root common.Hash
  169. if section > 0 {
  170. root = GetChtRoot(c.diskdb, section-1, lastSectionHead)
  171. }
  172. var err error
  173. c.trie, err = trie.New(root, c.triedb)
  174. if err != nil && c.odr != nil {
  175. err = c.fetchMissingNodes(ctx, section, root)
  176. if err == nil {
  177. c.trie, err = trie.New(root, c.triedb)
  178. }
  179. }
  180. c.section = section
  181. return err
  182. }
  183. // Process implements core.ChainIndexerBackend
  184. func (c *ChtIndexerBackend) Process(ctx context.Context, header *types.Header) error {
  185. hash, num := header.Hash(), header.Number.Uint64()
  186. c.lastHash = hash
  187. td := rawdb.ReadTd(c.diskdb, hash, num)
  188. if td == nil {
  189. panic(nil)
  190. }
  191. var encNumber [8]byte
  192. binary.BigEndian.PutUint64(encNumber[:], num)
  193. data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
  194. c.trie.Update(encNumber[:], data)
  195. return nil
  196. }
  197. // Commit implements core.ChainIndexerBackend
  198. func (c *ChtIndexerBackend) Commit() error {
  199. root, err := c.trie.Commit(nil)
  200. if err != nil {
  201. return err
  202. }
  203. c.triedb.Commit(root, false)
  204. log.Info("Storing CHT", "section", c.section, "head", fmt.Sprintf("%064x", c.lastHash), "root", fmt.Sprintf("%064x", root))
  205. StoreChtRoot(c.diskdb, c.section, c.lastHash, root)
  206. return nil
  207. }
  208. var (
  209. bloomTriePrefix = []byte("bltRoot-") // bloomTriePrefix + bloomTrieNum (uint64 big endian) -> trie root hash
  210. BloomTrieTablePrefix = "blt-"
  211. )
  212. // GetBloomTrieRoot reads the BloomTrie root assoctiated to the given section from the database
  213. func GetBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  214. var encNumber [8]byte
  215. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  216. data, _ := db.Get(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...))
  217. return common.BytesToHash(data)
  218. }
  219. // StoreBloomTrieRoot writes the BloomTrie root assoctiated to the given section into the database
  220. func StoreBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  221. var encNumber [8]byte
  222. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  223. db.Put(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  224. }
  225. // BloomTrieIndexerBackend implements core.ChainIndexerBackend
  226. type BloomTrieIndexerBackend struct {
  227. diskdb, trieTable ethdb.Database
  228. triedb *trie.Database
  229. odr OdrBackend
  230. section uint64
  231. parentSize uint64
  232. size uint64
  233. bloomTrieRatio uint64
  234. trie *trie.Trie
  235. sectionHeads []common.Hash
  236. }
  237. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  238. func NewBloomTrieIndexer(db ethdb.Database, odr OdrBackend, parentSize, size uint64) *core.ChainIndexer {
  239. trieTable := rawdb.NewTable(db, BloomTrieTablePrefix)
  240. backend := &BloomTrieIndexerBackend{
  241. diskdb: db,
  242. odr: odr,
  243. trieTable: trieTable,
  244. triedb: trie.NewDatabaseWithCache(trieTable, 1), // Use a tiny cache only to keep memory down
  245. parentSize: parentSize,
  246. size: size,
  247. }
  248. backend.bloomTrieRatio = size / parentSize
  249. backend.sectionHeads = make([]common.Hash, backend.bloomTrieRatio)
  250. return core.NewChainIndexer(db, rawdb.NewTable(db, "bltIndex-"), backend, size, 0, time.Millisecond*100, "bloomtrie")
  251. }
  252. // fetchMissingNodes tries to retrieve the last entries of the latest trusted bloom trie from the
  253. // ODR backend in order to be able to add new entries and calculate subsequent root hashes
  254. func (b *BloomTrieIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
  255. indexCh := make(chan uint, types.BloomBitLength)
  256. type res struct {
  257. nodes *NodeSet
  258. err error
  259. }
  260. resCh := make(chan res, types.BloomBitLength)
  261. for i := 0; i < 20; i++ {
  262. go func() {
  263. for bitIndex := range indexCh {
  264. r := &BloomRequest{BloomTrieRoot: root, BloomTrieNum: section - 1, BitIdx: bitIndex, SectionIndexList: []uint64{section - 1}, Config: b.odr.IndexerConfig()}
  265. for {
  266. if err := b.odr.Retrieve(ctx, r); err == ErrNoPeers {
  267. // if there are no peers to serve, retry later
  268. select {
  269. case <-ctx.Done():
  270. resCh <- res{nil, ctx.Err()}
  271. return
  272. case <-time.After(time.Second * 10):
  273. // stay in the loop and try again
  274. }
  275. } else {
  276. resCh <- res{r.Proofs, err}
  277. break
  278. }
  279. }
  280. }
  281. }()
  282. }
  283. for i := uint(0); i < types.BloomBitLength; i++ {
  284. indexCh <- i
  285. }
  286. close(indexCh)
  287. batch := b.trieTable.NewBatch()
  288. for i := uint(0); i < types.BloomBitLength; i++ {
  289. res := <-resCh
  290. if res.err != nil {
  291. return res.err
  292. }
  293. res.nodes.Store(batch)
  294. }
  295. return batch.Write()
  296. }
  297. // Reset implements core.ChainIndexerBackend
  298. func (b *BloomTrieIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
  299. var root common.Hash
  300. if section > 0 {
  301. root = GetBloomTrieRoot(b.diskdb, section-1, lastSectionHead)
  302. }
  303. var err error
  304. b.trie, err = trie.New(root, b.triedb)
  305. if err != nil && b.odr != nil {
  306. err = b.fetchMissingNodes(ctx, section, root)
  307. if err == nil {
  308. b.trie, err = trie.New(root, b.triedb)
  309. }
  310. }
  311. b.section = section
  312. return err
  313. }
  314. // Process implements core.ChainIndexerBackend
  315. func (b *BloomTrieIndexerBackend) Process(ctx context.Context, header *types.Header) error {
  316. num := header.Number.Uint64() - b.section*b.size
  317. if (num+1)%b.parentSize == 0 {
  318. b.sectionHeads[num/b.parentSize] = header.Hash()
  319. }
  320. return nil
  321. }
  322. // Commit implements core.ChainIndexerBackend
  323. func (b *BloomTrieIndexerBackend) Commit() error {
  324. var compSize, decompSize uint64
  325. for i := uint(0); i < types.BloomBitLength; i++ {
  326. var encKey [10]byte
  327. binary.BigEndian.PutUint16(encKey[0:2], uint16(i))
  328. binary.BigEndian.PutUint64(encKey[2:10], b.section)
  329. var decomp []byte
  330. for j := uint64(0); j < b.bloomTrieRatio; j++ {
  331. data, err := rawdb.ReadBloomBits(b.diskdb, i, b.section*b.bloomTrieRatio+j, b.sectionHeads[j])
  332. if err != nil {
  333. return err
  334. }
  335. decompData, err2 := bitutil.DecompressBytes(data, int(b.parentSize/8))
  336. if err2 != nil {
  337. return err2
  338. }
  339. decomp = append(decomp, decompData...)
  340. }
  341. comp := bitutil.CompressBytes(decomp)
  342. decompSize += uint64(len(decomp))
  343. compSize += uint64(len(comp))
  344. if len(comp) > 0 {
  345. b.trie.Update(encKey[:], comp)
  346. } else {
  347. b.trie.Delete(encKey[:])
  348. }
  349. }
  350. root, err := b.trie.Commit(nil)
  351. if err != nil {
  352. return err
  353. }
  354. b.triedb.Commit(root, false)
  355. sectionHead := b.sectionHeads[b.bloomTrieRatio-1]
  356. log.Info("Storing bloom trie", "section", b.section, "head", fmt.Sprintf("%064x", sectionHead), "root", fmt.Sprintf("%064x", root), "compression", float64(compSize)/float64(decompSize))
  357. StoreBloomTrieRoot(b.diskdb, b.section, sectionHead, root)
  358. return nil
  359. }