postprocess.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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: 150,
  51. sectionHead: common.HexToHash("1e2e67f289565cbe7bd4367f7960dbd73a3f7c53439e1047cd7ba331c8109e39"),
  52. chtRoot: common.HexToHash("f2a6c9ca143d647b44523cc249f1072c8912358ab873a77a5fdc792b8df99e80"),
  53. bloomTrieRoot: common.HexToHash("c018952fa1513c97857e79fbb9a37acaf8432d5b85e52a78eca7dff5fd5900ee"),
  54. }
  55. ropstenCheckpoint = trustedCheckpoint{
  56. name: "Ropsten testnet",
  57. sectionIdx: 75,
  58. sectionHead: common.HexToHash("12e68324f4578ea3e8e7fb3968167686729396c9279287fa1f1a8b51bb2d05b4"),
  59. chtRoot: common.HexToHash("3e51dc095c69fa654a4cac766e0afff7357515b4b3c3a379c675f810363e54be"),
  60. bloomTrieRoot: common.HexToHash("33e3a70b33c1d73aa698d496a80615e98ed31fa8f56969876180553b32333339"),
  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. diskdb ethdb.Database
  103. triedb *trie.Database
  104. section, sectionSize uint64
  105. lastHash common.Hash
  106. trie *trie.Trie
  107. }
  108. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  109. func NewChtIndexer(db ethdb.Database, clientMode bool) *core.ChainIndexer {
  110. var sectionSize, confirmReq uint64
  111. if clientMode {
  112. sectionSize = ChtFrequency
  113. confirmReq = HelperTrieConfirmations
  114. } else {
  115. sectionSize = ChtV1Frequency
  116. confirmReq = HelperTrieProcessConfirmations
  117. }
  118. idb := ethdb.NewTable(db, "chtIndex-")
  119. backend := &ChtIndexerBackend{
  120. diskdb: db,
  121. triedb: trie.NewDatabase(ethdb.NewTable(db, ChtTablePrefix)),
  122. sectionSize: sectionSize,
  123. }
  124. return core.NewChainIndexer(db, idb, backend, sectionSize, confirmReq, time.Millisecond*100, "cht")
  125. }
  126. // Reset implements core.ChainIndexerBackend
  127. func (c *ChtIndexerBackend) Reset(section uint64, lastSectionHead common.Hash) error {
  128. var root common.Hash
  129. if section > 0 {
  130. root = GetChtRoot(c.diskdb, section-1, lastSectionHead)
  131. }
  132. var err error
  133. c.trie, err = trie.New(root, c.triedb)
  134. c.section = section
  135. return err
  136. }
  137. // Process implements core.ChainIndexerBackend
  138. func (c *ChtIndexerBackend) Process(header *types.Header) {
  139. hash, num := header.Hash(), header.Number.Uint64()
  140. c.lastHash = hash
  141. td := core.GetTd(c.diskdb, hash, num)
  142. if td == nil {
  143. panic(nil)
  144. }
  145. var encNumber [8]byte
  146. binary.BigEndian.PutUint64(encNumber[:], num)
  147. data, _ := rlp.EncodeToBytes(ChtNode{hash, td})
  148. c.trie.Update(encNumber[:], data)
  149. }
  150. // Commit implements core.ChainIndexerBackend
  151. func (c *ChtIndexerBackend) Commit() error {
  152. root, err := c.trie.Commit(nil)
  153. if err != nil {
  154. return err
  155. }
  156. c.triedb.Commit(root, false)
  157. if ((c.section+1)*c.sectionSize)%ChtFrequency == 0 {
  158. log.Info("Storing CHT", "idx", c.section*c.sectionSize/ChtFrequency, "sectionHead", fmt.Sprintf("%064x", c.lastHash), "root", fmt.Sprintf("%064x", root))
  159. }
  160. StoreChtRoot(c.diskdb, c.section, c.lastHash, root)
  161. return nil
  162. }
  163. const (
  164. BloomTrieFrequency = 32768
  165. ethBloomBitsSection = 4096
  166. ethBloomBitsConfirmations = 256
  167. )
  168. var (
  169. bloomTriePrefix = []byte("bltRoot-") // bloomTriePrefix + bloomTrieNum (uint64 big endian) -> trie root hash
  170. BloomTrieTablePrefix = "blt-"
  171. )
  172. // GetBloomTrieRoot reads the BloomTrie root assoctiated to the given section from the database
  173. func GetBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead common.Hash) common.Hash {
  174. var encNumber [8]byte
  175. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  176. data, _ := db.Get(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...))
  177. return common.BytesToHash(data)
  178. }
  179. // StoreBloomTrieRoot writes the BloomTrie root assoctiated to the given section into the database
  180. func StoreBloomTrieRoot(db ethdb.Database, sectionIdx uint64, sectionHead, root common.Hash) {
  181. var encNumber [8]byte
  182. binary.BigEndian.PutUint64(encNumber[:], sectionIdx)
  183. db.Put(append(append(bloomTriePrefix, encNumber[:]...), sectionHead.Bytes()...), root.Bytes())
  184. }
  185. // BloomTrieIndexerBackend implements core.ChainIndexerBackend
  186. type BloomTrieIndexerBackend struct {
  187. diskdb ethdb.Database
  188. triedb *trie.Database
  189. section, parentSectionSize, bloomTrieRatio uint64
  190. trie *trie.Trie
  191. sectionHeads []common.Hash
  192. }
  193. // NewBloomTrieIndexer creates a BloomTrie chain indexer
  194. func NewBloomTrieIndexer(db ethdb.Database, clientMode bool) *core.ChainIndexer {
  195. backend := &BloomTrieIndexerBackend{
  196. diskdb: db,
  197. triedb: trie.NewDatabase(ethdb.NewTable(db, BloomTrieTablePrefix)),
  198. }
  199. idb := ethdb.NewTable(db, "bltIndex-")
  200. var confirmReq uint64
  201. if clientMode {
  202. backend.parentSectionSize = BloomTrieFrequency
  203. confirmReq = HelperTrieConfirmations
  204. } else {
  205. backend.parentSectionSize = ethBloomBitsSection
  206. confirmReq = HelperTrieProcessConfirmations
  207. }
  208. backend.bloomTrieRatio = BloomTrieFrequency / backend.parentSectionSize
  209. backend.sectionHeads = make([]common.Hash, backend.bloomTrieRatio)
  210. return core.NewChainIndexer(db, idb, backend, BloomTrieFrequency, confirmReq-ethBloomBitsConfirmations, time.Millisecond*100, "bloomtrie")
  211. }
  212. // Reset implements core.ChainIndexerBackend
  213. func (b *BloomTrieIndexerBackend) Reset(section uint64, lastSectionHead common.Hash) error {
  214. var root common.Hash
  215. if section > 0 {
  216. root = GetBloomTrieRoot(b.diskdb, section-1, lastSectionHead)
  217. }
  218. var err error
  219. b.trie, err = trie.New(root, b.triedb)
  220. b.section = section
  221. return err
  222. }
  223. // Process implements core.ChainIndexerBackend
  224. func (b *BloomTrieIndexerBackend) Process(header *types.Header) {
  225. num := header.Number.Uint64() - b.section*BloomTrieFrequency
  226. if (num+1)%b.parentSectionSize == 0 {
  227. b.sectionHeads[num/b.parentSectionSize] = header.Hash()
  228. }
  229. }
  230. // Commit implements core.ChainIndexerBackend
  231. func (b *BloomTrieIndexerBackend) Commit() error {
  232. var compSize, decompSize uint64
  233. for i := uint(0); i < types.BloomBitLength; i++ {
  234. var encKey [10]byte
  235. binary.BigEndian.PutUint16(encKey[0:2], uint16(i))
  236. binary.BigEndian.PutUint64(encKey[2:10], b.section)
  237. var decomp []byte
  238. for j := uint64(0); j < b.bloomTrieRatio; j++ {
  239. data, err := core.GetBloomBits(b.diskdb, i, b.section*b.bloomTrieRatio+j, b.sectionHeads[j])
  240. if err != nil {
  241. return err
  242. }
  243. decompData, err2 := bitutil.DecompressBytes(data, int(b.parentSectionSize/8))
  244. if err2 != nil {
  245. return err2
  246. }
  247. decomp = append(decomp, decompData...)
  248. }
  249. comp := bitutil.CompressBytes(decomp)
  250. decompSize += uint64(len(decomp))
  251. compSize += uint64(len(comp))
  252. if len(comp) > 0 {
  253. b.trie.Update(encKey[:], comp)
  254. } else {
  255. b.trie.Delete(encKey[:])
  256. }
  257. }
  258. root, err := b.trie.Commit(nil)
  259. if err != nil {
  260. return err
  261. }
  262. b.triedb.Commit(root, false)
  263. sectionHead := b.sectionHeads[b.bloomTrieRatio-1]
  264. log.Info("Storing BloomTrie", "section", b.section, "sectionHead", fmt.Sprintf("%064x", sectionHead), "root", fmt.Sprintf("%064x", root), "compression ratio", float64(compSize)/float64(decompSize))
  265. StoreBloomTrieRoot(b.diskdb, b.section, sectionHead, root)
  266. return nil
  267. }