sync_test.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. // Copyright 2020 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 snap
  17. import (
  18. "bytes"
  19. "crypto/rand"
  20. "encoding/binary"
  21. "fmt"
  22. "math/big"
  23. "sort"
  24. "testing"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core/rawdb"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/light"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/ethereum/go-ethereum/trie"
  34. "golang.org/x/crypto/sha3"
  35. )
  36. func TestHashing(t *testing.T) {
  37. t.Parallel()
  38. var bytecodes = make([][]byte, 10)
  39. for i := 0; i < len(bytecodes); i++ {
  40. buf := make([]byte, 100)
  41. rand.Read(buf)
  42. bytecodes[i] = buf
  43. }
  44. var want, got string
  45. var old = func() {
  46. hasher := sha3.NewLegacyKeccak256()
  47. for i := 0; i < len(bytecodes); i++ {
  48. hasher.Reset()
  49. hasher.Write(bytecodes[i])
  50. hash := hasher.Sum(nil)
  51. got = fmt.Sprintf("%v\n%v", got, hash)
  52. }
  53. }
  54. var new = func() {
  55. hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState)
  56. var hash = make([]byte, 32)
  57. for i := 0; i < len(bytecodes); i++ {
  58. hasher.Reset()
  59. hasher.Write(bytecodes[i])
  60. hasher.Read(hash)
  61. want = fmt.Sprintf("%v\n%v", want, hash)
  62. }
  63. }
  64. old()
  65. new()
  66. if want != got {
  67. t.Errorf("want\n%v\ngot\n%v\n", want, got)
  68. }
  69. }
  70. func BenchmarkHashing(b *testing.B) {
  71. var bytecodes = make([][]byte, 10000)
  72. for i := 0; i < len(bytecodes); i++ {
  73. buf := make([]byte, 100)
  74. rand.Read(buf)
  75. bytecodes[i] = buf
  76. }
  77. var old = func() {
  78. hasher := sha3.NewLegacyKeccak256()
  79. for i := 0; i < len(bytecodes); i++ {
  80. hasher.Reset()
  81. hasher.Write(bytecodes[i])
  82. hasher.Sum(nil)
  83. }
  84. }
  85. var new = func() {
  86. hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState)
  87. var hash = make([]byte, 32)
  88. for i := 0; i < len(bytecodes); i++ {
  89. hasher.Reset()
  90. hasher.Write(bytecodes[i])
  91. hasher.Read(hash)
  92. }
  93. }
  94. b.Run("old", func(b *testing.B) {
  95. b.ReportAllocs()
  96. for i := 0; i < b.N; i++ {
  97. old()
  98. }
  99. })
  100. b.Run("new", func(b *testing.B) {
  101. b.ReportAllocs()
  102. for i := 0; i < b.N; i++ {
  103. new()
  104. }
  105. })
  106. }
  107. type storageHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error
  108. type accountHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error
  109. type trieHandlerFunc func(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error
  110. type codeHandlerFunc func(t *testPeer, id uint64, hashes []common.Hash, max uint64) error
  111. type testPeer struct {
  112. id string
  113. test *testing.T
  114. remote *Syncer
  115. logger log.Logger
  116. accountTrie *trie.Trie
  117. accountValues entrySlice
  118. storageTries map[common.Hash]*trie.Trie
  119. storageValues map[common.Hash]entrySlice
  120. accountRequestHandler accountHandlerFunc
  121. storageRequestHandler storageHandlerFunc
  122. trieRequestHandler trieHandlerFunc
  123. codeRequestHandler codeHandlerFunc
  124. cancelCh chan struct{}
  125. }
  126. func newTestPeer(id string, t *testing.T, cancelCh chan struct{}) *testPeer {
  127. peer := &testPeer{
  128. id: id,
  129. test: t,
  130. logger: log.New("id", id),
  131. accountRequestHandler: defaultAccountRequestHandler,
  132. trieRequestHandler: defaultTrieRequestHandler,
  133. storageRequestHandler: defaultStorageRequestHandler,
  134. codeRequestHandler: defaultCodeRequestHandler,
  135. cancelCh: cancelCh,
  136. }
  137. //stderrHandler := log.StreamHandler(os.Stderr, log.TerminalFormat(true))
  138. //peer.logger.SetHandler(stderrHandler)
  139. return peer
  140. }
  141. func (t *testPeer) ID() string { return t.id }
  142. func (t *testPeer) Log() log.Logger { return t.logger }
  143. func (t *testPeer) RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes uint64) error {
  144. t.logger.Trace("Fetching range of accounts", "reqid", id, "root", root, "origin", origin, "limit", limit, "bytes", common.StorageSize(bytes))
  145. go t.accountRequestHandler(t, id, root, origin, bytes)
  146. return nil
  147. }
  148. func (t *testPeer) RequestTrieNodes(id uint64, root common.Hash, paths []TrieNodePathSet, bytes uint64) error {
  149. t.logger.Trace("Fetching set of trie nodes", "reqid", id, "root", root, "pathsets", len(paths), "bytes", common.StorageSize(bytes))
  150. go t.trieRequestHandler(t, id, root, paths, bytes)
  151. return nil
  152. }
  153. func (t *testPeer) RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes uint64) error {
  154. if len(accounts) == 1 && origin != nil {
  155. t.logger.Trace("Fetching range of large storage slots", "reqid", id, "root", root, "account", accounts[0], "origin", common.BytesToHash(origin), "limit", common.BytesToHash(limit), "bytes", common.StorageSize(bytes))
  156. } else {
  157. t.logger.Trace("Fetching ranges of small storage slots", "reqid", id, "root", root, "accounts", len(accounts), "first", accounts[0], "bytes", common.StorageSize(bytes))
  158. }
  159. go t.storageRequestHandler(t, id, root, accounts, origin, limit, bytes)
  160. return nil
  161. }
  162. func (t *testPeer) RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error {
  163. t.logger.Trace("Fetching set of byte codes", "reqid", id, "hashes", len(hashes), "bytes", common.StorageSize(bytes))
  164. go t.codeRequestHandler(t, id, hashes, bytes)
  165. return nil
  166. }
  167. // defaultTrieRequestHandler is a well-behaving handler for trie healing requests
  168. func defaultTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error {
  169. // Pass the response
  170. var nodes [][]byte
  171. for _, pathset := range paths {
  172. switch len(pathset) {
  173. case 1:
  174. blob, _, err := t.accountTrie.TryGetNode(pathset[0])
  175. if err != nil {
  176. t.logger.Info("Error handling req", "error", err)
  177. break
  178. }
  179. nodes = append(nodes, blob)
  180. default:
  181. account := t.storageTries[(common.BytesToHash(pathset[0]))]
  182. for _, path := range pathset[1:] {
  183. blob, _, err := account.TryGetNode(path)
  184. if err != nil {
  185. t.logger.Info("Error handling req", "error", err)
  186. break
  187. }
  188. nodes = append(nodes, blob)
  189. }
  190. }
  191. }
  192. t.remote.OnTrieNodes(t, requestId, nodes)
  193. return nil
  194. }
  195. // defaultAccountRequestHandler is a well-behaving handler for AccountRangeRequests
  196. func defaultAccountRequestHandler(t *testPeer, id uint64, root common.Hash, origin common.Hash, cap uint64) error {
  197. keys, vals, proofs := createAccountRequestResponse(t, root, origin, cap)
  198. if err := t.remote.OnAccounts(t, id, keys, vals, proofs); err != nil {
  199. t.logger.Error("remote error on delivery", "error", err)
  200. t.test.Errorf("Remote side rejected our delivery: %v", err)
  201. t.remote.Unregister(t.id)
  202. close(t.cancelCh)
  203. return err
  204. }
  205. return nil
  206. }
  207. func createAccountRequestResponse(t *testPeer, root common.Hash, origin common.Hash, cap uint64) (keys []common.Hash, vals [][]byte, proofs [][]byte) {
  208. var size uint64
  209. for _, entry := range t.accountValues {
  210. if size > cap {
  211. break
  212. }
  213. if bytes.Compare(origin[:], entry.k) <= 0 {
  214. keys = append(keys, common.BytesToHash(entry.k))
  215. vals = append(vals, entry.v)
  216. size += uint64(32 + len(entry.v))
  217. }
  218. }
  219. // Unless we send the entire trie, we need to supply proofs
  220. // Actually, we need to supply proofs either way! This seems tob be an implementation
  221. // quirk in go-ethereum
  222. proof := light.NewNodeSet()
  223. if err := t.accountTrie.Prove(origin[:], 0, proof); err != nil {
  224. t.logger.Error("Could not prove inexistence of origin", "origin", origin,
  225. "error", err)
  226. }
  227. if len(keys) > 0 {
  228. lastK := (keys[len(keys)-1])[:]
  229. if err := t.accountTrie.Prove(lastK, 0, proof); err != nil {
  230. t.logger.Error("Could not prove last item",
  231. "error", err)
  232. }
  233. }
  234. for _, blob := range proof.NodeList() {
  235. proofs = append(proofs, blob)
  236. }
  237. return keys, vals, proofs
  238. }
  239. // defaultStorageRequestHandler is a well-behaving storage request handler
  240. func defaultStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, bOrigin, bLimit []byte, max uint64) error {
  241. hashes, slots, proofs := createStorageRequestResponse(t, root, accounts, bOrigin, bLimit, max)
  242. if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil {
  243. t.logger.Error("remote error on delivery", "error", err)
  244. t.test.Errorf("Remote side rejected our delivery: %v", err)
  245. close(t.cancelCh)
  246. }
  247. return nil
  248. }
  249. func defaultCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
  250. var bytecodes [][]byte
  251. for _, h := range hashes {
  252. bytecodes = append(bytecodes, getCode(h))
  253. }
  254. if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil {
  255. t.logger.Error("remote error on delivery", "error", err)
  256. t.test.Errorf("Remote side rejected our delivery: %v", err)
  257. close(t.cancelCh)
  258. }
  259. return nil
  260. }
  261. func createStorageRequestResponse(t *testPeer, root common.Hash, accounts []common.Hash, bOrigin, bLimit []byte, max uint64) (hashes [][]common.Hash, slots [][][]byte, proofs [][]byte) {
  262. var (
  263. size uint64
  264. limit = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
  265. )
  266. if len(bLimit) > 0 {
  267. limit = common.BytesToHash(bLimit)
  268. }
  269. var origin common.Hash
  270. if len(bOrigin) > 0 {
  271. origin = common.BytesToHash(bOrigin)
  272. }
  273. var limitExceeded bool
  274. var incomplete bool
  275. for _, account := range accounts {
  276. var keys []common.Hash
  277. var vals [][]byte
  278. for _, entry := range t.storageValues[account] {
  279. if limitExceeded {
  280. incomplete = true
  281. break
  282. }
  283. if bytes.Compare(entry.k, origin[:]) < 0 {
  284. incomplete = true
  285. continue
  286. }
  287. keys = append(keys, common.BytesToHash(entry.k))
  288. vals = append(vals, entry.v)
  289. size += uint64(32 + len(entry.v))
  290. if bytes.Compare(entry.k, limit[:]) >= 0 {
  291. limitExceeded = true
  292. }
  293. if size > max {
  294. limitExceeded = true
  295. }
  296. }
  297. hashes = append(hashes, keys)
  298. slots = append(slots, vals)
  299. if incomplete {
  300. // If we're aborting, we need to prove the first and last item
  301. // This terminates the response (and thus the loop)
  302. proof := light.NewNodeSet()
  303. stTrie := t.storageTries[account]
  304. // Here's a potential gotcha: when constructing the proof, we cannot
  305. // use the 'origin' slice directly, but must use the full 32-byte
  306. // hash form.
  307. if err := stTrie.Prove(origin[:], 0, proof); err != nil {
  308. t.logger.Error("Could not prove inexistence of origin", "origin", origin,
  309. "error", err)
  310. }
  311. if len(keys) > 0 {
  312. lastK := (keys[len(keys)-1])[:]
  313. if err := stTrie.Prove(lastK, 0, proof); err != nil {
  314. t.logger.Error("Could not prove last item", "error", err)
  315. }
  316. }
  317. for _, blob := range proof.NodeList() {
  318. proofs = append(proofs, blob)
  319. }
  320. break
  321. }
  322. }
  323. return hashes, slots, proofs
  324. }
  325. // emptyRequestAccountRangeFn is a rejects AccountRangeRequests
  326. func emptyRequestAccountRangeFn(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error {
  327. var proofs [][]byte
  328. var keys []common.Hash
  329. var vals [][]byte
  330. t.remote.OnAccounts(t, requestId, keys, vals, proofs)
  331. return nil
  332. }
  333. func nonResponsiveRequestAccountRangeFn(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error {
  334. return nil
  335. }
  336. func emptyTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error {
  337. var nodes [][]byte
  338. t.remote.OnTrieNodes(t, requestId, nodes)
  339. return nil
  340. }
  341. func nonResponsiveTrieRequestHandler(t *testPeer, requestId uint64, root common.Hash, paths []TrieNodePathSet, cap uint64) error {
  342. return nil
  343. }
  344. func emptyStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
  345. var hashes [][]common.Hash
  346. var slots [][][]byte
  347. var proofs [][]byte
  348. t.remote.OnStorage(t, requestId, hashes, slots, proofs)
  349. return nil
  350. }
  351. func nonResponsiveStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
  352. return nil
  353. }
  354. //func emptyCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
  355. // var bytecodes [][]byte
  356. // t.remote.OnByteCodes(t, id, bytecodes)
  357. // return nil
  358. //}
  359. func corruptCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
  360. var bytecodes [][]byte
  361. for _, h := range hashes {
  362. // Send back the hashes
  363. bytecodes = append(bytecodes, h[:])
  364. }
  365. if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil {
  366. t.logger.Error("remote error on delivery", "error", err)
  367. // Mimic the real-life handler, which drops a peer on errors
  368. t.remote.Unregister(t.id)
  369. }
  370. return nil
  371. }
  372. func cappedCodeRequestHandler(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
  373. var bytecodes [][]byte
  374. for _, h := range hashes[:1] {
  375. bytecodes = append(bytecodes, getCode(h))
  376. }
  377. if err := t.remote.OnByteCodes(t, id, bytecodes); err != nil {
  378. t.logger.Error("remote error on delivery", "error", err)
  379. // Mimic the real-life handler, which drops a peer on errors
  380. t.remote.Unregister(t.id)
  381. }
  382. return nil
  383. }
  384. // starvingStorageRequestHandler is somewhat well-behaving storage handler, but it caps the returned results to be very small
  385. func starvingStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
  386. return defaultStorageRequestHandler(t, requestId, root, accounts, origin, limit, 500)
  387. }
  388. func starvingAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error {
  389. return defaultAccountRequestHandler(t, requestId, root, origin, 500)
  390. }
  391. //func misdeliveringAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error {
  392. // return defaultAccountRequestHandler(t, requestId-1, root, origin, 500)
  393. //}
  394. func corruptAccountRequestHandler(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error {
  395. hashes, accounts, proofs := createAccountRequestResponse(t, root, origin, cap)
  396. if len(proofs) > 0 {
  397. proofs = proofs[1:]
  398. }
  399. if err := t.remote.OnAccounts(t, requestId, hashes, accounts, proofs); err != nil {
  400. t.logger.Info("remote error on delivery (as expected)", "error", err)
  401. // Mimic the real-life handler, which drops a peer on errors
  402. t.remote.Unregister(t.id)
  403. }
  404. return nil
  405. }
  406. // corruptStorageRequestHandler doesn't provide good proofs
  407. func corruptStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
  408. hashes, slots, proofs := createStorageRequestResponse(t, root, accounts, origin, limit, max)
  409. if len(proofs) > 0 {
  410. proofs = proofs[1:]
  411. }
  412. if err := t.remote.OnStorage(t, requestId, hashes, slots, proofs); err != nil {
  413. t.logger.Info("remote error on delivery (as expected)", "error", err)
  414. // Mimic the real-life handler, which drops a peer on errors
  415. t.remote.Unregister(t.id)
  416. }
  417. return nil
  418. }
  419. func noProofStorageRequestHandler(t *testPeer, requestId uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, max uint64) error {
  420. hashes, slots, _ := createStorageRequestResponse(t, root, accounts, origin, limit, max)
  421. if err := t.remote.OnStorage(t, requestId, hashes, slots, nil); err != nil {
  422. t.logger.Info("remote error on delivery (as expected)", "error", err)
  423. // Mimic the real-life handler, which drops a peer on errors
  424. t.remote.Unregister(t.id)
  425. }
  426. return nil
  427. }
  428. // TestSyncBloatedProof tests a scenario where we provide only _one_ value, but
  429. // also ship the entire trie inside the proof. If the attack is successful,
  430. // the remote side does not do any follow-up requests
  431. func TestSyncBloatedProof(t *testing.T) {
  432. t.Parallel()
  433. sourceAccountTrie, elems := makeAccountTrieNoStorage(100)
  434. cancel := make(chan struct{})
  435. source := newTestPeer("source", t, cancel)
  436. source.accountTrie = sourceAccountTrie
  437. source.accountValues = elems
  438. source.accountRequestHandler = func(t *testPeer, requestId uint64, root common.Hash, origin common.Hash, cap uint64) error {
  439. var proofs [][]byte
  440. var keys []common.Hash
  441. var vals [][]byte
  442. // The values
  443. for _, entry := range t.accountValues {
  444. if bytes.Compare(origin[:], entry.k) <= 0 {
  445. keys = append(keys, common.BytesToHash(entry.k))
  446. vals = append(vals, entry.v)
  447. }
  448. }
  449. // The proofs
  450. proof := light.NewNodeSet()
  451. if err := t.accountTrie.Prove(origin[:], 0, proof); err != nil {
  452. t.logger.Error("Could not prove origin", "origin", origin, "error", err)
  453. }
  454. // The bloat: add proof of every single element
  455. for _, entry := range t.accountValues {
  456. if err := t.accountTrie.Prove(entry.k, 0, proof); err != nil {
  457. t.logger.Error("Could not prove item", "error", err)
  458. }
  459. }
  460. // And remove one item from the elements
  461. if len(keys) > 2 {
  462. keys = append(keys[:1], keys[2:]...)
  463. vals = append(vals[:1], vals[2:]...)
  464. }
  465. for _, blob := range proof.NodeList() {
  466. proofs = append(proofs, blob)
  467. }
  468. if err := t.remote.OnAccounts(t, requestId, keys, vals, proofs); err != nil {
  469. t.logger.Info("remote error on delivery", "error", err)
  470. // This is actually correct, signal to exit the test successfully
  471. close(t.cancelCh)
  472. }
  473. return nil
  474. }
  475. syncer := setupSyncer(source)
  476. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err == nil {
  477. t.Fatal("No error returned from incomplete/cancelled sync")
  478. }
  479. }
  480. func setupSyncer(peers ...*testPeer) *Syncer {
  481. stateDb := rawdb.NewMemoryDatabase()
  482. syncer := NewSyncer(stateDb, trie.NewSyncBloom(1, stateDb))
  483. for _, peer := range peers {
  484. syncer.Register(peer)
  485. peer.remote = syncer
  486. }
  487. return syncer
  488. }
  489. // TestSync tests a basic sync with one peer
  490. func TestSync(t *testing.T) {
  491. t.Parallel()
  492. cancel := make(chan struct{})
  493. sourceAccountTrie, elems := makeAccountTrieNoStorage(100)
  494. mkSource := func(name string) *testPeer {
  495. source := newTestPeer(name, t, cancel)
  496. source.accountTrie = sourceAccountTrie
  497. source.accountValues = elems
  498. return source
  499. }
  500. syncer := setupSyncer(mkSource("sourceA"))
  501. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  502. t.Fatalf("sync failed: %v", err)
  503. }
  504. }
  505. // TestSyncTinyTriePanic tests a basic sync with one peer, and a tiny trie. This caused a
  506. // panic within the prover
  507. func TestSyncTinyTriePanic(t *testing.T) {
  508. t.Parallel()
  509. cancel := make(chan struct{})
  510. sourceAccountTrie, elems := makeAccountTrieNoStorage(1)
  511. mkSource := func(name string) *testPeer {
  512. source := newTestPeer(name, t, cancel)
  513. source.accountTrie = sourceAccountTrie
  514. source.accountValues = elems
  515. return source
  516. }
  517. syncer := setupSyncer(
  518. mkSource("nice-a"),
  519. )
  520. done := checkStall(t, cancel)
  521. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  522. t.Fatalf("sync failed: %v", err)
  523. }
  524. close(done)
  525. }
  526. // TestMultiSync tests a basic sync with multiple peers
  527. func TestMultiSync(t *testing.T) {
  528. t.Parallel()
  529. cancel := make(chan struct{})
  530. sourceAccountTrie, elems := makeAccountTrieNoStorage(100)
  531. mkSource := func(name string) *testPeer {
  532. source := newTestPeer(name, t, cancel)
  533. source.accountTrie = sourceAccountTrie
  534. source.accountValues = elems
  535. return source
  536. }
  537. syncer := setupSyncer(mkSource("sourceA"), mkSource("sourceB"))
  538. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  539. t.Fatalf("sync failed: %v", err)
  540. }
  541. }
  542. // TestSyncWithStorage tests basic sync using accounts + storage + code
  543. func TestSyncWithStorage(t *testing.T) {
  544. t.Parallel()
  545. cancel := make(chan struct{})
  546. sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(3, 3000, true)
  547. mkSource := func(name string) *testPeer {
  548. source := newTestPeer(name, t, cancel)
  549. source.accountTrie = sourceAccountTrie
  550. source.accountValues = elems
  551. source.storageTries = storageTries
  552. source.storageValues = storageElems
  553. return source
  554. }
  555. syncer := setupSyncer(mkSource("sourceA"))
  556. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  557. t.Fatalf("sync failed: %v", err)
  558. }
  559. }
  560. // TestMultiSyncManyUseless contains one good peer, and many which doesn't return anything valuable at all
  561. func TestMultiSyncManyUseless(t *testing.T) {
  562. t.Parallel()
  563. cancel := make(chan struct{})
  564. sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true)
  565. mkSource := func(name string, a, b, c bool) *testPeer {
  566. source := newTestPeer(name, t, cancel)
  567. source.accountTrie = sourceAccountTrie
  568. source.accountValues = elems
  569. source.storageTries = storageTries
  570. source.storageValues = storageElems
  571. if !a {
  572. source.accountRequestHandler = emptyRequestAccountRangeFn
  573. }
  574. if !b {
  575. source.storageRequestHandler = emptyStorageRequestHandler
  576. }
  577. if !c {
  578. source.trieRequestHandler = emptyTrieRequestHandler
  579. }
  580. return source
  581. }
  582. syncer := setupSyncer(
  583. mkSource("full", true, true, true),
  584. mkSource("noAccounts", false, true, true),
  585. mkSource("noStorage", true, false, true),
  586. mkSource("noTrie", true, true, false),
  587. )
  588. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  589. t.Fatalf("sync failed: %v", err)
  590. }
  591. }
  592. // TestMultiSyncManyUseless contains one good peer, and many which doesn't return anything valuable at all
  593. func TestMultiSyncManyUselessWithLowTimeout(t *testing.T) {
  594. // We're setting the timeout to very low, to increase the chance of the timeout
  595. // being triggered. This was previously a cause of panic, when a response
  596. // arrived simultaneously as a timeout was triggered.
  597. defer func(old time.Duration) { requestTimeout = old }(requestTimeout)
  598. requestTimeout = time.Millisecond
  599. cancel := make(chan struct{})
  600. sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true)
  601. mkSource := func(name string, a, b, c bool) *testPeer {
  602. source := newTestPeer(name, t, cancel)
  603. source.accountTrie = sourceAccountTrie
  604. source.accountValues = elems
  605. source.storageTries = storageTries
  606. source.storageValues = storageElems
  607. if !a {
  608. source.accountRequestHandler = emptyRequestAccountRangeFn
  609. }
  610. if !b {
  611. source.storageRequestHandler = emptyStorageRequestHandler
  612. }
  613. if !c {
  614. source.trieRequestHandler = emptyTrieRequestHandler
  615. }
  616. return source
  617. }
  618. syncer := setupSyncer(
  619. mkSource("full", true, true, true),
  620. mkSource("noAccounts", false, true, true),
  621. mkSource("noStorage", true, false, true),
  622. mkSource("noTrie", true, true, false),
  623. )
  624. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  625. t.Fatalf("sync failed: %v", err)
  626. }
  627. }
  628. // TestMultiSyncManyUnresponsive contains one good peer, and many which doesn't respond at all
  629. func TestMultiSyncManyUnresponsive(t *testing.T) {
  630. // We're setting the timeout to very low, to make the test run a bit faster
  631. defer func(old time.Duration) { requestTimeout = old }(requestTimeout)
  632. requestTimeout = time.Millisecond
  633. cancel := make(chan struct{})
  634. sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true)
  635. mkSource := func(name string, a, b, c bool) *testPeer {
  636. source := newTestPeer(name, t, cancel)
  637. source.accountTrie = sourceAccountTrie
  638. source.accountValues = elems
  639. source.storageTries = storageTries
  640. source.storageValues = storageElems
  641. if !a {
  642. source.accountRequestHandler = nonResponsiveRequestAccountRangeFn
  643. }
  644. if !b {
  645. source.storageRequestHandler = nonResponsiveStorageRequestHandler
  646. }
  647. if !c {
  648. source.trieRequestHandler = nonResponsiveTrieRequestHandler
  649. }
  650. return source
  651. }
  652. syncer := setupSyncer(
  653. mkSource("full", true, true, true),
  654. mkSource("noAccounts", false, true, true),
  655. mkSource("noStorage", true, false, true),
  656. mkSource("noTrie", true, true, false),
  657. )
  658. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  659. t.Fatalf("sync failed: %v", err)
  660. }
  661. }
  662. func checkStall(t *testing.T, cancel chan struct{}) chan struct{} {
  663. testDone := make(chan struct{})
  664. go func() {
  665. select {
  666. case <-time.After(time.Minute): // TODO(karalabe): Make tests smaller, this is too much
  667. t.Log("Sync stalled")
  668. close(cancel)
  669. case <-testDone:
  670. return
  671. }
  672. }()
  673. return testDone
  674. }
  675. // TestSyncNoStorageAndOneCappedPeer tests sync using accounts and no storage, where one peer is
  676. // consistently returning very small results
  677. func TestSyncNoStorageAndOneCappedPeer(t *testing.T) {
  678. t.Parallel()
  679. cancel := make(chan struct{})
  680. sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
  681. mkSource := func(name string, slow bool) *testPeer {
  682. source := newTestPeer(name, t, cancel)
  683. source.accountTrie = sourceAccountTrie
  684. source.accountValues = elems
  685. if slow {
  686. source.accountRequestHandler = starvingAccountRequestHandler
  687. }
  688. return source
  689. }
  690. syncer := setupSyncer(
  691. mkSource("nice-a", false),
  692. mkSource("nice-b", false),
  693. mkSource("nice-c", false),
  694. mkSource("capped", true),
  695. )
  696. done := checkStall(t, cancel)
  697. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  698. t.Fatalf("sync failed: %v", err)
  699. }
  700. close(done)
  701. }
  702. // TestSyncNoStorageAndOneCodeCorruptPeer has one peer which doesn't deliver
  703. // code requests properly.
  704. func TestSyncNoStorageAndOneCodeCorruptPeer(t *testing.T) {
  705. t.Parallel()
  706. cancel := make(chan struct{})
  707. sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
  708. mkSource := func(name string, codeFn codeHandlerFunc) *testPeer {
  709. source := newTestPeer(name, t, cancel)
  710. source.accountTrie = sourceAccountTrie
  711. source.accountValues = elems
  712. source.codeRequestHandler = codeFn
  713. return source
  714. }
  715. // One is capped, one is corrupt. If we don't use a capped one, there's a 50%
  716. // chance that the full set of codes requested are sent only to the
  717. // non-corrupt peer, which delivers everything in one go, and makes the
  718. // test moot
  719. syncer := setupSyncer(
  720. mkSource("capped", cappedCodeRequestHandler),
  721. mkSource("corrupt", corruptCodeRequestHandler),
  722. )
  723. done := checkStall(t, cancel)
  724. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  725. t.Fatalf("sync failed: %v", err)
  726. }
  727. close(done)
  728. }
  729. func TestSyncNoStorageAndOneAccountCorruptPeer(t *testing.T) {
  730. t.Parallel()
  731. cancel := make(chan struct{})
  732. sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
  733. mkSource := func(name string, accFn accountHandlerFunc) *testPeer {
  734. source := newTestPeer(name, t, cancel)
  735. source.accountTrie = sourceAccountTrie
  736. source.accountValues = elems
  737. source.accountRequestHandler = accFn
  738. return source
  739. }
  740. // One is capped, one is corrupt. If we don't use a capped one, there's a 50%
  741. // chance that the full set of codes requested are sent only to the
  742. // non-corrupt peer, which delivers everything in one go, and makes the
  743. // test moot
  744. syncer := setupSyncer(
  745. mkSource("capped", defaultAccountRequestHandler),
  746. mkSource("corrupt", corruptAccountRequestHandler),
  747. )
  748. done := checkStall(t, cancel)
  749. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  750. t.Fatalf("sync failed: %v", err)
  751. }
  752. close(done)
  753. }
  754. // TestSyncNoStorageAndOneCodeCappedPeer has one peer which delivers code hashes
  755. // one by one
  756. func TestSyncNoStorageAndOneCodeCappedPeer(t *testing.T) {
  757. t.Parallel()
  758. cancel := make(chan struct{})
  759. sourceAccountTrie, elems := makeAccountTrieNoStorage(3000)
  760. mkSource := func(name string, codeFn codeHandlerFunc) *testPeer {
  761. source := newTestPeer(name, t, cancel)
  762. source.accountTrie = sourceAccountTrie
  763. source.accountValues = elems
  764. source.codeRequestHandler = codeFn
  765. return source
  766. }
  767. // Count how many times it's invoked. Remember, there are only 8 unique hashes,
  768. // so it shouldn't be more than that
  769. var counter int
  770. syncer := setupSyncer(
  771. mkSource("capped", func(t *testPeer, id uint64, hashes []common.Hash, max uint64) error {
  772. counter++
  773. return cappedCodeRequestHandler(t, id, hashes, max)
  774. }),
  775. )
  776. done := checkStall(t, cancel)
  777. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  778. t.Fatalf("sync failed: %v", err)
  779. }
  780. close(done)
  781. // There are only 8 unique hashes, and 3K accounts. However, the code
  782. // deduplication is per request batch. If it were a perfect global dedup,
  783. // we would expect only 8 requests. If there were no dedup, there would be
  784. // 3k requests.
  785. // We expect somewhere below 100 requests for these 8 unique hashes.
  786. if threshold := 100; counter > threshold {
  787. t.Fatalf("Error, expected < %d invocations, got %d", threshold, counter)
  788. }
  789. }
  790. // TestSyncWithStorageAndOneCappedPeer tests sync using accounts + storage, where one peer is
  791. // consistently returning very small results
  792. func TestSyncWithStorageAndOneCappedPeer(t *testing.T) {
  793. t.Parallel()
  794. cancel := make(chan struct{})
  795. sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(300, 1000, false)
  796. mkSource := func(name string, slow bool) *testPeer {
  797. source := newTestPeer(name, t, cancel)
  798. source.accountTrie = sourceAccountTrie
  799. source.accountValues = elems
  800. source.storageTries = storageTries
  801. source.storageValues = storageElems
  802. if slow {
  803. source.storageRequestHandler = starvingStorageRequestHandler
  804. }
  805. return source
  806. }
  807. syncer := setupSyncer(
  808. mkSource("nice-a", false),
  809. mkSource("slow", true),
  810. )
  811. done := checkStall(t, cancel)
  812. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  813. t.Fatalf("sync failed: %v", err)
  814. }
  815. close(done)
  816. }
  817. // TestSyncWithStorageAndCorruptPeer tests sync using accounts + storage, where one peer is
  818. // sometimes sending bad proofs
  819. func TestSyncWithStorageAndCorruptPeer(t *testing.T) {
  820. t.Parallel()
  821. cancel := make(chan struct{})
  822. sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true)
  823. mkSource := func(name string, handler storageHandlerFunc) *testPeer {
  824. source := newTestPeer(name, t, cancel)
  825. source.accountTrie = sourceAccountTrie
  826. source.accountValues = elems
  827. source.storageTries = storageTries
  828. source.storageValues = storageElems
  829. source.storageRequestHandler = handler
  830. return source
  831. }
  832. syncer := setupSyncer(
  833. mkSource("nice-a", defaultStorageRequestHandler),
  834. mkSource("nice-b", defaultStorageRequestHandler),
  835. mkSource("nice-c", defaultStorageRequestHandler),
  836. mkSource("corrupt", corruptStorageRequestHandler),
  837. )
  838. done := checkStall(t, cancel)
  839. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  840. t.Fatalf("sync failed: %v", err)
  841. }
  842. close(done)
  843. }
  844. func TestSyncWithStorageAndNonProvingPeer(t *testing.T) {
  845. t.Parallel()
  846. cancel := make(chan struct{})
  847. sourceAccountTrie, elems, storageTries, storageElems := makeAccountTrieWithStorage(100, 3000, true)
  848. mkSource := func(name string, handler storageHandlerFunc) *testPeer {
  849. source := newTestPeer(name, t, cancel)
  850. source.accountTrie = sourceAccountTrie
  851. source.accountValues = elems
  852. source.storageTries = storageTries
  853. source.storageValues = storageElems
  854. source.storageRequestHandler = handler
  855. return source
  856. }
  857. syncer := setupSyncer(
  858. mkSource("nice-a", defaultStorageRequestHandler),
  859. mkSource("nice-b", defaultStorageRequestHandler),
  860. mkSource("nice-c", defaultStorageRequestHandler),
  861. mkSource("corrupt", noProofStorageRequestHandler),
  862. )
  863. done := checkStall(t, cancel)
  864. if err := syncer.Sync(sourceAccountTrie.Hash(), cancel); err != nil {
  865. t.Fatalf("sync failed: %v", err)
  866. }
  867. close(done)
  868. }
  869. type kv struct {
  870. k, v []byte
  871. t bool
  872. }
  873. // Some helpers for sorting
  874. type entrySlice []*kv
  875. func (p entrySlice) Len() int { return len(p) }
  876. func (p entrySlice) Less(i, j int) bool { return bytes.Compare(p[i].k, p[j].k) < 0 }
  877. func (p entrySlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
  878. func key32(i uint64) []byte {
  879. key := make([]byte, 32)
  880. binary.LittleEndian.PutUint64(key, i)
  881. return key
  882. }
  883. var (
  884. codehashes = []common.Hash{
  885. crypto.Keccak256Hash([]byte{0}),
  886. crypto.Keccak256Hash([]byte{1}),
  887. crypto.Keccak256Hash([]byte{2}),
  888. crypto.Keccak256Hash([]byte{3}),
  889. crypto.Keccak256Hash([]byte{4}),
  890. crypto.Keccak256Hash([]byte{5}),
  891. crypto.Keccak256Hash([]byte{6}),
  892. crypto.Keccak256Hash([]byte{7}),
  893. }
  894. )
  895. // getACodeHash returns a pseudo-random code hash
  896. func getACodeHash(i uint64) []byte {
  897. h := codehashes[int(i)%len(codehashes)]
  898. return common.CopyBytes(h[:])
  899. }
  900. // convenience function to lookup the code from the code hash
  901. func getCode(hash common.Hash) []byte {
  902. if hash == emptyCode {
  903. return nil
  904. }
  905. for i, h := range codehashes {
  906. if h == hash {
  907. return []byte{byte(i)}
  908. }
  909. }
  910. return nil
  911. }
  912. // makeAccountTrieNoStorage spits out a trie, along with the leafs
  913. func makeAccountTrieNoStorage(n int) (*trie.Trie, entrySlice) {
  914. db := trie.NewDatabase(rawdb.NewMemoryDatabase())
  915. accTrie, _ := trie.New(common.Hash{}, db)
  916. var entries entrySlice
  917. for i := uint64(1); i <= uint64(n); i++ {
  918. value, _ := rlp.EncodeToBytes(state.Account{
  919. Nonce: i,
  920. Balance: big.NewInt(int64(i)),
  921. Root: emptyRoot,
  922. CodeHash: getACodeHash(i),
  923. })
  924. key := key32(i)
  925. elem := &kv{key, value, false}
  926. accTrie.Update(elem.k, elem.v)
  927. entries = append(entries, elem)
  928. }
  929. sort.Sort(entries)
  930. // Push to disk layer
  931. accTrie.Commit(nil)
  932. return accTrie, entries
  933. }
  934. // makeAccountTrieWithStorage spits out a trie, along with the leafs
  935. func makeAccountTrieWithStorage(accounts, slots int, code bool) (*trie.Trie, entrySlice,
  936. map[common.Hash]*trie.Trie, map[common.Hash]entrySlice) {
  937. var (
  938. db = trie.NewDatabase(rawdb.NewMemoryDatabase())
  939. accTrie, _ = trie.New(common.Hash{}, db)
  940. entries entrySlice
  941. storageTries = make(map[common.Hash]*trie.Trie)
  942. storageEntries = make(map[common.Hash]entrySlice)
  943. )
  944. // Make a storage trie which we reuse for the whole lot
  945. stTrie, stEntries := makeStorageTrie(slots, db)
  946. stRoot := stTrie.Hash()
  947. // Create n accounts in the trie
  948. for i := uint64(1); i <= uint64(accounts); i++ {
  949. key := key32(i)
  950. codehash := emptyCode[:]
  951. if code {
  952. codehash = getACodeHash(i)
  953. }
  954. value, _ := rlp.EncodeToBytes(state.Account{
  955. Nonce: i,
  956. Balance: big.NewInt(int64(i)),
  957. Root: stRoot,
  958. CodeHash: codehash,
  959. })
  960. elem := &kv{key, value, false}
  961. accTrie.Update(elem.k, elem.v)
  962. entries = append(entries, elem)
  963. // we reuse the same one for all accounts
  964. storageTries[common.BytesToHash(key)] = stTrie
  965. storageEntries[common.BytesToHash(key)] = stEntries
  966. }
  967. sort.Sort(entries)
  968. stTrie.Commit(nil)
  969. accTrie.Commit(nil)
  970. return accTrie, entries, storageTries, storageEntries
  971. }
  972. // makeStorageTrie fills a storage trie with n items, returning the
  973. // not-yet-committed trie and the sorted entries
  974. func makeStorageTrie(n int, db *trie.Database) (*trie.Trie, entrySlice) {
  975. trie, _ := trie.New(common.Hash{}, db)
  976. var entries entrySlice
  977. for i := uint64(1); i <= uint64(n); i++ {
  978. // store 'i' at slot 'i'
  979. slotValue := key32(i)
  980. rlpSlotValue, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(slotValue[:]))
  981. slotKey := key32(i)
  982. key := crypto.Keccak256Hash(slotKey[:])
  983. elem := &kv{key[:], rlpSlotValue, false}
  984. trie.Update(elem.k, elem.v)
  985. entries = append(entries, elem)
  986. }
  987. sort.Sort(entries)
  988. return trie, entries
  989. }