fetcher_test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Copyright 2019 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 les
  17. import (
  18. "math/big"
  19. "testing"
  20. "time"
  21. "github.com/ethereum/go-ethereum/consensus/ethash"
  22. "github.com/ethereum/go-ethereum/core"
  23. "github.com/ethereum/go-ethereum/core/rawdb"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/light"
  26. "github.com/ethereum/go-ethereum/p2p/enode"
  27. "github.com/ethereum/go-ethereum/params"
  28. )
  29. // verifyImportEvent verifies that one single event arrive on an import channel.
  30. func verifyImportEvent(t *testing.T, imported chan interface{}, arrive bool) {
  31. if arrive {
  32. select {
  33. case <-imported:
  34. case <-time.After(time.Second):
  35. t.Fatalf("import timeout")
  36. }
  37. } else {
  38. select {
  39. case <-imported:
  40. t.Fatalf("import invoked")
  41. case <-time.After(20 * time.Millisecond):
  42. }
  43. }
  44. }
  45. // verifyImportDone verifies that no more events are arriving on an import channel.
  46. func verifyImportDone(t *testing.T, imported chan interface{}) {
  47. select {
  48. case <-imported:
  49. t.Fatalf("extra block imported")
  50. case <-time.After(50 * time.Millisecond):
  51. }
  52. }
  53. // verifyChainHeight verifies the chain height is as expected.
  54. func verifyChainHeight(t *testing.T, fetcher *lightFetcher, height uint64) {
  55. local := fetcher.chain.CurrentHeader().Number.Uint64()
  56. if local != height {
  57. t.Fatalf("chain height mismatch, got %d, want %d", local, height)
  58. }
  59. }
  60. func TestSequentialAnnouncementsLes2(t *testing.T) { testSequentialAnnouncements(t, 2) }
  61. func TestSequentialAnnouncementsLes3(t *testing.T) { testSequentialAnnouncements(t, 3) }
  62. func testSequentialAnnouncements(t *testing.T, protocol int) {
  63. netconfig := testnetConfig{
  64. blocks: 4,
  65. protocol: protocol,
  66. nopruning: true,
  67. }
  68. s, c, teardown := newClientServerEnv(t, netconfig)
  69. defer teardown()
  70. // Create connected peer pair, the initial signal from LES server
  71. // is discarded to prevent syncing.
  72. p1, _, err := newTestPeerPair("peer", protocol, s.handler, c.handler, true)
  73. if err != nil {
  74. t.Fatalf("Failed to create peer pair %v", err)
  75. }
  76. importCh := make(chan interface{})
  77. c.handler.fetcher.newHeadHook = func(header *types.Header) {
  78. importCh <- header
  79. }
  80. for i := uint64(1); i <= s.backend.Blockchain().CurrentHeader().Number.Uint64(); i++ {
  81. header := s.backend.Blockchain().GetHeaderByNumber(i)
  82. hash, number := header.Hash(), header.Number.Uint64()
  83. td := rawdb.ReadTd(s.db, hash, number)
  84. announce := announceData{hash, number, td, 0, nil}
  85. if p1.cpeer.announceType == announceTypeSigned {
  86. announce.sign(s.handler.server.privateKey)
  87. }
  88. p1.cpeer.sendAnnounce(announce)
  89. verifyImportEvent(t, importCh, true)
  90. }
  91. verifyImportDone(t, importCh)
  92. verifyChainHeight(t, c.handler.fetcher, 4)
  93. }
  94. func TestGappedAnnouncementsLes2(t *testing.T) { testGappedAnnouncements(t, 2) }
  95. func TestGappedAnnouncementsLes3(t *testing.T) { testGappedAnnouncements(t, 3) }
  96. func testGappedAnnouncements(t *testing.T, protocol int) {
  97. netconfig := testnetConfig{
  98. blocks: 4,
  99. protocol: protocol,
  100. nopruning: true,
  101. }
  102. s, c, teardown := newClientServerEnv(t, netconfig)
  103. defer teardown()
  104. // Create connected peer pair, the initial signal from LES server
  105. // is discarded to prevent syncing.
  106. peer, _, err := newTestPeerPair("peer", protocol, s.handler, c.handler, true)
  107. if err != nil {
  108. t.Fatalf("Failed to create peer pair %v", err)
  109. }
  110. done := make(chan *types.Header, 1)
  111. c.handler.fetcher.newHeadHook = func(header *types.Header) { done <- header }
  112. // Prepare announcement by latest header.
  113. latest := s.backend.Blockchain().CurrentHeader()
  114. hash, number := latest.Hash(), latest.Number.Uint64()
  115. td := rawdb.ReadTd(s.db, hash, number)
  116. // Sign the announcement if necessary.
  117. announce := announceData{hash, number, td, 0, nil}
  118. if peer.cpeer.announceType == announceTypeSigned {
  119. announce.sign(s.handler.server.privateKey)
  120. }
  121. peer.cpeer.sendAnnounce(announce)
  122. <-done // Wait syncing
  123. verifyChainHeight(t, c.handler.fetcher, 4)
  124. // Send a reorged announcement
  125. blocks, _ := core.GenerateChain(rawdb.ReadChainConfig(s.db, s.backend.Blockchain().Genesis().Hash()), s.backend.Blockchain().GetBlockByNumber(3),
  126. ethash.NewFaker(), s.db, 2, func(i int, gen *core.BlockGen) {
  127. gen.OffsetTime(-9) // higher block difficulty
  128. })
  129. s.backend.Blockchain().InsertChain(blocks)
  130. <-done // Wait syncing
  131. verifyChainHeight(t, c.handler.fetcher, 5)
  132. }
  133. func TestTrustedAnnouncementsLes2(t *testing.T) { testTrustedAnnouncement(t, 2) }
  134. func TestTrustedAnnouncementsLes3(t *testing.T) { testTrustedAnnouncement(t, 3) }
  135. func testTrustedAnnouncement(t *testing.T, protocol int) {
  136. //log.Root().SetHandler(log.LvlFilterHandler(log.LvlDebug, log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
  137. var (
  138. servers []*testServer
  139. teardowns []func()
  140. nodes []*enode.Node
  141. ids []string
  142. cpeers []*clientPeer
  143. config = light.TestServerIndexerConfig
  144. waitIndexers = func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  145. for {
  146. cs, _, _ := cIndexer.Sections()
  147. bts, _, _ := btIndexer.Sections()
  148. if cs >= 2 && bts >= 2 {
  149. break
  150. }
  151. time.Sleep(10 * time.Millisecond)
  152. }
  153. }
  154. )
  155. for i := 0; i < 4; i++ {
  156. s, n, teardown := newTestServerPeer(t, int(2*config.ChtSize+config.ChtConfirms), protocol, waitIndexers)
  157. servers = append(servers, s)
  158. nodes = append(nodes, n)
  159. teardowns = append(teardowns, teardown)
  160. // A half of them are trusted servers.
  161. if i < 2 {
  162. ids = append(ids, n.String())
  163. }
  164. }
  165. netconfig := testnetConfig{
  166. protocol: protocol,
  167. nopruning: true,
  168. ulcServers: ids,
  169. ulcFraction: 60,
  170. }
  171. _, c, teardown := newClientServerEnv(t, netconfig)
  172. defer teardown()
  173. defer func() {
  174. for i := 0; i < len(teardowns); i++ {
  175. teardowns[i]()
  176. }
  177. }()
  178. // Register the assembled checkpoint as hardcoded one.
  179. head := servers[0].chtIndexer.SectionHead(0)
  180. cp := &params.TrustedCheckpoint{
  181. SectionIndex: 0,
  182. SectionHead: head,
  183. CHTRoot: light.GetChtRoot(servers[0].db, 0, head),
  184. BloomRoot: light.GetBloomTrieRoot(servers[0].db, 0, head),
  185. }
  186. c.handler.checkpoint = cp
  187. c.handler.backend.blockchain.AddTrustedCheckpoint(cp)
  188. // Connect all server instances.
  189. for i := 0; i < len(servers); i++ {
  190. _, cp, err := connect(servers[i].handler, nodes[i].ID(), c.handler, protocol, true)
  191. if err != nil {
  192. t.Fatalf("connect server and client failed, err %s", err)
  193. }
  194. cpeers = append(cpeers, cp)
  195. }
  196. newHead := make(chan *types.Header, 1)
  197. c.handler.fetcher.newHeadHook = func(header *types.Header) { newHead <- header }
  198. check := func(height []uint64, expected uint64, callback func()) {
  199. for i := 0; i < len(height); i++ {
  200. for j := 0; j < len(servers); j++ {
  201. h := servers[j].backend.Blockchain().GetHeaderByNumber(height[i])
  202. hash, number := h.Hash(), h.Number.Uint64()
  203. td := rawdb.ReadTd(servers[j].db, hash, number)
  204. // Sign the announcement if necessary.
  205. announce := announceData{hash, number, td, 0, nil}
  206. p := cpeers[j]
  207. if p.announceType == announceTypeSigned {
  208. announce.sign(servers[j].handler.server.privateKey)
  209. }
  210. p.sendAnnounce(announce)
  211. }
  212. }
  213. if callback != nil {
  214. callback()
  215. }
  216. verifyChainHeight(t, c.handler.fetcher, expected)
  217. }
  218. check([]uint64{1}, 1, func() { <-newHead }) // Sequential announcements
  219. check([]uint64{config.ChtSize + config.ChtConfirms}, config.ChtSize+config.ChtConfirms, func() { <-newHead }) // ULC-style light syncing, rollback untrusted headers
  220. check([]uint64{2*config.ChtSize + config.ChtConfirms}, 2*config.ChtSize+config.ChtConfirms, func() { <-newHead }) // Sync the whole chain.
  221. }
  222. func TestInvalidAnnouncesLES2(t *testing.T) { testInvalidAnnounces(t, lpv2) }
  223. func TestInvalidAnnouncesLES3(t *testing.T) { testInvalidAnnounces(t, lpv3) }
  224. func TestInvalidAnnouncesLES4(t *testing.T) { testInvalidAnnounces(t, lpv4) }
  225. func testInvalidAnnounces(t *testing.T, protocol int) {
  226. netconfig := testnetConfig{
  227. blocks: 4,
  228. protocol: protocol,
  229. nopruning: true,
  230. }
  231. s, c, teardown := newClientServerEnv(t, netconfig)
  232. defer teardown()
  233. // Create connected peer pair, the initial signal from LES server
  234. // is discarded to prevent syncing.
  235. peer, _, err := newTestPeerPair("peer", lpv3, s.handler, c.handler, true)
  236. if err != nil {
  237. t.Fatalf("Failed to create peer pair %v", err)
  238. }
  239. done := make(chan *types.Header, 1)
  240. c.handler.fetcher.newHeadHook = func(header *types.Header) { done <- header }
  241. // Prepare announcement by latest header.
  242. headerOne := s.backend.Blockchain().GetHeaderByNumber(1)
  243. hash, number := headerOne.Hash(), headerOne.Number.Uint64()
  244. td := big.NewInt(params.GenesisDifficulty.Int64() + 200) // bad td
  245. // Sign the announcement if necessary.
  246. announce := announceData{hash, number, td, 0, nil}
  247. if peer.cpeer.announceType == announceTypeSigned {
  248. announce.sign(s.handler.server.privateKey)
  249. }
  250. peer.cpeer.sendAnnounce(announce)
  251. <-done // Wait syncing
  252. // Ensure the bad peer is evicited
  253. if c.handler.backend.peers.len() != 0 {
  254. t.Fatalf("Failed to evict invalid peer")
  255. }
  256. }