postprocess.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. const (
  36. // CHTFrequencyClient is the block frequency for creating CHTs on the client side.
  37. CHTFrequencyClient = 32768
  38. // CHTFrequencyServer is the block frequency for creating CHTs on the server side.
  39. // Eventually this can be merged back with the client version, but that requires a
  40. // full database upgrade, so that should be left for a suitable moment.
  41. CHTFrequencyServer = 4096
  42. HelperTrieConfirmations = 2048 // number of confirmations before a server is expected to have the given HelperTrie available
  43. HelperTrieProcessConfirmations = 256 // number of confirmations before a HelperTrie is generated
  44. )
  45. // TrustedCheckpoint represents a set of post-processed trie roots (CHT and BloomTrie) associated with
  46. // the appropriate section index and head hash. It is used to start light syncing from this checkpoint
  47. // and avoid downloading the entire header chain while still being able to securely access old headers/logs.
  48. type TrustedCheckpoint struct {
  49. name string
  50. SectionIdx uint64
  51. SectionHead, CHTRoot, BloomRoot common.Hash
  52. }
  53. var (
  54. mainnetCheckpoint = TrustedCheckpoint{
  55. name: "mainnet",
  56. SectionIdx: 187,
  57. SectionHead: common.HexToHash("e6baa034efa31562d71ff23676512dec6562c1ad0301e08843b907e81958c696"),
  58. CHTRoot: common.HexToHash("28001955219719cf06de1b08648969139d123a9835fc760547a1e4dabdabc15a"),
  59. BloomRoot: common.HexToHash("395ca2373fc662720ac6b58b3bbe71f68aa0f38b63b2d3553dd32ff3c51eebc4"),
  60. }
  61. ropstenCheckpoint = TrustedCheckpoint{
  62. name: "ropsten",
  63. SectionIdx: 117,
  64. SectionHead: common.HexToHash("9529b38631ae30783f56cbe4c3b9f07575b770ecba4f6e20a274b1e2f40fede1"),
  65. CHTRoot: common.HexToHash("6f48e9f101f1fac98e7d74fbbcc4fda138358271ffd974d40d2506f0308bb363"),
  66. BloomRoot: common.HexToHash("8242342e66e942c0cd893484e6736b9862ceb88b43ca344bb06a8285ac1b6d64"),
  67. }
  68. )
  69. // trustedCheckpoints associates each known checkpoint with the genesis hash of the chain it belongs to
  70. var trustedCheckpoints = map[common.Hash]TrustedCheckpoint{
  71. params.MainnetGenesisHash: mainnetCheckpoint,
  72. params.TestnetGenesisHash: ropstenCheckpoint,
  73. }
  74. var (
  75. ErrNoTrustedCht = errors.New("No trusted canonical hash trie")
  76. ErrNoTrustedBloomTrie = errors.New("No trusted bloom trie")
  77. ErrNoHeader = errors.New("Header not found")
  78. chtPrefix = []byte("chtRoot-") // chtPrefix + chtNum (uint64 big endian) -> trie root hash
  79. ChtTablePrefix = "cht-"
  80. )
  81. // ChtNode structures are stored in the Canonical Hash Trie in an RLP encoded format
  82. type ChtNode struct {
  83. Hash common.Hash
  84. Td *big.Int
  85. }
  86. // GetChtRoot reads the CHT root assoctiated to the given section from the database
  87. // Note that sectionIdx is specified according to LES/1 CHT section size
  88. func GetChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  89. var encNumber [8]byte
  90. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  91. data, _ := db.Get(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...))
  92. return common.BytesToHash(data)
  93. }
  94. // GetChtV2Root reads the CHT root assoctiated to the given section from the database
  95. // Note that sectionIdx is specified according to LES/2 CHT section size
  96. func GetChtV2Root(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  97. return GetChtRoot(db, (sectionIdx+1)*(CHTFrequencyClient/CHTFrequencyServer)-1, sectionHead)
  98. }
  99. // StoreChtRoot writes the CHT root assoctiated to the given section into the database
  100. // Note that sectionIdx is specified according to LES/1 CHT section size
  101. func StoreChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  102. var encNumber [8]byte
  103. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  104. db.Put(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  105. }
  106. // ChtIndexerBackend implements core.ChainIndexerBackend
  107. type ChtIndexerBackend struct {
  108. diskdb, trieTable ethdb.Database
  109. odr OdrBackend
  110. triedb *trie.Database
  111. section, sectionSize uint64
  112. lastHash common.Hash
  113. trie *trie.Trie
  114. }
  115. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  116. func NewChtIndexer(db ethdb.Database, clientMode bool, odr OdrBackend) *core.ChainIndexer {
  117. var sectionSize, confirmReq uint64
  118. if clientMode {
  119. sectionSize = CHTFrequencyClient
  120. confirmReq = HelperTrieConfirmations
  121. } else {
  122. sectionSize = CHTFrequencyServer
  123. confirmReq = HelperTrieProcessConfirmations
  124. }
  125. idb := ethdb.NewTable(db, "chtIndex-")
  126. trieTable := ethdb.NewTable(db, ChtTablePrefix)
  127. backend := &ChtIndexerBackend{
  128. diskdb: db,
  129. odr: odr,
  130. trieTable: trieTable,
  131. triedb: trie.NewDatabase(trieTable),
  132. sectionSize: sectionSize,
  133. }
  134. return core.NewChainIndexer(db, idb, backend, sectionSize, confirmReq, time.Millisecond*100, "cht")
  135. }
  136. // fetchMissingNodes tries to retrieve the last entry of the latest trusted CHT from the
  137. // ODR backend in order to be able to add new entries and calculate subsequent root hashes
  138. func (c *ChtIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
  139. batch := c.trieTable.NewBatch()
  140. r := &ChtRequest{ChtRoot: root, ChtNum: section - 1, BlockNum: section*c.sectionSize - 1}
  141. for {
  142. err := c.odr.Retrieve(ctx, r)
  143. switch err {
  144. case nil:
  145. r.Proof.Store(batch)
  146. return batch.Write()
  147. case ErrNoPeers:
  148. // if there are no peers to serve, retry later
  149. select {
  150. case <-ctx.Done():
  151. return ctx.Err()
  152. case <-time.After(time.Second * 10):
  153. // stay in the loop and try again
  154. }
  155. default:
  156. return err
  157. }
  158. }
  159. }
  160. // Reset implements core.ChainIndexerBackend
  161. func (c *ChtIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
  162. var root common.Hash
  163. if section > 0 {
  164. root = GetChtRoot(c.diskdb, section-1, lastSectionHead)
  165. }
  166. var err error
  167. c.trie, err = trie.New(root, c.triedb)
  168. if err != nil && c.odr != nil {
  169. err = c.fetchMissingNodes(ctx, section, root)
  170. if err == nil {
  171. c.trie, err = trie.New(root, c.triedb)
  172. }
  173. }
  174. c.section = section
  175. return err
  176. }
  177. // Process implements core.ChainIndexerBackend
  178. func (c *ChtIndexerBackend) Process(ctx context.Context, header *types.Header) error {
  179. hash, num := header.Hash(), header.Number.Uint64()
  180. c.lastHash = hash
  181. td := rawdb.ReadTd(c.diskdb, hash, num)
  182. if td == nil {
  183. panic(nil)
  184. }
  185. var encNumber [8]byte
  186. binary.BigEndian.PutUint64(encNumber[:], num)
  187. data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
  188. c.trie.Update(encNumber[:], data)
  189. return nil
  190. }
  191. // Commit implements core.ChainIndexerBackend
  192. func (c *ChtIndexerBackend) Commit() error {
  193. root, err := c.trie.Commit(nil)
  194. if err != nil {
  195. return err
  196. }
  197. c.triedb.Commit(root, false)
  198. if ((c.section+1)*c.sectionSize)%CHTFrequencyClient == 0 {
  199. log.Info("Storing CHT", "section", c.section*c.sectionSize/CHTFrequencyClient, "head", fmt.Sprintf("%064x", c.lastHash), "root", fmt.Sprintf("%064x", root))
  200. }
  201. StoreChtRoot(c.diskdb, c.section, c.lastHash, root)
  202. return nil
  203. }
  204. const (
  205. BloomTrieFrequency = 32768
  206. ethBloomBitsSection = 4096
  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. odr OdrBackend
  229. triedb *trie.Database
  230. section, parentSectionSize, bloomTrieRatio uint64
  231. trie *trie.Trie
  232. sectionHeads []common.Hash
  233. }
  234. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  235. func NewBloomTrieIndexer(db ethdb.Database, clientMode bool, odr OdrBackend) *core.ChainIndexer {
  236. trieTable := ethdb.NewTable(db, BloomTrieTablePrefix)
  237. backend := &BloomTrieIndexerBackend{
  238. diskdb: db,
  239. odr: odr,
  240. trieTable: trieTable,
  241. triedb: trie.NewDatabase(trieTable),
  242. }
  243. idb := ethdb.NewTable(db, "bltIndex-")
  244. if clientMode {
  245. backend.parentSectionSize = BloomTrieFrequency
  246. } else {
  247. backend.parentSectionSize = ethBloomBitsSection
  248. }
  249. backend.bloomTrieRatio = BloomTrieFrequency / backend.parentSectionSize
  250. backend.sectionHeads = make([]common.Hash, backend.bloomTrieRatio)
  251. return core.NewChainIndexer(db, idb, backend, BloomTrieFrequency, 0, time.Millisecond*100, "bloomtrie")
  252. }
  253. // fetchMissingNodes tries to retrieve the last entries of the latest trusted bloom trie from the
  254. // ODR backend in order to be able to add new entries and calculate subsequent root hashes
  255. func (b *BloomTrieIndexerBackend) fetchMissingNodes(ctx context.Context, section uint64, root common.Hash) error {
  256. indexCh := make(chan uint, types.BloomBitLength)
  257. type res struct {
  258. nodes *NodeSet
  259. err error
  260. }
  261. resCh := make(chan res, types.BloomBitLength)
  262. for i := 0; i < 20; i++ {
  263. go func() {
  264. for bitIndex := range indexCh {
  265. r := &BloomRequest{BloomTrieRoot: root, BloomTrieNum: section - 1, BitIdx: bitIndex, SectionIdxList: []uint64{section - 1}}
  266. for {
  267. if err := b.odr.Retrieve(ctx, r); err == ErrNoPeers {
  268. // if there are no peers to serve, retry later
  269. select {
  270. case <-ctx.Done():
  271. resCh <- res{nil, ctx.Err()}
  272. return
  273. case <-time.After(time.Second * 10):
  274. // stay in the loop and try again
  275. }
  276. } else {
  277. resCh <- res{r.Proofs, err}
  278. break
  279. }
  280. }
  281. }
  282. }()
  283. }
  284. for i := uint(0); i < types.BloomBitLength; i++ {
  285. indexCh <- i
  286. }
  287. close(indexCh)
  288. batch := b.trieTable.NewBatch()
  289. for i := uint(0); i < types.BloomBitLength; i++ {
  290. res := <-resCh
  291. if res.err != nil {
  292. return res.err
  293. }
  294. res.nodes.Store(batch)
  295. }
  296. return batch.Write()
  297. }
  298. // Reset implements core.ChainIndexerBackend
  299. func (b *BloomTrieIndexerBackend) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error {
  300. var root common.Hash
  301. if section > 0 {
  302. root = GetBloomTrieRoot(b.diskdb, section-1, lastSectionHead)
  303. }
  304. var err error
  305. b.trie, err = trie.New(root, b.triedb)
  306. if err != nil && b.odr != nil {
  307. err = b.fetchMissingNodes(ctx, section, root)
  308. if err == nil {
  309. b.trie, err = trie.New(root, b.triedb)
  310. }
  311. }
  312. b.section = section
  313. return err
  314. }
  315. // Process implements core.ChainIndexerBackend
  316. func (b *BloomTrieIndexerBackend) Process(ctx context.Context, header *types.Header) error {
  317. num := header.Number.Uint64() - b.section*BloomTrieFrequency
  318. if (num+1)%b.parentSectionSize == 0 {
  319. b.sectionHeads[num/b.parentSectionSize] = header.Hash()
  320. }
  321. return nil
  322. }
  323. // Commit implements core.ChainIndexerBackend
  324. func (b *BloomTrieIndexerBackend) Commit() error {
  325. var compSize, decompSize uint64
  326. for i := uint(0); i < types.BloomBitLength; i++ {
  327. var encKey [10]byte
  328. binary.BigEndian.PutUint16(encKey[0:2], uint16(i))
  329. binary.BigEndian.PutUint64(encKey[2:10], b.section)
  330. var decomp []byte
  331. for j := uint64(0); j < b.bloomTrieRatio; j++ {
  332. data, err := rawdb.ReadBloomBits(b.diskdb, i, b.section*b.bloomTrieRatio+j, b.sectionHeads[j])
  333. if err != nil {
  334. return err
  335. }
  336. decompData, err2 := bitutil.DecompressBytes(data, int(b.parentSectionSize/8))
  337. if err2 != nil {
  338. return err2
  339. }
  340. decomp = append(decomp, decompData...)
  341. }
  342. comp := bitutil.CompressBytes(decomp)
  343. decompSize += uint64(len(decomp))
  344. compSize += uint64(len(comp))
  345. if len(comp) > 0 {
  346. b.trie.Update(encKey[:], comp)
  347. } else {
  348. b.trie.Delete(encKey[:])
  349. }
  350. }
  351. root, err := b.trie.Commit(nil)
  352. if err != nil {
  353. return err
  354. }
  355. b.triedb.Commit(root, false)
  356. sectionHead := b.sectionHeads[b.bloomTrieRatio-1]
  357. log.Info("Storing bloom trie", "section", b.section, "head", fmt.Sprintf("%064x", sectionHead), "root", fmt.Sprintf("%064x", root), "compression", float64(compSize)/float64(decompSize))
  358. StoreBloomTrieRoot(b.diskdb, b.section, sectionHead, root)
  359. return nil
  360. }