postprocess.go 14 KB

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