postprocess.go 15 KB

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