sync_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. "fmt"
  19. "math/big"
  20. "testing"
  21. "time"
  22. "github.com/ethereum/go-ethereum/accounts/abi/bind"
  23. "github.com/ethereum/go-ethereum/core"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/crypto"
  26. "github.com/ethereum/go-ethereum/light"
  27. "github.com/ethereum/go-ethereum/params"
  28. )
  29. // Test light syncing which will download all headers from genesis.
  30. func TestLightSyncingLes3(t *testing.T) { testCheckpointSyncing(t, lpv3, 0) }
  31. // Test legacy checkpoint syncing which will download tail headers
  32. // based on a hardcoded checkpoint.
  33. func TestLegacyCheckpointSyncingLes3(t *testing.T) { testCheckpointSyncing(t, lpv3, 1) }
  34. // Test checkpoint syncing which will download tail headers based
  35. // on a verified checkpoint.
  36. func TestCheckpointSyncingLes3(t *testing.T) { testCheckpointSyncing(t, lpv3, 2) }
  37. func testCheckpointSyncing(t *testing.T, protocol int, syncMode int) {
  38. config := light.TestServerIndexerConfig
  39. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  40. for {
  41. cs, _, _ := cIndexer.Sections()
  42. bts, _, _ := btIndexer.Sections()
  43. if cs >= 1 && bts >= 1 {
  44. break
  45. }
  46. time.Sleep(10 * time.Millisecond)
  47. }
  48. }
  49. // Generate 128+1 blocks (totally 1 CHT section)
  50. netconfig := testnetConfig{
  51. blocks: int(config.ChtSize + config.ChtConfirms),
  52. protocol: protocol,
  53. indexFn: waitIndexers,
  54. nopruning: true,
  55. }
  56. server, client, tearDown := newClientServerEnv(t, netconfig)
  57. defer tearDown()
  58. expected := config.ChtSize + config.ChtConfirms
  59. // Checkpoint syncing or legacy checkpoint syncing.
  60. if syncMode == 1 || syncMode == 2 {
  61. // Assemble checkpoint 0
  62. s, _, head := server.chtIndexer.Sections()
  63. cp := &params.TrustedCheckpoint{
  64. SectionIndex: 0,
  65. SectionHead: head,
  66. CHTRoot: light.GetChtRoot(server.db, s-1, head),
  67. BloomRoot: light.GetBloomTrieRoot(server.db, s-1, head),
  68. }
  69. if syncMode == 1 {
  70. // Register the assembled checkpoint as hardcoded one.
  71. client.handler.checkpoint = cp
  72. client.handler.backend.blockchain.AddTrustedCheckpoint(cp)
  73. } else {
  74. // Register the assembled checkpoint into oracle.
  75. header := server.backend.Blockchain().CurrentHeader()
  76. data := append([]byte{0x19, 0x00}, append(oracleAddr.Bytes(), append([]byte{0, 0, 0, 0, 0, 0, 0, 0}, cp.Hash().Bytes()...)...)...)
  77. sig, _ := crypto.Sign(crypto.Keccak256(data), signerKey)
  78. sig[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  79. auth, _ := bind.NewKeyedTransactorWithChainID(signerKey, big.NewInt(1337))
  80. if _, err := server.handler.server.oracle.Contract().RegisterCheckpoint(auth, cp.SectionIndex, cp.Hash().Bytes(), new(big.Int).Sub(header.Number, big.NewInt(1)), header.ParentHash, [][]byte{sig}); err != nil {
  81. t.Error("register checkpoint failed", err)
  82. }
  83. server.backend.Commit()
  84. // Wait for the checkpoint registration
  85. for {
  86. _, hash, _, err := server.handler.server.oracle.Contract().Contract().GetLatestCheckpoint(nil)
  87. if err != nil || hash == [32]byte{} {
  88. time.Sleep(10 * time.Millisecond)
  89. continue
  90. }
  91. break
  92. }
  93. expected += 1
  94. }
  95. }
  96. done := make(chan error)
  97. client.handler.syncEnd = func(header *types.Header) {
  98. if header.Number.Uint64() == expected {
  99. done <- nil
  100. } else {
  101. done <- fmt.Errorf("blockchain length mismatch, want %d, got %d", expected, header.Number)
  102. }
  103. }
  104. // Create connected peer pair.
  105. peer1, peer2, err := newTestPeerPair("peer", protocol, server.handler, client.handler)
  106. if err != nil {
  107. t.Fatalf("Failed to connect testing peers %v", err)
  108. }
  109. defer peer1.close()
  110. defer peer2.close()
  111. select {
  112. case err := <-done:
  113. if err != nil {
  114. t.Error("sync failed", err)
  115. }
  116. return
  117. case <-time.NewTimer(10 * time.Second).C:
  118. t.Error("checkpoint syncing timeout")
  119. }
  120. }
  121. func TestMissOracleBackendLES3(t *testing.T) { testMissOracleBackend(t, true, lpv3) }
  122. func TestMissOracleBackendNoCheckpointLES3(t *testing.T) { testMissOracleBackend(t, false, lpv3) }
  123. func testMissOracleBackend(t *testing.T, hasCheckpoint bool, protocol int) {
  124. config := light.TestServerIndexerConfig
  125. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  126. for {
  127. cs, _, _ := cIndexer.Sections()
  128. bts, _, _ := btIndexer.Sections()
  129. if cs >= 1 && bts >= 1 {
  130. break
  131. }
  132. time.Sleep(10 * time.Millisecond)
  133. }
  134. }
  135. // Generate 128+1 blocks (totally 1 CHT section)
  136. netconfig := testnetConfig{
  137. blocks: int(config.ChtSize + config.ChtConfirms),
  138. protocol: protocol,
  139. indexFn: waitIndexers,
  140. nopruning: true,
  141. }
  142. server, client, tearDown := newClientServerEnv(t, netconfig)
  143. defer tearDown()
  144. expected := config.ChtSize + config.ChtConfirms
  145. s, _, head := server.chtIndexer.Sections()
  146. cp := &params.TrustedCheckpoint{
  147. SectionIndex: 0,
  148. SectionHead: head,
  149. CHTRoot: light.GetChtRoot(server.db, s-1, head),
  150. BloomRoot: light.GetBloomTrieRoot(server.db, s-1, head),
  151. }
  152. // Register the assembled checkpoint into oracle.
  153. header := server.backend.Blockchain().CurrentHeader()
  154. data := append([]byte{0x19, 0x00}, append(oracleAddr.Bytes(), append([]byte{0, 0, 0, 0, 0, 0, 0, 0}, cp.Hash().Bytes()...)...)...)
  155. sig, _ := crypto.Sign(crypto.Keccak256(data), signerKey)
  156. sig[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  157. auth, _ := bind.NewKeyedTransactorWithChainID(signerKey, big.NewInt(1337))
  158. if _, err := server.handler.server.oracle.Contract().RegisterCheckpoint(auth, cp.SectionIndex, cp.Hash().Bytes(), new(big.Int).Sub(header.Number, big.NewInt(1)), header.ParentHash, [][]byte{sig}); err != nil {
  159. t.Error("register checkpoint failed", err)
  160. }
  161. server.backend.Commit()
  162. // Wait for the checkpoint registration
  163. for {
  164. _, hash, _, err := server.handler.server.oracle.Contract().Contract().GetLatestCheckpoint(nil)
  165. if err != nil || hash == [32]byte{} {
  166. time.Sleep(100 * time.Millisecond)
  167. continue
  168. }
  169. break
  170. }
  171. expected += 1
  172. // Explicitly set the oracle as nil. In normal use case it can happen
  173. // that user wants to unlock something which blocks the oracle backend
  174. // initialisation. But at the same time syncing starts.
  175. //
  176. // See https://github.com/ethereum/go-ethereum/issues/20097 for more detail.
  177. //
  178. // In this case, client should run light sync or legacy checkpoint sync
  179. // if hardcoded checkpoint is configured.
  180. client.handler.backend.oracle = nil
  181. // For some private networks it can happen checkpoint syncing is enabled
  182. // but there is no hardcoded checkpoint configured.
  183. if hasCheckpoint {
  184. client.handler.checkpoint = cp
  185. client.handler.backend.blockchain.AddTrustedCheckpoint(cp)
  186. }
  187. done := make(chan error)
  188. client.handler.syncEnd = func(header *types.Header) {
  189. if header.Number.Uint64() == expected {
  190. done <- nil
  191. } else {
  192. done <- fmt.Errorf("blockchain length mismatch, want %d, got %d", expected, header.Number)
  193. }
  194. }
  195. // Create connected peer pair.
  196. if _, _, err := newTestPeerPair("peer", 2, server.handler, client.handler); err != nil {
  197. t.Fatalf("Failed to connect testing peers %v", err)
  198. }
  199. select {
  200. case err := <-done:
  201. if err != nil {
  202. t.Error("sync failed", err)
  203. }
  204. return
  205. case <-time.NewTimer(10 * time.Second).C:
  206. t.Error("checkpoint syncing timeout")
  207. }
  208. }
  209. func TestSyncFromConfiguredCheckpointLES3(t *testing.T) { testSyncFromConfiguredCheckpoint(t, lpv3) }
  210. func testSyncFromConfiguredCheckpoint(t *testing.T, protocol int) {
  211. config := light.TestServerIndexerConfig
  212. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  213. for {
  214. cs, _, _ := cIndexer.Sections()
  215. bts, _, _ := btIndexer.Sections()
  216. if cs >= 2 && bts >= 2 {
  217. break
  218. }
  219. time.Sleep(10 * time.Millisecond)
  220. }
  221. }
  222. // Generate 256+1 blocks (totally 2 CHT sections)
  223. netconfig := testnetConfig{
  224. blocks: int(2*config.ChtSize + config.ChtConfirms),
  225. protocol: protocol,
  226. indexFn: waitIndexers,
  227. nopruning: true,
  228. }
  229. server, client, tearDown := newClientServerEnv(t, netconfig)
  230. defer tearDown()
  231. // Configure the local checkpoint(the first section)
  232. head := server.handler.blockchain.GetHeaderByNumber(config.ChtSize - 1).Hash()
  233. cp := &params.TrustedCheckpoint{
  234. SectionIndex: 0,
  235. SectionHead: head,
  236. CHTRoot: light.GetChtRoot(server.db, 0, head),
  237. BloomRoot: light.GetBloomTrieRoot(server.db, 0, head),
  238. }
  239. client.handler.backend.config.SyncFromCheckpoint = true
  240. client.handler.backend.config.Checkpoint = cp
  241. client.handler.checkpoint = cp
  242. client.handler.backend.blockchain.AddTrustedCheckpoint(cp)
  243. var (
  244. start = make(chan error, 1)
  245. end = make(chan error, 1)
  246. expectStart = config.ChtSize - 1
  247. expectEnd = 2*config.ChtSize + config.ChtConfirms
  248. )
  249. client.handler.syncStart = func(header *types.Header) {
  250. if header.Number.Uint64() == expectStart {
  251. start <- nil
  252. } else {
  253. start <- fmt.Errorf("blockchain length mismatch, want %d, got %d", expectStart, header.Number)
  254. }
  255. }
  256. client.handler.syncEnd = func(header *types.Header) {
  257. if header.Number.Uint64() == expectEnd {
  258. end <- nil
  259. } else {
  260. end <- fmt.Errorf("blockchain length mismatch, want %d, got %d", expectEnd, header.Number)
  261. }
  262. }
  263. // Create connected peer pair.
  264. if _, _, err := newTestPeerPair("peer", 2, server.handler, client.handler); err != nil {
  265. t.Fatalf("Failed to connect testing peers %v", err)
  266. }
  267. select {
  268. case err := <-start:
  269. if err != nil {
  270. t.Error("sync failed", err)
  271. }
  272. return
  273. case <-time.NewTimer(10 * time.Second).C:
  274. t.Error("checkpoint syncing timeout")
  275. }
  276. select {
  277. case err := <-end:
  278. if err != nil {
  279. t.Error("sync failed", err)
  280. }
  281. return
  282. case <-time.NewTimer(10 * time.Second).C:
  283. t.Error("checkpoint syncing timeout")
  284. }
  285. }
  286. func TestSyncAll(t *testing.T) { testSyncAll(t, lpv3) }
  287. func testSyncAll(t *testing.T, protocol int) {
  288. config := light.TestServerIndexerConfig
  289. waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) {
  290. for {
  291. cs, _, _ := cIndexer.Sections()
  292. bts, _, _ := btIndexer.Sections()
  293. if cs >= 2 && bts >= 2 {
  294. break
  295. }
  296. time.Sleep(10 * time.Millisecond)
  297. }
  298. }
  299. // Generate 256+1 blocks (totally 2 CHT sections)
  300. netconfig := testnetConfig{
  301. blocks: int(2*config.ChtSize + config.ChtConfirms),
  302. protocol: protocol,
  303. indexFn: waitIndexers,
  304. nopruning: true,
  305. }
  306. server, client, tearDown := newClientServerEnv(t, netconfig)
  307. defer tearDown()
  308. client.handler.backend.config.SyncFromCheckpoint = true
  309. var (
  310. start = make(chan error, 1)
  311. end = make(chan error, 1)
  312. expectStart = uint64(0)
  313. expectEnd = 2*config.ChtSize + config.ChtConfirms
  314. )
  315. client.handler.syncStart = func(header *types.Header) {
  316. if header.Number.Uint64() == expectStart {
  317. start <- nil
  318. } else {
  319. start <- fmt.Errorf("blockchain length mismatch, want %d, got %d", expectStart, header.Number)
  320. }
  321. }
  322. client.handler.syncEnd = func(header *types.Header) {
  323. if header.Number.Uint64() == expectEnd {
  324. end <- nil
  325. } else {
  326. end <- fmt.Errorf("blockchain length mismatch, want %d, got %d", expectEnd, header.Number)
  327. }
  328. }
  329. // Create connected peer pair.
  330. if _, _, err := newTestPeerPair("peer", 2, server.handler, client.handler); err != nil {
  331. t.Fatalf("Failed to connect testing peers %v", err)
  332. }
  333. select {
  334. case err := <-start:
  335. if err != nil {
  336. t.Error("sync failed", err)
  337. }
  338. return
  339. case <-time.NewTimer(10 * time.Second).C:
  340. t.Error("checkpoint syncing timeout")
  341. }
  342. select {
  343. case err := <-end:
  344. if err != nil {
  345. t.Error("sync failed", err)
  346. }
  347. return
  348. case <-time.NewTimer(10 * time.Second).C:
  349. t.Error("checkpoint syncing timeout")
  350. }
  351. }