postprocess.go 11 KB

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