postprocess.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. "encoding/binary"
  19. "errors"
  20. "math/big"
  21. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/bitutil"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/rawdb"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/params"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. "github.com/ethereum/go-ethereum/trie"
  32. )
  33. const (
  34. // CHTFrequencyClient is the block frequency for creating CHTs on the client side.
  35. CHTFrequencyClient = 32768
  36. // CHTFrequencyServer is the block frequency for creating CHTs on the server side.
  37. // Eventually this can be merged back with the client version, but that requires a
  38. // full database upgrade, so that should be left for a suitable moment.
  39. CHTFrequencyServer = 4096
  40. HelperTrieConfirmations = 2048 // number of confirmations before a server is expected to have the given HelperTrie available
  41. HelperTrieProcessConfirmations = 256 // number of confirmations before a HelperTrie is generated
  42. )
  43. // trustedCheckpoint represents a set of post-processed trie roots (CHT and BloomTrie) associated with
  44. // the appropriate section index and head hash. It is used to start light syncing from this checkpoint
  45. // and avoid downloading the entire header chain while still being able to securely access old headers/logs.
  46. type trustedCheckpoint struct {
  47. name string
  48. sectionIdx uint64
  49. sectionHead, chtRoot, bloomTrieRoot common.Hash
  50. }
  51. var (
  52. mainnetCheckpoint = trustedCheckpoint{
  53. name: "mainnet",
  54. sectionIdx: 170,
  55. sectionHead: common.HexToHash("3bb2c28bcce463d57968f14f56cdb3fbf35349ab7a701f44c1afb57349c9a356"),
  56. chtRoot: common.HexToHash("d92b6d0853455f8439086292338e87f69781921680dd7aa072fb71547b87415e"),
  57. bloomTrieRoot: common.HexToHash("e4e8250a2fefddead7ae42daecd848cbf9b66d748a8270f8bbd4370b764bb9e9"),
  58. }
  59. ropstenCheckpoint = trustedCheckpoint{
  60. name: "ropsten",
  61. sectionIdx: 97,
  62. sectionHead: common.HexToHash("719448c67c01eb5b9f27833a36a4e34612f66801316d7ff37daf9e77fb4cd095"),
  63. chtRoot: common.HexToHash("a7857afc15930ca6e583b6c3d563a025144011655843d52d28e2fdaadd417bea"),
  64. bloomTrieRoot: common.HexToHash("9c71d4b50cbec86dfeaa8e08992de8a4667b81d13c54d6522b17ce2fc5d36416"),
  65. }
  66. )
  67. // trustedCheckpoints associates each known checkpoint with the genesis hash of the chain it belongs to
  68. var trustedCheckpoints = map[common.Hash]trustedCheckpoint{
  69. params.MainnetGenesisHash: mainnetCheckpoint,
  70. params.TestnetGenesisHash: ropstenCheckpoint,
  71. }
  72. var (
  73. ErrNoTrustedCht = errors.New("No trusted canonical hash trie")
  74. ErrNoTrustedBloomTrie = errors.New("No trusted bloom trie")
  75. ErrNoHeader = errors.New("Header not found")
  76. chtPrefix = []byte("chtRoot-") // chtPrefix + chtNum (uint64 big endian) -> trie root hash
  77. ChtTablePrefix = "cht-"
  78. )
  79. // ChtNode structures are stored in the Canonical Hash Trie in an RLP encoded format
  80. type ChtNode struct {
  81. Hash common.Hash
  82. Td *big.Int
  83. }
  84. // GetChtRoot reads the CHT root assoctiated to the given section from the database
  85. // Note that sectionIdx is specified according to LES/1 CHT section size
  86. func GetChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  87. var encNumber [8]byte
  88. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  89. data, _ := db.Get(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...))
  90. return common.BytesToHash(data)
  91. }
  92. // GetChtV2Root reads the CHT root assoctiated to the given section from the database
  93. // Note that sectionIdx is specified according to LES/2 CHT section size
  94. func GetChtV2Root(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  95. return GetChtRoot(db, (sectionIdx+1)*(CHTFrequencyClient/CHTFrequencyServer)-1, sectionHead)
  96. }
  97. // StoreChtRoot writes the CHT root assoctiated to the given section into the database
  98. // Note that sectionIdx is specified according to LES/1 CHT section size
  99. func StoreChtRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  100. var encNumber [8]byte
  101. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  102. db.Put(append(append(chtPrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  103. }
  104. // ChtIndexerBackend implements core.ChainIndexerBackend
  105. type ChtIndexerBackend struct {
  106. diskdb ethdb.Database
  107. triedb *trie.Database
  108. section, sectionSize uint64
  109. lastHash common.Hash
  110. trie *trie.Trie
  111. }
  112. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  113. func NewChtIndexer(db ethdb.Database, clientMode bool) *core.ChainIndexer {
  114. var sectionSize, confirmReq uint64
  115. if clientMode {
  116. sectionSize = CHTFrequencyClient
  117. confirmReq = HelperTrieConfirmations
  118. } else {
  119. sectionSize = CHTFrequencyServer
  120. confirmReq = HelperTrieProcessConfirmations
  121. }
  122. idb := ethdb.NewTable(db, "chtIndex-")
  123. backend := &ChtIndexerBackend{
  124. diskdb: db,
  125. triedb: trie.NewDatabase(ethdb.NewTable(db, ChtTablePrefix)),
  126. sectionSize: sectionSize,
  127. }
  128. return core.NewChainIndexer(db, idb, backend, sectionSize, confirmReq, time.Millisecond*100, "cht")
  129. }
  130. // Reset implements core.ChainIndexerBackend
  131. func (c *ChtIndexerBackend) Reset(section uint64, lastSectionHead common.Hash) error {
  132. var root common.Hash
  133. if section > 0 {
  134. root = GetChtRoot(c.diskdb, section-1, lastSectionHead)
  135. }
  136. var err error
  137. c.trie, err = trie.New(root, c.triedb)
  138. c.section = section
  139. return err
  140. }
  141. // Process implements core.ChainIndexerBackend
  142. func (c *ChtIndexerBackend) Process(header *types.Header) {
  143. hash, num := header.Hash(), header.Number.Uint64()
  144. c.lastHash = hash
  145. td := rawdb.ReadTd(c.diskdb, hash, num)
  146. if td == nil {
  147. panic(nil)
  148. }
  149. var encNumber [8]byte
  150. binary.BigEndian.PutUint64(encNumber[:], num)
  151. data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
  152. c.trie.Update(encNumber[:], data)
  153. }
  154. // Commit implements core.ChainIndexerBackend
  155. func (c *ChtIndexerBackend) Commit() error {
  156. root, err := c.trie.Commit(nil)
  157. if err != nil {
  158. return err
  159. }
  160. c.triedb.Commit(root, false)
  161. if ((c.section+1)*c.sectionSize)%CHTFrequencyClient == 0 {
  162. log.Info("Storing CHT", "section", c.section*c.sectionSize/CHTFrequencyClient, "head", c.lastHash, "root", root)
  163. }
  164. StoreChtRoot(c.diskdb, c.section, c.lastHash, root)
  165. return nil
  166. }
  167. const (
  168. BloomTrieFrequency = 32768
  169. ethBloomBitsSection = 4096
  170. ethBloomBitsConfirmations = 256
  171. )
  172. var (
  173. bloomTriePrefix = []byte("bltRoot-") // bloomTriePrefix + bloomTrieNum (uint64 big endian) -> trie root hash
  174. BloomTrieTablePrefix = "blt-"
  175. )
  176. // GetBloomTrieRoot reads the BloomTrie root assoctiated to the given section from the database
  177. func GetBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  178. var encNumber [8]byte
  179. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  180. data, _ := db.Get(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...))
  181. return common.BytesToHash(data)
  182. }
  183. // StoreBloomTrieRoot writes the BloomTrie root assoctiated to the given section into the database
  184. func StoreBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  185. var encNumber [8]byte
  186. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  187. db.Put(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  188. }
  189. // BloomTrieIndexerBackend implements core.ChainIndexerBackend
  190. type BloomTrieIndexerBackend struct {
  191. diskdb ethdb.Database
  192. triedb *trie.Database
  193. section, parentSectionSize, bloomTrieRatio uint64
  194. trie *trie.Trie
  195. sectionHeads []common.Hash
  196. }
  197. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  198. func NewBloomTrieIndexer(db ethdb.Database, clientMode bool) *core.ChainIndexer {
  199. backend := &BloomTrieIndexerBackend{
  200. diskdb: db,
  201. triedb: trie.NewDatabase(ethdb.NewTable(db, BloomTrieTablePrefix)),
  202. }
  203. idb := ethdb.NewTable(db, "bltIndex-")
  204. var confirmReq uint64
  205. if clientMode {
  206. backend.parentSectionSize = BloomTrieFrequency
  207. confirmReq = HelperTrieConfirmations
  208. } else {
  209. backend.parentSectionSize = ethBloomBitsSection
  210. confirmReq = HelperTrieProcessConfirmations
  211. }
  212. backend.bloomTrieRatio = BloomTrieFrequency / backend.parentSectionSize
  213. backend.sectionHeads = make([]common.Hash, backend.bloomTrieRatio)
  214. return core.NewChainIndexer(db, idb, backend, BloomTrieFrequency, confirmReq-ethBloomBitsConfirmations, time.Millisecond*100, "bloomtrie")
  215. }
  216. // Reset implements core.ChainIndexerBackend
  217. func (b *BloomTrieIndexerBackend) Reset(section uint64, lastSectionHead common.Hash) error {
  218. var root common.Hash
  219. if section > 0 {
  220. root = GetBloomTrieRoot(b.diskdb, section-1, lastSectionHead)
  221. }
  222. var err error
  223. b.trie, err = trie.New(root, b.triedb)
  224. b.section = section
  225. return err
  226. }
  227. // Process implements core.ChainIndexerBackend
  228. func (b *BloomTrieIndexerBackend) Process(header *types.Header) {
  229. num := header.Number.Uint64() - b.section*BloomTrieFrequency
  230. if (num+1)%b.parentSectionSize == 0 {
  231. b.sectionHeads[num/b.parentSectionSize] = header.Hash()
  232. }
  233. }
  234. // Commit implements core.ChainIndexerBackend
  235. func (b *BloomTrieIndexerBackend) Commit() error {
  236. var compSize, decompSize uint64
  237. for i := uint(0); i < types.BloomBitLength; i++ {
  238. var encKey [10]byte
  239. binary.BigEndian.PutUint16(encKey[0:2], uint16(i))
  240. binary.BigEndian.PutUint64(encKey[2:10], b.section)
  241. var decomp []byte
  242. for j := uint64(0); j < b.bloomTrieRatio; j++ {
  243. data, err := rawdb.ReadBloomBits(b.diskdb, i, b.section*b.bloomTrieRatio+j, b.sectionHeads[j])
  244. if err != nil {
  245. return err
  246. }
  247. decompData, err2 := bitutil.DecompressBytes(data, int(b.parentSectionSize/8))
  248. if err2 != nil {
  249. return err2
  250. }
  251. decomp = append(decomp, decompData...)
  252. }
  253. comp := bitutil.CompressBytes(decomp)
  254. decompSize += uint64(len(decomp))
  255. compSize += uint64(len(comp))
  256. if len(comp) > 0 {
  257. b.trie.Update(encKey[:], comp)
  258. } else {
  259. b.trie.Delete(encKey[:])
  260. }
  261. }
  262. root, err := b.trie.Commit(nil)
  263. if err != nil {
  264. return err
  265. }
  266. b.triedb.Commit(root, false)
  267. sectionHead := b.sectionHeads[b.bloomTrieRatio-1]
  268. log.Info("Storing bloom trie", "section", b.section, "head", sectionHead, "root", root, "compression", float64(compSize)/float64(decompSize))
  269. StoreBloomTrieRoot(b.diskdb, b.section, sectionHead, root)
  270. return nil
  271. }