postprocess.go 14 KB

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