postprocess.go 14 KB

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