sync.go 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756
  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. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "math/rand"
  24. "sort"
  25. "sync"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/math"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/state/snapshot"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/light"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/rlp"
  38. "github.com/ethereum/go-ethereum/trie"
  39. "golang.org/x/crypto/sha3"
  40. )
  41. var (
  42. // emptyRoot is the known root hash of an empty trie.
  43. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  44. // emptyCode is the known hash of the empty EVM bytecode.
  45. emptyCode = crypto.Keccak256Hash(nil)
  46. )
  47. const (
  48. // maxRequestSize is the maximum number of bytes to request from a remote peer.
  49. maxRequestSize = 128 * 1024
  50. // maxStorageSetRequestCount is the maximum number of contracts to request the
  51. // storage of in a single query. If this number is too low, we're not filling
  52. // responses fully and waste round trip times. If it's too high, we're capping
  53. // responses and waste bandwidth.
  54. maxStorageSetRequestCount = maxRequestSize / 1024
  55. // maxCodeRequestCount is the maximum number of bytecode blobs to request in a
  56. // single query. If this number is too low, we're not filling responses fully
  57. // and waste round trip times. If it's too high, we're capping responses and
  58. // waste bandwidth.
  59. //
  60. // Depoyed bytecodes are currently capped at 24KB, so the minimum request
  61. // size should be maxRequestSize / 24K. Assuming that most contracts do not
  62. // come close to that, requesting 4x should be a good approximation.
  63. maxCodeRequestCount = maxRequestSize / (24 * 1024) * 4
  64. // maxTrieRequestCount is the maximum number of trie node blobs to request in
  65. // a single query. If this number is too low, we're not filling responses fully
  66. // and waste round trip times. If it's too high, we're capping responses and
  67. // waste bandwidth.
  68. maxTrieRequestCount = 256
  69. )
  70. var (
  71. // accountConcurrency is the number of chunks to split the account trie into
  72. // to allow concurrent retrievals.
  73. accountConcurrency = 16
  74. // storageConcurrency is the number of chunks to split the a large contract
  75. // storage trie into to allow concurrent retrievals.
  76. storageConcurrency = 16
  77. // requestTimeout is the maximum time a peer is allowed to spend on serving
  78. // a single network request.
  79. requestTimeout = 15 * time.Second // TODO(karalabe): Make it dynamic ala fast-sync?
  80. )
  81. // ErrCancelled is returned from snap syncing if the operation was prematurely
  82. // terminated.
  83. var ErrCancelled = errors.New("sync cancelled")
  84. // accountRequest tracks a pending account range request to ensure responses are
  85. // to actual requests and to validate any security constraints.
  86. //
  87. // Concurrency note: account requests and responses are handled concurrently from
  88. // the main runloop to allow Merkle proof verifications on the peer's thread and
  89. // to drop on invalid response. The request struct must contain all the data to
  90. // construct the response without accessing runloop internals (i.e. task). That
  91. // is only included to allow the runloop to match a response to the task being
  92. // synced without having yet another set of maps.
  93. type accountRequest struct {
  94. peer string // Peer to which this request is assigned
  95. id uint64 // Request ID of this request
  96. deliver chan *accountResponse // Channel to deliver successful response on
  97. revert chan *accountRequest // Channel to deliver request failure on
  98. cancel chan struct{} // Channel to track sync cancellation
  99. timeout *time.Timer // Timer to track delivery timeout
  100. stale chan struct{} // Channel to signal the request was dropped
  101. origin common.Hash // First account requested to allow continuation checks
  102. limit common.Hash // Last account requested to allow non-overlapping chunking
  103. task *accountTask // Task which this request is filling (only access fields through the runloop!!)
  104. }
  105. // accountResponse is an already Merkle-verified remote response to an account
  106. // range request. It contains the subtrie for the requested account range and
  107. // the database that's going to be filled with the internal nodes on commit.
  108. type accountResponse struct {
  109. task *accountTask // Task which this request is filling
  110. hashes []common.Hash // Account hashes in the returned range
  111. accounts []*state.Account // Expanded accounts in the returned range
  112. cont bool // Whether the account range has a continuation
  113. }
  114. // bytecodeRequest tracks a pending bytecode request to ensure responses are to
  115. // actual requests and to validate any security constraints.
  116. //
  117. // Concurrency note: bytecode requests and responses are handled concurrently from
  118. // the main runloop to allow Keccak256 hash verifications on the peer's thread and
  119. // to drop on invalid response. The request struct must contain all the data to
  120. // construct the response without accessing runloop internals (i.e. task). That
  121. // is only included to allow the runloop to match a response to the task being
  122. // synced without having yet another set of maps.
  123. type bytecodeRequest struct {
  124. peer string // Peer to which this request is assigned
  125. id uint64 // Request ID of this request
  126. deliver chan *bytecodeResponse // Channel to deliver successful response on
  127. revert chan *bytecodeRequest // Channel to deliver request failure on
  128. cancel chan struct{} // Channel to track sync cancellation
  129. timeout *time.Timer // Timer to track delivery timeout
  130. stale chan struct{} // Channel to signal the request was dropped
  131. hashes []common.Hash // Bytecode hashes to validate responses
  132. task *accountTask // Task which this request is filling (only access fields through the runloop!!)
  133. }
  134. // bytecodeResponse is an already verified remote response to a bytecode request.
  135. type bytecodeResponse struct {
  136. task *accountTask // Task which this request is filling
  137. hashes []common.Hash // Hashes of the bytecode to avoid double hashing
  138. codes [][]byte // Actual bytecodes to store into the database (nil = missing)
  139. }
  140. // storageRequest tracks a pending storage ranges request to ensure responses are
  141. // to actual requests and to validate any security constraints.
  142. //
  143. // Concurrency note: storage requests and responses are handled concurrently from
  144. // the main runloop to allow Merkel proof verifications on the peer's thread and
  145. // to drop on invalid response. The request struct must contain all the data to
  146. // construct the response without accessing runloop internals (i.e. tasks). That
  147. // is only included to allow the runloop to match a response to the task being
  148. // synced without having yet another set of maps.
  149. type storageRequest struct {
  150. peer string // Peer to which this request is assigned
  151. id uint64 // Request ID of this request
  152. deliver chan *storageResponse // Channel to deliver successful response on
  153. revert chan *storageRequest // Channel to deliver request failure on
  154. cancel chan struct{} // Channel to track sync cancellation
  155. timeout *time.Timer // Timer to track delivery timeout
  156. stale chan struct{} // Channel to signal the request was dropped
  157. accounts []common.Hash // Account hashes to validate responses
  158. roots []common.Hash // Storage roots to validate responses
  159. origin common.Hash // First storage slot requested to allow continuation checks
  160. limit common.Hash // Last storage slot requested to allow non-overlapping chunking
  161. mainTask *accountTask // Task which this response belongs to (only access fields through the runloop!!)
  162. subTask *storageTask // Task which this response is filling (only access fields through the runloop!!)
  163. }
  164. // storageResponse is an already Merkle-verified remote response to a storage
  165. // range request. It contains the subtries for the requested storage ranges and
  166. // the databases that's going to be filled with the internal nodes on commit.
  167. type storageResponse struct {
  168. mainTask *accountTask // Task which this response belongs to
  169. subTask *storageTask // Task which this response is filling
  170. accounts []common.Hash // Account hashes requested, may be only partially filled
  171. roots []common.Hash // Storage roots requested, may be only partially filled
  172. hashes [][]common.Hash // Storage slot hashes in the returned range
  173. slots [][][]byte // Storage slot values in the returned range
  174. nodes []ethdb.KeyValueStore // Database containing the reconstructed trie nodes
  175. cont bool // Whether the last storage range has a continuation
  176. }
  177. // trienodeHealRequest tracks a pending state trie request to ensure responses
  178. // are to actual requests and to validate any security constraints.
  179. //
  180. // Concurrency note: trie node requests and responses are handled concurrently from
  181. // the main runloop to allow Keccak256 hash verifications on the peer's thread and
  182. // to drop on invalid response. The request struct must contain all the data to
  183. // construct the response without accessing runloop internals (i.e. task). That
  184. // is only included to allow the runloop to match a response to the task being
  185. // synced without having yet another set of maps.
  186. type trienodeHealRequest struct {
  187. peer string // Peer to which this request is assigned
  188. id uint64 // Request ID of this request
  189. deliver chan *trienodeHealResponse // Channel to deliver successful response on
  190. revert chan *trienodeHealRequest // Channel to deliver request failure on
  191. cancel chan struct{} // Channel to track sync cancellation
  192. timeout *time.Timer // Timer to track delivery timeout
  193. stale chan struct{} // Channel to signal the request was dropped
  194. hashes []common.Hash // Trie node hashes to validate responses
  195. paths []trie.SyncPath // Trie node paths requested for rescheduling
  196. task *healTask // Task which this request is filling (only access fields through the runloop!!)
  197. }
  198. // trienodeHealResponse is an already verified remote response to a trie node request.
  199. type trienodeHealResponse struct {
  200. task *healTask // Task which this request is filling
  201. hashes []common.Hash // Hashes of the trie nodes to avoid double hashing
  202. paths []trie.SyncPath // Trie node paths requested for rescheduling missing ones
  203. nodes [][]byte // Actual trie nodes to store into the database (nil = missing)
  204. }
  205. // bytecodeHealRequest tracks a pending bytecode request to ensure responses are to
  206. // actual requests and to validate any security constraints.
  207. //
  208. // Concurrency note: bytecode requests and responses are handled concurrently from
  209. // the main runloop to allow Keccak256 hash verifications on the peer's thread and
  210. // to drop on invalid response. The request struct must contain all the data to
  211. // construct the response without accessing runloop internals (i.e. task). That
  212. // is only included to allow the runloop to match a response to the task being
  213. // synced without having yet another set of maps.
  214. type bytecodeHealRequest struct {
  215. peer string // Peer to which this request is assigned
  216. id uint64 // Request ID of this request
  217. deliver chan *bytecodeHealResponse // Channel to deliver successful response on
  218. revert chan *bytecodeHealRequest // Channel to deliver request failure on
  219. cancel chan struct{} // Channel to track sync cancellation
  220. timeout *time.Timer // Timer to track delivery timeout
  221. stale chan struct{} // Channel to signal the request was dropped
  222. hashes []common.Hash // Bytecode hashes to validate responses
  223. task *healTask // Task which this request is filling (only access fields through the runloop!!)
  224. }
  225. // bytecodeHealResponse is an already verified remote response to a bytecode request.
  226. type bytecodeHealResponse struct {
  227. task *healTask // Task which this request is filling
  228. hashes []common.Hash // Hashes of the bytecode to avoid double hashing
  229. codes [][]byte // Actual bytecodes to store into the database (nil = missing)
  230. }
  231. // accountTask represents the sync task for a chunk of the account snapshot.
  232. type accountTask struct {
  233. // These fields get serialized to leveldb on shutdown
  234. Next common.Hash // Next account to sync in this interval
  235. Last common.Hash // Last account to sync in this interval
  236. SubTasks map[common.Hash][]*storageTask // Storage intervals needing fetching for large contracts
  237. // These fields are internals used during runtime
  238. req *accountRequest // Pending request to fill this task
  239. res *accountResponse // Validate response filling this task
  240. pend int // Number of pending subtasks for this round
  241. needCode []bool // Flags whether the filling accounts need code retrieval
  242. needState []bool // Flags whether the filling accounts need storage retrieval
  243. needHeal []bool // Flags whether the filling accounts's state was chunked and need healing
  244. codeTasks map[common.Hash]struct{} // Code hashes that need retrieval
  245. stateTasks map[common.Hash]common.Hash // Account hashes->roots that need full state retrieval
  246. genBatch ethdb.Batch // Batch used by the node generator
  247. genTrie *trie.StackTrie // Node generator from storage slots
  248. done bool // Flag whether the task can be removed
  249. }
  250. // storageTask represents the sync task for a chunk of the storage snapshot.
  251. type storageTask struct {
  252. Next common.Hash // Next account to sync in this interval
  253. Last common.Hash // Last account to sync in this interval
  254. // These fields are internals used during runtime
  255. root common.Hash // Storage root hash for this instance
  256. req *storageRequest // Pending request to fill this task
  257. genBatch ethdb.Batch // Batch used by the node generator
  258. genTrie *trie.StackTrie // Node generator from storage slots
  259. done bool // Flag whether the task can be removed
  260. }
  261. // healTask represents the sync task for healing the snap-synced chunk boundaries.
  262. type healTask struct {
  263. scheduler *trie.Sync // State trie sync scheduler defining the tasks
  264. trieTasks map[common.Hash]trie.SyncPath // Set of trie node tasks currently queued for retrieval
  265. codeTasks map[common.Hash]struct{} // Set of byte code tasks currently queued for retrieval
  266. }
  267. // syncProgress is a database entry to allow suspending and resuming a snapshot state
  268. // sync. Opposed to full and fast sync, there is no way to restart a suspended
  269. // snap sync without prior knowledge of the suspension point.
  270. type syncProgress struct {
  271. Tasks []*accountTask // The suspended account tasks (contract tasks within)
  272. // Status report during syncing phase
  273. AccountSynced uint64 // Number of accounts downloaded
  274. AccountBytes common.StorageSize // Number of account trie bytes persisted to disk
  275. BytecodeSynced uint64 // Number of bytecodes downloaded
  276. BytecodeBytes common.StorageSize // Number of bytecode bytes downloaded
  277. StorageSynced uint64 // Number of storage slots downloaded
  278. StorageBytes common.StorageSize // Number of storage trie bytes persisted to disk
  279. // Status report during healing phase
  280. TrienodeHealSynced uint64 // Number of state trie nodes downloaded
  281. TrienodeHealBytes common.StorageSize // Number of state trie bytes persisted to disk
  282. TrienodeHealDups uint64 // Number of state trie nodes already processed
  283. TrienodeHealNops uint64 // Number of state trie nodes not requested
  284. BytecodeHealSynced uint64 // Number of bytecodes downloaded
  285. BytecodeHealBytes common.StorageSize // Number of bytecodes persisted to disk
  286. BytecodeHealDups uint64 // Number of bytecodes already processed
  287. BytecodeHealNops uint64 // Number of bytecodes not requested
  288. }
  289. // SyncPeer abstracts out the methods required for a peer to be synced against
  290. // with the goal of allowing the construction of mock peers without the full
  291. // blown networking.
  292. type SyncPeer interface {
  293. // ID retrieves the peer's unique identifier.
  294. ID() string
  295. // RequestAccountRange fetches a batch of accounts rooted in a specific account
  296. // trie, starting with the origin.
  297. RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes uint64) error
  298. // RequestStorageRanges fetches a batch of storage slots belonging to one or
  299. // more accounts. If slots from only one accout is requested, an origin marker
  300. // may also be used to retrieve from there.
  301. RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes uint64) error
  302. // RequestByteCodes fetches a batch of bytecodes by hash.
  303. RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error
  304. // RequestTrieNodes fetches a batch of account or storage trie nodes rooted in
  305. // a specificstate trie.
  306. RequestTrieNodes(id uint64, root common.Hash, paths []TrieNodePathSet, bytes uint64) error
  307. // Log retrieves the peer's own contextual logger.
  308. Log() log.Logger
  309. }
  310. // Syncer is an Ethereum account and storage trie syncer based on snapshots and
  311. // the snap protocol. It's purpose is to download all the accounts and storage
  312. // slots from remote peers and reassemble chunks of the state trie, on top of
  313. // which a state sync can be run to fix any gaps / overlaps.
  314. //
  315. // Every network request has a variety of failure events:
  316. // - The peer disconnects after task assignment, failing to send the request
  317. // - The peer disconnects after sending the request, before delivering on it
  318. // - The peer remains connected, but does not deliver a response in time
  319. // - The peer delivers a stale response after a previous timeout
  320. // - The peer delivers a refusal to serve the requested state
  321. type Syncer struct {
  322. db ethdb.KeyValueStore // Database to store the trie nodes into (and dedup)
  323. root common.Hash // Current state trie root being synced
  324. tasks []*accountTask // Current account task set being synced
  325. snapped bool // Flag to signal that snap phase is done
  326. healer *healTask // Current state healing task being executed
  327. update chan struct{} // Notification channel for possible sync progression
  328. peers map[string]SyncPeer // Currently active peers to download from
  329. peerJoin *event.Feed // Event feed to react to peers joining
  330. peerDrop *event.Feed // Event feed to react to peers dropping
  331. // Request tracking during syncing phase
  332. statelessPeers map[string]struct{} // Peers that failed to deliver state data
  333. accountIdlers map[string]struct{} // Peers that aren't serving account requests
  334. bytecodeIdlers map[string]struct{} // Peers that aren't serving bytecode requests
  335. storageIdlers map[string]struct{} // Peers that aren't serving storage requests
  336. accountReqs map[uint64]*accountRequest // Account requests currently running
  337. bytecodeReqs map[uint64]*bytecodeRequest // Bytecode requests currently running
  338. storageReqs map[uint64]*storageRequest // Storage requests currently running
  339. accountSynced uint64 // Number of accounts downloaded
  340. accountBytes common.StorageSize // Number of account trie bytes persisted to disk
  341. bytecodeSynced uint64 // Number of bytecodes downloaded
  342. bytecodeBytes common.StorageSize // Number of bytecode bytes downloaded
  343. storageSynced uint64 // Number of storage slots downloaded
  344. storageBytes common.StorageSize // Number of storage trie bytes persisted to disk
  345. // Request tracking during healing phase
  346. trienodeHealIdlers map[string]struct{} // Peers that aren't serving trie node requests
  347. bytecodeHealIdlers map[string]struct{} // Peers that aren't serving bytecode requests
  348. trienodeHealReqs map[uint64]*trienodeHealRequest // Trie node requests currently running
  349. bytecodeHealReqs map[uint64]*bytecodeHealRequest // Bytecode requests currently running
  350. trienodeHealSynced uint64 // Number of state trie nodes downloaded
  351. trienodeHealBytes common.StorageSize // Number of state trie bytes persisted to disk
  352. trienodeHealDups uint64 // Number of state trie nodes already processed
  353. trienodeHealNops uint64 // Number of state trie nodes not requested
  354. bytecodeHealSynced uint64 // Number of bytecodes downloaded
  355. bytecodeHealBytes common.StorageSize // Number of bytecodes persisted to disk
  356. bytecodeHealDups uint64 // Number of bytecodes already processed
  357. bytecodeHealNops uint64 // Number of bytecodes not requested
  358. stateWriter ethdb.Batch // Shared batch writer used for persisting raw states
  359. accountHealed uint64 // Number of accounts downloaded during the healing stage
  360. accountHealedBytes common.StorageSize // Number of raw account bytes persisted to disk during the healing stage
  361. storageHealed uint64 // Number of storage slots downloaded during the healing stage
  362. storageHealedBytes common.StorageSize // Number of raw storage bytes persisted to disk during the healing stage
  363. startTime time.Time // Time instance when snapshot sync started
  364. logTime time.Time // Time instance when status was last reported
  365. pend sync.WaitGroup // Tracks network request goroutines for graceful shutdown
  366. lock sync.RWMutex // Protects fields that can change outside of sync (peers, reqs, root)
  367. }
  368. // NewSyncer creates a new snapshot syncer to download the Ethereum state over the
  369. // snap protocol.
  370. func NewSyncer(db ethdb.KeyValueStore) *Syncer {
  371. return &Syncer{
  372. db: db,
  373. peers: make(map[string]SyncPeer),
  374. peerJoin: new(event.Feed),
  375. peerDrop: new(event.Feed),
  376. update: make(chan struct{}, 1),
  377. accountIdlers: make(map[string]struct{}),
  378. storageIdlers: make(map[string]struct{}),
  379. bytecodeIdlers: make(map[string]struct{}),
  380. accountReqs: make(map[uint64]*accountRequest),
  381. storageReqs: make(map[uint64]*storageRequest),
  382. bytecodeReqs: make(map[uint64]*bytecodeRequest),
  383. trienodeHealIdlers: make(map[string]struct{}),
  384. bytecodeHealIdlers: make(map[string]struct{}),
  385. trienodeHealReqs: make(map[uint64]*trienodeHealRequest),
  386. bytecodeHealReqs: make(map[uint64]*bytecodeHealRequest),
  387. stateWriter: db.NewBatch(),
  388. }
  389. }
  390. // Register injects a new data source into the syncer's peerset.
  391. func (s *Syncer) Register(peer SyncPeer) error {
  392. // Make sure the peer is not registered yet
  393. id := peer.ID()
  394. s.lock.Lock()
  395. if _, ok := s.peers[id]; ok {
  396. log.Error("Snap peer already registered", "id", id)
  397. s.lock.Unlock()
  398. return errors.New("already registered")
  399. }
  400. s.peers[id] = peer
  401. // Mark the peer as idle, even if no sync is running
  402. s.accountIdlers[id] = struct{}{}
  403. s.storageIdlers[id] = struct{}{}
  404. s.bytecodeIdlers[id] = struct{}{}
  405. s.trienodeHealIdlers[id] = struct{}{}
  406. s.bytecodeHealIdlers[id] = struct{}{}
  407. s.lock.Unlock()
  408. // Notify any active syncs that a new peer can be assigned data
  409. s.peerJoin.Send(id)
  410. return nil
  411. }
  412. // Unregister injects a new data source into the syncer's peerset.
  413. func (s *Syncer) Unregister(id string) error {
  414. // Remove all traces of the peer from the registry
  415. s.lock.Lock()
  416. if _, ok := s.peers[id]; !ok {
  417. log.Error("Snap peer not registered", "id", id)
  418. s.lock.Unlock()
  419. return errors.New("not registered")
  420. }
  421. delete(s.peers, id)
  422. // Remove status markers, even if no sync is running
  423. delete(s.statelessPeers, id)
  424. delete(s.accountIdlers, id)
  425. delete(s.storageIdlers, id)
  426. delete(s.bytecodeIdlers, id)
  427. delete(s.trienodeHealIdlers, id)
  428. delete(s.bytecodeHealIdlers, id)
  429. s.lock.Unlock()
  430. // Notify any active syncs that pending requests need to be reverted
  431. s.peerDrop.Send(id)
  432. return nil
  433. }
  434. // Sync starts (or resumes a previous) sync cycle to iterate over an state trie
  435. // with the given root and reconstruct the nodes based on the snapshot leaves.
  436. // Previously downloaded segments will not be redownloaded of fixed, rather any
  437. // errors will be healed after the leaves are fully accumulated.
  438. func (s *Syncer) Sync(root common.Hash, cancel chan struct{}) error {
  439. // Move the trie root from any previous value, revert stateless markers for
  440. // any peers and initialize the syncer if it was not yet run
  441. s.lock.Lock()
  442. s.root = root
  443. s.healer = &healTask{
  444. scheduler: state.NewStateSync(root, s.db, nil, s.onHealState),
  445. trieTasks: make(map[common.Hash]trie.SyncPath),
  446. codeTasks: make(map[common.Hash]struct{}),
  447. }
  448. s.statelessPeers = make(map[string]struct{})
  449. s.lock.Unlock()
  450. if s.startTime == (time.Time{}) {
  451. s.startTime = time.Now()
  452. }
  453. // Retrieve the previous sync status from LevelDB and abort if already synced
  454. s.loadSyncStatus()
  455. if len(s.tasks) == 0 && s.healer.scheduler.Pending() == 0 {
  456. log.Debug("Snapshot sync already completed")
  457. return nil
  458. }
  459. // If sync is still not finished, we need to ensure that any marker is wiped.
  460. // Otherwise, it may happen that requests for e.g. genesis-data is delivered
  461. // from the snapshot data, instead of from the trie
  462. snapshot.ClearSnapshotMarker(s.db)
  463. defer func() { // Persist any progress, independent of failure
  464. for _, task := range s.tasks {
  465. s.forwardAccountTask(task)
  466. }
  467. s.cleanAccountTasks()
  468. s.saveSyncStatus()
  469. }()
  470. log.Debug("Starting snapshot sync cycle", "root", root)
  471. // Flush out the last committed raw states
  472. defer func() {
  473. if s.stateWriter.ValueSize() > 0 {
  474. s.stateWriter.Write()
  475. s.stateWriter.Reset()
  476. }
  477. }()
  478. defer s.report(true)
  479. // Whether sync completed or not, disregard any future packets
  480. defer func() {
  481. log.Debug("Terminating snapshot sync cycle", "root", root)
  482. s.lock.Lock()
  483. s.accountReqs = make(map[uint64]*accountRequest)
  484. s.storageReqs = make(map[uint64]*storageRequest)
  485. s.bytecodeReqs = make(map[uint64]*bytecodeRequest)
  486. s.trienodeHealReqs = make(map[uint64]*trienodeHealRequest)
  487. s.bytecodeHealReqs = make(map[uint64]*bytecodeHealRequest)
  488. s.lock.Unlock()
  489. }()
  490. // Keep scheduling sync tasks
  491. peerJoin := make(chan string, 16)
  492. peerJoinSub := s.peerJoin.Subscribe(peerJoin)
  493. defer peerJoinSub.Unsubscribe()
  494. peerDrop := make(chan string, 16)
  495. peerDropSub := s.peerDrop.Subscribe(peerDrop)
  496. defer peerDropSub.Unsubscribe()
  497. // Create a set of unique channels for this sync cycle. We need these to be
  498. // ephemeral so a data race doesn't accidentally deliver something stale on
  499. // a persistent channel across syncs (yup, this happened)
  500. var (
  501. accountReqFails = make(chan *accountRequest)
  502. storageReqFails = make(chan *storageRequest)
  503. bytecodeReqFails = make(chan *bytecodeRequest)
  504. accountResps = make(chan *accountResponse)
  505. storageResps = make(chan *storageResponse)
  506. bytecodeResps = make(chan *bytecodeResponse)
  507. trienodeHealReqFails = make(chan *trienodeHealRequest)
  508. bytecodeHealReqFails = make(chan *bytecodeHealRequest)
  509. trienodeHealResps = make(chan *trienodeHealResponse)
  510. bytecodeHealResps = make(chan *bytecodeHealResponse)
  511. )
  512. for {
  513. // Remove all completed tasks and terminate sync if everything's done
  514. s.cleanStorageTasks()
  515. s.cleanAccountTasks()
  516. if len(s.tasks) == 0 && s.healer.scheduler.Pending() == 0 {
  517. return nil
  518. }
  519. // Assign all the data retrieval tasks to any free peers
  520. s.assignAccountTasks(accountResps, accountReqFails, cancel)
  521. s.assignBytecodeTasks(bytecodeResps, bytecodeReqFails, cancel)
  522. s.assignStorageTasks(storageResps, storageReqFails, cancel)
  523. if len(s.tasks) == 0 {
  524. // Sync phase done, run heal phase
  525. s.assignTrienodeHealTasks(trienodeHealResps, trienodeHealReqFails, cancel)
  526. s.assignBytecodeHealTasks(bytecodeHealResps, bytecodeHealReqFails, cancel)
  527. }
  528. // Wait for something to happen
  529. select {
  530. case <-s.update:
  531. // Something happened (new peer, delivery, timeout), recheck tasks
  532. case <-peerJoin:
  533. // A new peer joined, try to schedule it new tasks
  534. case id := <-peerDrop:
  535. s.revertRequests(id)
  536. case <-cancel:
  537. return ErrCancelled
  538. case req := <-accountReqFails:
  539. s.revertAccountRequest(req)
  540. case req := <-bytecodeReqFails:
  541. s.revertBytecodeRequest(req)
  542. case req := <-storageReqFails:
  543. s.revertStorageRequest(req)
  544. case req := <-trienodeHealReqFails:
  545. s.revertTrienodeHealRequest(req)
  546. case req := <-bytecodeHealReqFails:
  547. s.revertBytecodeHealRequest(req)
  548. case res := <-accountResps:
  549. s.processAccountResponse(res)
  550. case res := <-bytecodeResps:
  551. s.processBytecodeResponse(res)
  552. case res := <-storageResps:
  553. s.processStorageResponse(res)
  554. case res := <-trienodeHealResps:
  555. s.processTrienodeHealResponse(res)
  556. case res := <-bytecodeHealResps:
  557. s.processBytecodeHealResponse(res)
  558. }
  559. // Report stats if something meaningful happened
  560. s.report(false)
  561. }
  562. }
  563. // loadSyncStatus retrieves a previously aborted sync status from the database,
  564. // or generates a fresh one if none is available.
  565. func (s *Syncer) loadSyncStatus() {
  566. var progress syncProgress
  567. if status := rawdb.ReadSnapshotSyncStatus(s.db); status != nil {
  568. if err := json.Unmarshal(status, &progress); err != nil {
  569. log.Error("Failed to decode snap sync status", "err", err)
  570. } else {
  571. for _, task := range progress.Tasks {
  572. log.Debug("Scheduled account sync task", "from", task.Next, "last", task.Last)
  573. }
  574. s.tasks = progress.Tasks
  575. for _, task := range s.tasks {
  576. task.genBatch = s.db.NewBatch()
  577. task.genTrie = trie.NewStackTrie(task.genBatch)
  578. for _, subtasks := range task.SubTasks {
  579. for _, subtask := range subtasks {
  580. subtask.genBatch = s.db.NewBatch()
  581. subtask.genTrie = trie.NewStackTrie(task.genBatch)
  582. }
  583. }
  584. }
  585. s.snapped = len(s.tasks) == 0
  586. s.accountSynced = progress.AccountSynced
  587. s.accountBytes = progress.AccountBytes
  588. s.bytecodeSynced = progress.BytecodeSynced
  589. s.bytecodeBytes = progress.BytecodeBytes
  590. s.storageSynced = progress.StorageSynced
  591. s.storageBytes = progress.StorageBytes
  592. s.trienodeHealSynced = progress.TrienodeHealSynced
  593. s.trienodeHealBytes = progress.TrienodeHealBytes
  594. s.bytecodeHealSynced = progress.BytecodeHealSynced
  595. s.bytecodeHealBytes = progress.BytecodeHealBytes
  596. return
  597. }
  598. }
  599. // Either we've failed to decode the previus state, or there was none.
  600. // Start a fresh sync by chunking up the account range and scheduling
  601. // them for retrieval.
  602. s.tasks = nil
  603. s.accountSynced, s.accountBytes = 0, 0
  604. s.bytecodeSynced, s.bytecodeBytes = 0, 0
  605. s.storageSynced, s.storageBytes = 0, 0
  606. s.trienodeHealSynced, s.trienodeHealBytes = 0, 0
  607. s.bytecodeHealSynced, s.bytecodeHealBytes = 0, 0
  608. var next common.Hash
  609. step := new(big.Int).Sub(
  610. new(big.Int).Div(
  611. new(big.Int).Exp(common.Big2, common.Big256, nil),
  612. big.NewInt(int64(accountConcurrency)),
  613. ), common.Big1,
  614. )
  615. for i := 0; i < accountConcurrency; i++ {
  616. last := common.BigToHash(new(big.Int).Add(next.Big(), step))
  617. if i == accountConcurrency-1 {
  618. // Make sure we don't overflow if the step is not a proper divisor
  619. last = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
  620. }
  621. batch := s.db.NewBatch()
  622. s.tasks = append(s.tasks, &accountTask{
  623. Next: next,
  624. Last: last,
  625. SubTasks: make(map[common.Hash][]*storageTask),
  626. genBatch: batch,
  627. genTrie: trie.NewStackTrie(batch),
  628. })
  629. log.Debug("Created account sync task", "from", next, "last", last)
  630. next = common.BigToHash(new(big.Int).Add(last.Big(), common.Big1))
  631. }
  632. }
  633. // saveSyncStatus marshals the remaining sync tasks into leveldb.
  634. func (s *Syncer) saveSyncStatus() {
  635. // Serialize any partial progress to disk before spinning down
  636. for _, task := range s.tasks {
  637. keys, bytes := task.genBatch.KeyCount(), task.genBatch.ValueSize()
  638. if err := task.genBatch.Write(); err != nil {
  639. log.Error("Failed to persist account slots", "err", err)
  640. }
  641. s.accountBytes += common.StorageSize(keys*common.HashLength + bytes)
  642. for _, subtasks := range task.SubTasks {
  643. for _, subtask := range subtasks {
  644. keys, bytes := subtask.genBatch.KeyCount(), subtask.genBatch.ValueSize()
  645. if err := subtask.genBatch.Write(); err != nil {
  646. log.Error("Failed to persist storage slots", "err", err)
  647. }
  648. s.accountBytes += common.StorageSize(keys*common.HashLength + bytes)
  649. }
  650. }
  651. }
  652. // Store the actual progress markers
  653. progress := &syncProgress{
  654. Tasks: s.tasks,
  655. AccountSynced: s.accountSynced,
  656. AccountBytes: s.accountBytes,
  657. BytecodeSynced: s.bytecodeSynced,
  658. BytecodeBytes: s.bytecodeBytes,
  659. StorageSynced: s.storageSynced,
  660. StorageBytes: s.storageBytes,
  661. TrienodeHealSynced: s.trienodeHealSynced,
  662. TrienodeHealBytes: s.trienodeHealBytes,
  663. BytecodeHealSynced: s.bytecodeHealSynced,
  664. BytecodeHealBytes: s.bytecodeHealBytes,
  665. }
  666. status, err := json.Marshal(progress)
  667. if err != nil {
  668. panic(err) // This can only fail during implementation
  669. }
  670. rawdb.WriteSnapshotSyncStatus(s.db, status)
  671. }
  672. // cleanAccountTasks removes account range retrieval tasks that have already been
  673. // completed.
  674. func (s *Syncer) cleanAccountTasks() {
  675. // If the sync was already done before, don't even bother
  676. if len(s.tasks) == 0 {
  677. return
  678. }
  679. // Sync wasn't finished previously, check for any task that can be finalized
  680. for i := 0; i < len(s.tasks); i++ {
  681. if s.tasks[i].done {
  682. s.tasks = append(s.tasks[:i], s.tasks[i+1:]...)
  683. i--
  684. }
  685. }
  686. // If everything was just finalized just, generate the account trie and start heal
  687. if len(s.tasks) == 0 {
  688. s.lock.Lock()
  689. s.snapped = true
  690. s.lock.Unlock()
  691. // Push the final sync report
  692. s.reportSyncProgress(true)
  693. }
  694. }
  695. // cleanStorageTasks iterates over all the account tasks and storage sub-tasks
  696. // within, cleaning any that have been completed.
  697. func (s *Syncer) cleanStorageTasks() {
  698. for _, task := range s.tasks {
  699. for account, subtasks := range task.SubTasks {
  700. // Remove storage range retrieval tasks that completed
  701. for j := 0; j < len(subtasks); j++ {
  702. if subtasks[j].done {
  703. subtasks = append(subtasks[:j], subtasks[j+1:]...)
  704. j--
  705. }
  706. }
  707. if len(subtasks) > 0 {
  708. task.SubTasks[account] = subtasks
  709. continue
  710. }
  711. // If all storage chunks are done, mark the account as done too
  712. for j, hash := range task.res.hashes {
  713. if hash == account {
  714. task.needState[j] = false
  715. }
  716. }
  717. delete(task.SubTasks, account)
  718. task.pend--
  719. // If this was the last pending task, forward the account task
  720. if task.pend == 0 {
  721. s.forwardAccountTask(task)
  722. }
  723. }
  724. }
  725. }
  726. // assignAccountTasks attempts to match idle peers to pending account range
  727. // retrievals.
  728. func (s *Syncer) assignAccountTasks(success chan *accountResponse, fail chan *accountRequest, cancel chan struct{}) {
  729. s.lock.Lock()
  730. defer s.lock.Unlock()
  731. // If there are no idle peers, short circuit assignment
  732. if len(s.accountIdlers) == 0 {
  733. return
  734. }
  735. // Iterate over all the tasks and try to find a pending one
  736. for _, task := range s.tasks {
  737. // Skip any tasks already filling
  738. if task.req != nil || task.res != nil {
  739. continue
  740. }
  741. // Task pending retrieval, try to find an idle peer. If no such peer
  742. // exists, we probably assigned tasks for all (or they are stateless).
  743. // Abort the entire assignment mechanism.
  744. var idle string
  745. for id := range s.accountIdlers {
  746. // If the peer rejected a query in this sync cycle, don't bother asking
  747. // again for anything, it's either out of sync or already pruned
  748. if _, ok := s.statelessPeers[id]; ok {
  749. continue
  750. }
  751. idle = id
  752. break
  753. }
  754. if idle == "" {
  755. return
  756. }
  757. peer := s.peers[idle]
  758. // Matched a pending task to an idle peer, allocate a unique request id
  759. var reqid uint64
  760. for {
  761. reqid = uint64(rand.Int63())
  762. if reqid == 0 {
  763. continue
  764. }
  765. if _, ok := s.accountReqs[reqid]; ok {
  766. continue
  767. }
  768. break
  769. }
  770. // Generate the network query and send it to the peer
  771. req := &accountRequest{
  772. peer: idle,
  773. id: reqid,
  774. deliver: success,
  775. revert: fail,
  776. cancel: cancel,
  777. stale: make(chan struct{}),
  778. origin: task.Next,
  779. limit: task.Last,
  780. task: task,
  781. }
  782. req.timeout = time.AfterFunc(requestTimeout, func() {
  783. peer.Log().Debug("Account range request timed out", "reqid", reqid)
  784. s.scheduleRevertAccountRequest(req)
  785. })
  786. s.accountReqs[reqid] = req
  787. delete(s.accountIdlers, idle)
  788. s.pend.Add(1)
  789. go func(root common.Hash) {
  790. defer s.pend.Done()
  791. // Attempt to send the remote request and revert if it fails
  792. if err := peer.RequestAccountRange(reqid, root, req.origin, req.limit, maxRequestSize); err != nil {
  793. peer.Log().Debug("Failed to request account range", "err", err)
  794. s.scheduleRevertAccountRequest(req)
  795. }
  796. }(s.root)
  797. // Inject the request into the task to block further assignments
  798. task.req = req
  799. }
  800. }
  801. // assignBytecodeTasks attempts to match idle peers to pending code retrievals.
  802. func (s *Syncer) assignBytecodeTasks(success chan *bytecodeResponse, fail chan *bytecodeRequest, cancel chan struct{}) {
  803. s.lock.Lock()
  804. defer s.lock.Unlock()
  805. // If there are no idle peers, short circuit assignment
  806. if len(s.bytecodeIdlers) == 0 {
  807. return
  808. }
  809. // Iterate over all the tasks and try to find a pending one
  810. for _, task := range s.tasks {
  811. // Skip any tasks not in the bytecode retrieval phase
  812. if task.res == nil {
  813. continue
  814. }
  815. // Skip tasks that are already retrieving (or done with) all codes
  816. if len(task.codeTasks) == 0 {
  817. continue
  818. }
  819. // Task pending retrieval, try to find an idle peer. If no such peer
  820. // exists, we probably assigned tasks for all (or they are stateless).
  821. // Abort the entire assignment mechanism.
  822. var idle string
  823. for id := range s.bytecodeIdlers {
  824. // If the peer rejected a query in this sync cycle, don't bother asking
  825. // again for anything, it's either out of sync or already pruned
  826. if _, ok := s.statelessPeers[id]; ok {
  827. continue
  828. }
  829. idle = id
  830. break
  831. }
  832. if idle == "" {
  833. return
  834. }
  835. peer := s.peers[idle]
  836. // Matched a pending task to an idle peer, allocate a unique request id
  837. var reqid uint64
  838. for {
  839. reqid = uint64(rand.Int63())
  840. if reqid == 0 {
  841. continue
  842. }
  843. if _, ok := s.bytecodeReqs[reqid]; ok {
  844. continue
  845. }
  846. break
  847. }
  848. // Generate the network query and send it to the peer
  849. hashes := make([]common.Hash, 0, maxCodeRequestCount)
  850. for hash := range task.codeTasks {
  851. delete(task.codeTasks, hash)
  852. hashes = append(hashes, hash)
  853. if len(hashes) >= maxCodeRequestCount {
  854. break
  855. }
  856. }
  857. req := &bytecodeRequest{
  858. peer: idle,
  859. id: reqid,
  860. deliver: success,
  861. revert: fail,
  862. cancel: cancel,
  863. stale: make(chan struct{}),
  864. hashes: hashes,
  865. task: task,
  866. }
  867. req.timeout = time.AfterFunc(requestTimeout, func() {
  868. peer.Log().Debug("Bytecode request timed out", "reqid", reqid)
  869. s.scheduleRevertBytecodeRequest(req)
  870. })
  871. s.bytecodeReqs[reqid] = req
  872. delete(s.bytecodeIdlers, idle)
  873. s.pend.Add(1)
  874. go func() {
  875. defer s.pend.Done()
  876. // Attempt to send the remote request and revert if it fails
  877. if err := peer.RequestByteCodes(reqid, hashes, maxRequestSize); err != nil {
  878. log.Debug("Failed to request bytecodes", "err", err)
  879. s.scheduleRevertBytecodeRequest(req)
  880. }
  881. }()
  882. }
  883. }
  884. // assignStorageTasks attempts to match idle peers to pending storage range
  885. // retrievals.
  886. func (s *Syncer) assignStorageTasks(success chan *storageResponse, fail chan *storageRequest, cancel chan struct{}) {
  887. s.lock.Lock()
  888. defer s.lock.Unlock()
  889. // If there are no idle peers, short circuit assignment
  890. if len(s.storageIdlers) == 0 {
  891. return
  892. }
  893. // Iterate over all the tasks and try to find a pending one
  894. for _, task := range s.tasks {
  895. // Skip any tasks not in the storage retrieval phase
  896. if task.res == nil {
  897. continue
  898. }
  899. // Skip tasks that are already retrieving (or done with) all small states
  900. if len(task.SubTasks) == 0 && len(task.stateTasks) == 0 {
  901. continue
  902. }
  903. // Task pending retrieval, try to find an idle peer. If no such peer
  904. // exists, we probably assigned tasks for all (or they are stateless).
  905. // Abort the entire assignment mechanism.
  906. var idle string
  907. for id := range s.storageIdlers {
  908. // If the peer rejected a query in this sync cycle, don't bother asking
  909. // again for anything, it's either out of sync or already pruned
  910. if _, ok := s.statelessPeers[id]; ok {
  911. continue
  912. }
  913. idle = id
  914. break
  915. }
  916. if idle == "" {
  917. return
  918. }
  919. peer := s.peers[idle]
  920. // Matched a pending task to an idle peer, allocate a unique request id
  921. var reqid uint64
  922. for {
  923. reqid = uint64(rand.Int63())
  924. if reqid == 0 {
  925. continue
  926. }
  927. if _, ok := s.storageReqs[reqid]; ok {
  928. continue
  929. }
  930. break
  931. }
  932. // Generate the network query and send it to the peer. If there are
  933. // large contract tasks pending, complete those before diving into
  934. // even more new contracts.
  935. var (
  936. accounts = make([]common.Hash, 0, maxStorageSetRequestCount)
  937. roots = make([]common.Hash, 0, maxStorageSetRequestCount)
  938. subtask *storageTask
  939. )
  940. for account, subtasks := range task.SubTasks {
  941. for _, st := range subtasks {
  942. // Skip any subtasks already filling
  943. if st.req != nil {
  944. continue
  945. }
  946. // Found an incomplete storage chunk, schedule it
  947. accounts = append(accounts, account)
  948. roots = append(roots, st.root)
  949. subtask = st
  950. break // Large contract chunks are downloaded individually
  951. }
  952. if subtask != nil {
  953. break // Large contract chunks are downloaded individually
  954. }
  955. }
  956. if subtask == nil {
  957. // No large contract required retrieval, but small ones available
  958. for acccount, root := range task.stateTasks {
  959. delete(task.stateTasks, acccount)
  960. accounts = append(accounts, acccount)
  961. roots = append(roots, root)
  962. if len(accounts) >= maxStorageSetRequestCount {
  963. break
  964. }
  965. }
  966. }
  967. // If nothing was found, it means this task is actually already fully
  968. // retrieving, but large contracts are hard to detect. Skip to the next.
  969. if len(accounts) == 0 {
  970. continue
  971. }
  972. req := &storageRequest{
  973. peer: idle,
  974. id: reqid,
  975. deliver: success,
  976. revert: fail,
  977. cancel: cancel,
  978. stale: make(chan struct{}),
  979. accounts: accounts,
  980. roots: roots,
  981. mainTask: task,
  982. subTask: subtask,
  983. }
  984. if subtask != nil {
  985. req.origin = subtask.Next
  986. req.limit = subtask.Last
  987. }
  988. req.timeout = time.AfterFunc(requestTimeout, func() {
  989. peer.Log().Debug("Storage request timed out", "reqid", reqid)
  990. s.scheduleRevertStorageRequest(req)
  991. })
  992. s.storageReqs[reqid] = req
  993. delete(s.storageIdlers, idle)
  994. s.pend.Add(1)
  995. go func(root common.Hash) {
  996. defer s.pend.Done()
  997. // Attempt to send the remote request and revert if it fails
  998. var origin, limit []byte
  999. if subtask != nil {
  1000. origin, limit = req.origin[:], req.limit[:]
  1001. }
  1002. if err := peer.RequestStorageRanges(reqid, root, accounts, origin, limit, maxRequestSize); err != nil {
  1003. log.Debug("Failed to request storage", "err", err)
  1004. s.scheduleRevertStorageRequest(req)
  1005. }
  1006. }(s.root)
  1007. // Inject the request into the subtask to block further assignments
  1008. if subtask != nil {
  1009. subtask.req = req
  1010. }
  1011. }
  1012. }
  1013. // assignTrienodeHealTasks attempts to match idle peers to trie node requests to
  1014. // heal any trie errors caused by the snap sync's chunked retrieval model.
  1015. func (s *Syncer) assignTrienodeHealTasks(success chan *trienodeHealResponse, fail chan *trienodeHealRequest, cancel chan struct{}) {
  1016. s.lock.Lock()
  1017. defer s.lock.Unlock()
  1018. // If there are no idle peers, short circuit assignment
  1019. if len(s.trienodeHealIdlers) == 0 {
  1020. return
  1021. }
  1022. // Iterate over pending tasks and try to find a peer to retrieve with
  1023. for len(s.healer.trieTasks) > 0 || s.healer.scheduler.Pending() > 0 {
  1024. // If there are not enough trie tasks queued to fully assign, fill the
  1025. // queue from the state sync scheduler. The trie synced schedules these
  1026. // together with bytecodes, so we need to queue them combined.
  1027. var (
  1028. have = len(s.healer.trieTasks) + len(s.healer.codeTasks)
  1029. want = maxTrieRequestCount + maxCodeRequestCount
  1030. )
  1031. if have < want {
  1032. nodes, paths, codes := s.healer.scheduler.Missing(want - have)
  1033. for i, hash := range nodes {
  1034. s.healer.trieTasks[hash] = paths[i]
  1035. }
  1036. for _, hash := range codes {
  1037. s.healer.codeTasks[hash] = struct{}{}
  1038. }
  1039. }
  1040. // If all the heal tasks are bytecodes or already downloading, bail
  1041. if len(s.healer.trieTasks) == 0 {
  1042. return
  1043. }
  1044. // Task pending retrieval, try to find an idle peer. If no such peer
  1045. // exists, we probably assigned tasks for all (or they are stateless).
  1046. // Abort the entire assignment mechanism.
  1047. var idle string
  1048. for id := range s.trienodeHealIdlers {
  1049. // If the peer rejected a query in this sync cycle, don't bother asking
  1050. // again for anything, it's either out of sync or already pruned
  1051. if _, ok := s.statelessPeers[id]; ok {
  1052. continue
  1053. }
  1054. idle = id
  1055. break
  1056. }
  1057. if idle == "" {
  1058. return
  1059. }
  1060. peer := s.peers[idle]
  1061. // Matched a pending task to an idle peer, allocate a unique request id
  1062. var reqid uint64
  1063. for {
  1064. reqid = uint64(rand.Int63())
  1065. if reqid == 0 {
  1066. continue
  1067. }
  1068. if _, ok := s.trienodeHealReqs[reqid]; ok {
  1069. continue
  1070. }
  1071. break
  1072. }
  1073. // Generate the network query and send it to the peer
  1074. var (
  1075. hashes = make([]common.Hash, 0, maxTrieRequestCount)
  1076. paths = make([]trie.SyncPath, 0, maxTrieRequestCount)
  1077. pathsets = make([]TrieNodePathSet, 0, maxTrieRequestCount)
  1078. )
  1079. for hash, pathset := range s.healer.trieTasks {
  1080. delete(s.healer.trieTasks, hash)
  1081. hashes = append(hashes, hash)
  1082. paths = append(paths, pathset)
  1083. pathsets = append(pathsets, [][]byte(pathset)) // TODO(karalabe): group requests by account hash
  1084. if len(hashes) >= maxTrieRequestCount {
  1085. break
  1086. }
  1087. }
  1088. req := &trienodeHealRequest{
  1089. peer: idle,
  1090. id: reqid,
  1091. deliver: success,
  1092. revert: fail,
  1093. cancel: cancel,
  1094. stale: make(chan struct{}),
  1095. hashes: hashes,
  1096. paths: paths,
  1097. task: s.healer,
  1098. }
  1099. req.timeout = time.AfterFunc(requestTimeout, func() {
  1100. peer.Log().Debug("Trienode heal request timed out", "reqid", reqid)
  1101. s.scheduleRevertTrienodeHealRequest(req)
  1102. })
  1103. s.trienodeHealReqs[reqid] = req
  1104. delete(s.trienodeHealIdlers, idle)
  1105. s.pend.Add(1)
  1106. go func(root common.Hash) {
  1107. defer s.pend.Done()
  1108. // Attempt to send the remote request and revert if it fails
  1109. if err := peer.RequestTrieNodes(reqid, root, pathsets, maxRequestSize); err != nil {
  1110. log.Debug("Failed to request trienode healers", "err", err)
  1111. s.scheduleRevertTrienodeHealRequest(req)
  1112. }
  1113. }(s.root)
  1114. }
  1115. }
  1116. // assignBytecodeHealTasks attempts to match idle peers to bytecode requests to
  1117. // heal any trie errors caused by the snap sync's chunked retrieval model.
  1118. func (s *Syncer) assignBytecodeHealTasks(success chan *bytecodeHealResponse, fail chan *bytecodeHealRequest, cancel chan struct{}) {
  1119. s.lock.Lock()
  1120. defer s.lock.Unlock()
  1121. // If there are no idle peers, short circuit assignment
  1122. if len(s.bytecodeHealIdlers) == 0 {
  1123. return
  1124. }
  1125. // Iterate over pending tasks and try to find a peer to retrieve with
  1126. for len(s.healer.codeTasks) > 0 || s.healer.scheduler.Pending() > 0 {
  1127. // If there are not enough trie tasks queued to fully assign, fill the
  1128. // queue from the state sync scheduler. The trie synced schedules these
  1129. // together with trie nodes, so we need to queue them combined.
  1130. var (
  1131. have = len(s.healer.trieTasks) + len(s.healer.codeTasks)
  1132. want = maxTrieRequestCount + maxCodeRequestCount
  1133. )
  1134. if have < want {
  1135. nodes, paths, codes := s.healer.scheduler.Missing(want - have)
  1136. for i, hash := range nodes {
  1137. s.healer.trieTasks[hash] = paths[i]
  1138. }
  1139. for _, hash := range codes {
  1140. s.healer.codeTasks[hash] = struct{}{}
  1141. }
  1142. }
  1143. // If all the heal tasks are trienodes or already downloading, bail
  1144. if len(s.healer.codeTasks) == 0 {
  1145. return
  1146. }
  1147. // Task pending retrieval, try to find an idle peer. If no such peer
  1148. // exists, we probably assigned tasks for all (or they are stateless).
  1149. // Abort the entire assignment mechanism.
  1150. var idle string
  1151. for id := range s.bytecodeHealIdlers {
  1152. // If the peer rejected a query in this sync cycle, don't bother asking
  1153. // again for anything, it's either out of sync or already pruned
  1154. if _, ok := s.statelessPeers[id]; ok {
  1155. continue
  1156. }
  1157. idle = id
  1158. break
  1159. }
  1160. if idle == "" {
  1161. return
  1162. }
  1163. peer := s.peers[idle]
  1164. // Matched a pending task to an idle peer, allocate a unique request id
  1165. var reqid uint64
  1166. for {
  1167. reqid = uint64(rand.Int63())
  1168. if reqid == 0 {
  1169. continue
  1170. }
  1171. if _, ok := s.bytecodeHealReqs[reqid]; ok {
  1172. continue
  1173. }
  1174. break
  1175. }
  1176. // Generate the network query and send it to the peer
  1177. hashes := make([]common.Hash, 0, maxCodeRequestCount)
  1178. for hash := range s.healer.codeTasks {
  1179. delete(s.healer.codeTasks, hash)
  1180. hashes = append(hashes, hash)
  1181. if len(hashes) >= maxCodeRequestCount {
  1182. break
  1183. }
  1184. }
  1185. req := &bytecodeHealRequest{
  1186. peer: idle,
  1187. id: reqid,
  1188. deliver: success,
  1189. revert: fail,
  1190. cancel: cancel,
  1191. stale: make(chan struct{}),
  1192. hashes: hashes,
  1193. task: s.healer,
  1194. }
  1195. req.timeout = time.AfterFunc(requestTimeout, func() {
  1196. peer.Log().Debug("Bytecode heal request timed out", "reqid", reqid)
  1197. s.scheduleRevertBytecodeHealRequest(req)
  1198. })
  1199. s.bytecodeHealReqs[reqid] = req
  1200. delete(s.bytecodeHealIdlers, idle)
  1201. s.pend.Add(1)
  1202. go func() {
  1203. defer s.pend.Done()
  1204. // Attempt to send the remote request and revert if it fails
  1205. if err := peer.RequestByteCodes(reqid, hashes, maxRequestSize); err != nil {
  1206. log.Debug("Failed to request bytecode healers", "err", err)
  1207. s.scheduleRevertBytecodeHealRequest(req)
  1208. }
  1209. }()
  1210. }
  1211. }
  1212. // revertRequests locates all the currently pending reuqests from a particular
  1213. // peer and reverts them, rescheduling for others to fulfill.
  1214. func (s *Syncer) revertRequests(peer string) {
  1215. // Gather the requests first, revertals need the lock too
  1216. s.lock.Lock()
  1217. var accountReqs []*accountRequest
  1218. for _, req := range s.accountReqs {
  1219. if req.peer == peer {
  1220. accountReqs = append(accountReqs, req)
  1221. }
  1222. }
  1223. var bytecodeReqs []*bytecodeRequest
  1224. for _, req := range s.bytecodeReqs {
  1225. if req.peer == peer {
  1226. bytecodeReqs = append(bytecodeReqs, req)
  1227. }
  1228. }
  1229. var storageReqs []*storageRequest
  1230. for _, req := range s.storageReqs {
  1231. if req.peer == peer {
  1232. storageReqs = append(storageReqs, req)
  1233. }
  1234. }
  1235. var trienodeHealReqs []*trienodeHealRequest
  1236. for _, req := range s.trienodeHealReqs {
  1237. if req.peer == peer {
  1238. trienodeHealReqs = append(trienodeHealReqs, req)
  1239. }
  1240. }
  1241. var bytecodeHealReqs []*bytecodeHealRequest
  1242. for _, req := range s.bytecodeHealReqs {
  1243. if req.peer == peer {
  1244. bytecodeHealReqs = append(bytecodeHealReqs, req)
  1245. }
  1246. }
  1247. s.lock.Unlock()
  1248. // Revert all the requests matching the peer
  1249. for _, req := range accountReqs {
  1250. s.revertAccountRequest(req)
  1251. }
  1252. for _, req := range bytecodeReqs {
  1253. s.revertBytecodeRequest(req)
  1254. }
  1255. for _, req := range storageReqs {
  1256. s.revertStorageRequest(req)
  1257. }
  1258. for _, req := range trienodeHealReqs {
  1259. s.revertTrienodeHealRequest(req)
  1260. }
  1261. for _, req := range bytecodeHealReqs {
  1262. s.revertBytecodeHealRequest(req)
  1263. }
  1264. }
  1265. // scheduleRevertAccountRequest asks the event loop to clean up an account range
  1266. // request and return all failed retrieval tasks to the scheduler for reassignment.
  1267. func (s *Syncer) scheduleRevertAccountRequest(req *accountRequest) {
  1268. select {
  1269. case req.revert <- req:
  1270. // Sync event loop notified
  1271. case <-req.cancel:
  1272. // Sync cycle got cancelled
  1273. case <-req.stale:
  1274. // Request already reverted
  1275. }
  1276. }
  1277. // revertAccountRequest cleans up an account range request and returns all failed
  1278. // retrieval tasks to the scheduler for reassignment.
  1279. //
  1280. // Note, this needs to run on the event runloop thread to reschedule to idle peers.
  1281. // On peer threads, use scheduleRevertAccountRequest.
  1282. func (s *Syncer) revertAccountRequest(req *accountRequest) {
  1283. log.Debug("Reverting account request", "peer", req.peer, "reqid", req.id)
  1284. select {
  1285. case <-req.stale:
  1286. log.Trace("Account request already reverted", "peer", req.peer, "reqid", req.id)
  1287. return
  1288. default:
  1289. }
  1290. close(req.stale)
  1291. // Remove the request from the tracked set
  1292. s.lock.Lock()
  1293. delete(s.accountReqs, req.id)
  1294. s.lock.Unlock()
  1295. // If there's a timeout timer still running, abort it and mark the account
  1296. // task as not-pending, ready for resheduling
  1297. req.timeout.Stop()
  1298. if req.task.req == req {
  1299. req.task.req = nil
  1300. }
  1301. }
  1302. // scheduleRevertBytecodeRequest asks the event loop to clean up a bytecode request
  1303. // and return all failed retrieval tasks to the scheduler for reassignment.
  1304. func (s *Syncer) scheduleRevertBytecodeRequest(req *bytecodeRequest) {
  1305. select {
  1306. case req.revert <- req:
  1307. // Sync event loop notified
  1308. case <-req.cancel:
  1309. // Sync cycle got cancelled
  1310. case <-req.stale:
  1311. // Request already reverted
  1312. }
  1313. }
  1314. // revertBytecodeRequest cleans up a bytecode request and returns all failed
  1315. // retrieval tasks to the scheduler for reassignment.
  1316. //
  1317. // Note, this needs to run on the event runloop thread to reschedule to idle peers.
  1318. // On peer threads, use scheduleRevertBytecodeRequest.
  1319. func (s *Syncer) revertBytecodeRequest(req *bytecodeRequest) {
  1320. log.Debug("Reverting bytecode request", "peer", req.peer)
  1321. select {
  1322. case <-req.stale:
  1323. log.Trace("Bytecode request already reverted", "peer", req.peer, "reqid", req.id)
  1324. return
  1325. default:
  1326. }
  1327. close(req.stale)
  1328. // Remove the request from the tracked set
  1329. s.lock.Lock()
  1330. delete(s.bytecodeReqs, req.id)
  1331. s.lock.Unlock()
  1332. // If there's a timeout timer still running, abort it and mark the code
  1333. // retrievals as not-pending, ready for resheduling
  1334. req.timeout.Stop()
  1335. for _, hash := range req.hashes {
  1336. req.task.codeTasks[hash] = struct{}{}
  1337. }
  1338. }
  1339. // scheduleRevertStorageRequest asks the event loop to clean up a storage range
  1340. // request and return all failed retrieval tasks to the scheduler for reassignment.
  1341. func (s *Syncer) scheduleRevertStorageRequest(req *storageRequest) {
  1342. select {
  1343. case req.revert <- req:
  1344. // Sync event loop notified
  1345. case <-req.cancel:
  1346. // Sync cycle got cancelled
  1347. case <-req.stale:
  1348. // Request already reverted
  1349. }
  1350. }
  1351. // revertStorageRequest cleans up a storage range request and returns all failed
  1352. // retrieval tasks to the scheduler for reassignment.
  1353. //
  1354. // Note, this needs to run on the event runloop thread to reschedule to idle peers.
  1355. // On peer threads, use scheduleRevertStorageRequest.
  1356. func (s *Syncer) revertStorageRequest(req *storageRequest) {
  1357. log.Debug("Reverting storage request", "peer", req.peer)
  1358. select {
  1359. case <-req.stale:
  1360. log.Trace("Storage request already reverted", "peer", req.peer, "reqid", req.id)
  1361. return
  1362. default:
  1363. }
  1364. close(req.stale)
  1365. // Remove the request from the tracked set
  1366. s.lock.Lock()
  1367. delete(s.storageReqs, req.id)
  1368. s.lock.Unlock()
  1369. // If there's a timeout timer still running, abort it and mark the storage
  1370. // task as not-pending, ready for resheduling
  1371. req.timeout.Stop()
  1372. if req.subTask != nil {
  1373. req.subTask.req = nil
  1374. } else {
  1375. for i, account := range req.accounts {
  1376. req.mainTask.stateTasks[account] = req.roots[i]
  1377. }
  1378. }
  1379. }
  1380. // scheduleRevertTrienodeHealRequest asks the event loop to clean up a trienode heal
  1381. // request and return all failed retrieval tasks to the scheduler for reassignment.
  1382. func (s *Syncer) scheduleRevertTrienodeHealRequest(req *trienodeHealRequest) {
  1383. select {
  1384. case req.revert <- req:
  1385. // Sync event loop notified
  1386. case <-req.cancel:
  1387. // Sync cycle got cancelled
  1388. case <-req.stale:
  1389. // Request already reverted
  1390. }
  1391. }
  1392. // revertTrienodeHealRequest cleans up a trienode heal request and returns all
  1393. // failed retrieval tasks to the scheduler for reassignment.
  1394. //
  1395. // Note, this needs to run on the event runloop thread to reschedule to idle peers.
  1396. // On peer threads, use scheduleRevertTrienodeHealRequest.
  1397. func (s *Syncer) revertTrienodeHealRequest(req *trienodeHealRequest) {
  1398. log.Debug("Reverting trienode heal request", "peer", req.peer)
  1399. select {
  1400. case <-req.stale:
  1401. log.Trace("Trienode heal request already reverted", "peer", req.peer, "reqid", req.id)
  1402. return
  1403. default:
  1404. }
  1405. close(req.stale)
  1406. // Remove the request from the tracked set
  1407. s.lock.Lock()
  1408. delete(s.trienodeHealReqs, req.id)
  1409. s.lock.Unlock()
  1410. // If there's a timeout timer still running, abort it and mark the trie node
  1411. // retrievals as not-pending, ready for resheduling
  1412. req.timeout.Stop()
  1413. for i, hash := range req.hashes {
  1414. req.task.trieTasks[hash] = req.paths[i]
  1415. }
  1416. }
  1417. // scheduleRevertBytecodeHealRequest asks the event loop to clean up a bytecode heal
  1418. // request and return all failed retrieval tasks to the scheduler for reassignment.
  1419. func (s *Syncer) scheduleRevertBytecodeHealRequest(req *bytecodeHealRequest) {
  1420. select {
  1421. case req.revert <- req:
  1422. // Sync event loop notified
  1423. case <-req.cancel:
  1424. // Sync cycle got cancelled
  1425. case <-req.stale:
  1426. // Request already reverted
  1427. }
  1428. }
  1429. // revertBytecodeHealRequest cleans up a bytecode heal request and returns all
  1430. // failed retrieval tasks to the scheduler for reassignment.
  1431. //
  1432. // Note, this needs to run on the event runloop thread to reschedule to idle peers.
  1433. // On peer threads, use scheduleRevertBytecodeHealRequest.
  1434. func (s *Syncer) revertBytecodeHealRequest(req *bytecodeHealRequest) {
  1435. log.Debug("Reverting bytecode heal request", "peer", req.peer)
  1436. select {
  1437. case <-req.stale:
  1438. log.Trace("Bytecode heal request already reverted", "peer", req.peer, "reqid", req.id)
  1439. return
  1440. default:
  1441. }
  1442. close(req.stale)
  1443. // Remove the request from the tracked set
  1444. s.lock.Lock()
  1445. delete(s.bytecodeHealReqs, req.id)
  1446. s.lock.Unlock()
  1447. // If there's a timeout timer still running, abort it and mark the code
  1448. // retrievals as not-pending, ready for resheduling
  1449. req.timeout.Stop()
  1450. for _, hash := range req.hashes {
  1451. req.task.codeTasks[hash] = struct{}{}
  1452. }
  1453. }
  1454. // processAccountResponse integrates an already validated account range response
  1455. // into the account tasks.
  1456. func (s *Syncer) processAccountResponse(res *accountResponse) {
  1457. // Switch the task from pending to filling
  1458. res.task.req = nil
  1459. res.task.res = res
  1460. // Ensure that the response doesn't overflow into the subsequent task
  1461. last := res.task.Last.Big()
  1462. for i, hash := range res.hashes {
  1463. // Mark the range complete if the last is already included.
  1464. // Keep iteration to delete the extra states if exists.
  1465. cmp := hash.Big().Cmp(last)
  1466. if cmp == 0 {
  1467. res.cont = false
  1468. continue
  1469. }
  1470. if cmp > 0 {
  1471. // Chunk overflown, cut off excess
  1472. res.hashes = res.hashes[:i]
  1473. res.accounts = res.accounts[:i]
  1474. res.cont = false // Mark range completed
  1475. break
  1476. }
  1477. }
  1478. // Iterate over all the accounts and assemble which ones need further sub-
  1479. // filling before the entire account range can be persisted.
  1480. res.task.needCode = make([]bool, len(res.accounts))
  1481. res.task.needState = make([]bool, len(res.accounts))
  1482. res.task.needHeal = make([]bool, len(res.accounts))
  1483. res.task.codeTasks = make(map[common.Hash]struct{})
  1484. res.task.stateTasks = make(map[common.Hash]common.Hash)
  1485. resumed := make(map[common.Hash]struct{})
  1486. res.task.pend = 0
  1487. for i, account := range res.accounts {
  1488. // Check if the account is a contract with an unknown code
  1489. if !bytes.Equal(account.CodeHash, emptyCode[:]) {
  1490. if code := rawdb.ReadCodeWithPrefix(s.db, common.BytesToHash(account.CodeHash)); code == nil {
  1491. res.task.codeTasks[common.BytesToHash(account.CodeHash)] = struct{}{}
  1492. res.task.needCode[i] = true
  1493. res.task.pend++
  1494. }
  1495. }
  1496. // Check if the account is a contract with an unknown storage trie
  1497. if account.Root != emptyRoot {
  1498. if node, err := s.db.Get(account.Root[:]); err != nil || node == nil {
  1499. // If there was a previous large state retrieval in progress,
  1500. // don't restart it from scratch. This happens if a sync cycle
  1501. // is interrupted and resumed later. However, *do* update the
  1502. // previous root hash.
  1503. if subtasks, ok := res.task.SubTasks[res.hashes[i]]; ok {
  1504. log.Debug("Resuming large storage retrieval", "account", res.hashes[i], "root", account.Root)
  1505. for _, subtask := range subtasks {
  1506. subtask.root = account.Root
  1507. }
  1508. res.task.needHeal[i] = true
  1509. resumed[res.hashes[i]] = struct{}{}
  1510. } else {
  1511. res.task.stateTasks[res.hashes[i]] = account.Root
  1512. }
  1513. res.task.needState[i] = true
  1514. res.task.pend++
  1515. }
  1516. }
  1517. }
  1518. // Delete any subtasks that have been aborted but not resumed. This may undo
  1519. // some progress if a new peer gives us less accounts than an old one, but for
  1520. // now we have to live with that.
  1521. for hash := range res.task.SubTasks {
  1522. if _, ok := resumed[hash]; !ok {
  1523. log.Debug("Aborting suspended storage retrieval", "account", hash)
  1524. delete(res.task.SubTasks, hash)
  1525. }
  1526. }
  1527. // If the account range contained no contracts, or all have been fully filled
  1528. // beforehand, short circuit storage filling and forward to the next task
  1529. if res.task.pend == 0 {
  1530. s.forwardAccountTask(res.task)
  1531. return
  1532. }
  1533. // Some accounts are incomplete, leave as is for the storage and contract
  1534. // task assigners to pick up and fill.
  1535. }
  1536. // processBytecodeResponse integrates an already validated bytecode response
  1537. // into the account tasks.
  1538. func (s *Syncer) processBytecodeResponse(res *bytecodeResponse) {
  1539. batch := s.db.NewBatch()
  1540. var (
  1541. codes uint64
  1542. )
  1543. for i, hash := range res.hashes {
  1544. code := res.codes[i]
  1545. // If the bytecode was not delivered, reschedule it
  1546. if code == nil {
  1547. res.task.codeTasks[hash] = struct{}{}
  1548. continue
  1549. }
  1550. // Code was delivered, mark it not needed any more
  1551. for j, account := range res.task.res.accounts {
  1552. if res.task.needCode[j] && hash == common.BytesToHash(account.CodeHash) {
  1553. res.task.needCode[j] = false
  1554. res.task.pend--
  1555. }
  1556. }
  1557. // Push the bytecode into a database batch
  1558. codes++
  1559. rawdb.WriteCode(batch, hash, code)
  1560. }
  1561. bytes := common.StorageSize(batch.ValueSize())
  1562. if err := batch.Write(); err != nil {
  1563. log.Crit("Failed to persist bytecodes", "err", err)
  1564. }
  1565. s.bytecodeSynced += codes
  1566. s.bytecodeBytes += bytes
  1567. log.Debug("Persisted set of bytecodes", "count", codes, "bytes", bytes)
  1568. // If this delivery completed the last pending task, forward the account task
  1569. // to the next chunk
  1570. if res.task.pend == 0 {
  1571. s.forwardAccountTask(res.task)
  1572. return
  1573. }
  1574. // Some accounts are still incomplete, leave as is for the storage and contract
  1575. // task assigners to pick up and fill.
  1576. }
  1577. // processStorageResponse integrates an already validated storage response
  1578. // into the account tasks.
  1579. func (s *Syncer) processStorageResponse(res *storageResponse) {
  1580. // Switch the subtask from pending to idle
  1581. if res.subTask != nil {
  1582. res.subTask.req = nil
  1583. }
  1584. batch := s.db.NewBatch()
  1585. var (
  1586. slots int
  1587. nodes int
  1588. bytes common.StorageSize
  1589. )
  1590. // Iterate over all the accounts and reconstruct their storage tries from the
  1591. // delivered slots
  1592. for i, account := range res.accounts {
  1593. // If the account was not delivered, reschedule it
  1594. if i >= len(res.hashes) {
  1595. res.mainTask.stateTasks[account] = res.roots[i]
  1596. continue
  1597. }
  1598. // State was delivered, if complete mark as not needed any more, otherwise
  1599. // mark the account as needing healing
  1600. for j, hash := range res.mainTask.res.hashes {
  1601. if account != hash {
  1602. continue
  1603. }
  1604. acc := res.mainTask.res.accounts[j]
  1605. // If the packet contains multiple contract storage slots, all
  1606. // but the last are surely complete. The last contract may be
  1607. // chunked, so check it's continuation flag.
  1608. if res.subTask == nil && res.mainTask.needState[j] && (i < len(res.hashes)-1 || !res.cont) {
  1609. res.mainTask.needState[j] = false
  1610. res.mainTask.pend--
  1611. }
  1612. // If the last contract was chunked, mark it as needing healing
  1613. // to avoid writing it out to disk prematurely.
  1614. if res.subTask == nil && !res.mainTask.needHeal[j] && i == len(res.hashes)-1 && res.cont {
  1615. res.mainTask.needHeal[j] = true
  1616. }
  1617. // If the last contract was chunked, we need to switch to large
  1618. // contract handling mode
  1619. if res.subTask == nil && i == len(res.hashes)-1 && res.cont {
  1620. // If we haven't yet started a large-contract retrieval, create
  1621. // the subtasks for it within the main account task
  1622. if tasks, ok := res.mainTask.SubTasks[account]; !ok {
  1623. var (
  1624. keys = res.hashes[i]
  1625. chunks = uint64(storageConcurrency)
  1626. lastKey common.Hash
  1627. )
  1628. if len(keys) > 0 {
  1629. lastKey = keys[len(keys)-1]
  1630. }
  1631. // If the number of slots remaining is low, decrease the
  1632. // number of chunks. Somewhere on the order of 10-15K slots
  1633. // fit into a packet of 500KB. A key/slot pair is maximum 64
  1634. // bytes, so pessimistically maxRequestSize/64 = 8K.
  1635. //
  1636. // Chunk so that at least 2 packets are needed to fill a task.
  1637. if estimate, err := estimateRemainingSlots(len(keys), lastKey); err == nil {
  1638. if n := estimate / (2 * (maxRequestSize / 64)); n+1 < chunks {
  1639. chunks = n + 1
  1640. }
  1641. log.Debug("Chunked large contract", "initiators", len(keys), "tail", lastKey, "remaining", estimate, "chunks", chunks)
  1642. } else {
  1643. log.Debug("Chunked large contract", "initiators", len(keys), "tail", lastKey, "chunks", chunks)
  1644. }
  1645. r := newHashRange(lastKey, chunks)
  1646. // Our first task is the one that was just filled by this response.
  1647. batch := s.db.NewBatch()
  1648. tasks = append(tasks, &storageTask{
  1649. Next: common.Hash{},
  1650. Last: r.End(),
  1651. root: acc.Root,
  1652. genBatch: batch,
  1653. genTrie: trie.NewStackTrie(batch),
  1654. })
  1655. for r.Next() {
  1656. batch := s.db.NewBatch()
  1657. tasks = append(tasks, &storageTask{
  1658. Next: r.Start(),
  1659. Last: r.End(),
  1660. root: acc.Root,
  1661. genBatch: batch,
  1662. genTrie: trie.NewStackTrie(batch),
  1663. })
  1664. }
  1665. for _, task := range tasks {
  1666. log.Debug("Created storage sync task", "account", account, "root", acc.Root, "from", task.Next, "last", task.Last)
  1667. }
  1668. res.mainTask.SubTasks[account] = tasks
  1669. // Since we've just created the sub-tasks, this response
  1670. // is surely for the first one (zero origin)
  1671. res.subTask = tasks[0]
  1672. }
  1673. }
  1674. // If we're in large contract delivery mode, forward the subtask
  1675. if res.subTask != nil {
  1676. // Ensure the response doesn't overflow into the subsequent task
  1677. last := res.subTask.Last.Big()
  1678. // Find the first overflowing key. While at it, mark res as complete
  1679. // if we find the range to include or pass the 'last'
  1680. index := sort.Search(len(res.hashes[i]), func(k int) bool {
  1681. cmp := res.hashes[i][k].Big().Cmp(last)
  1682. if cmp >= 0 {
  1683. res.cont = false
  1684. }
  1685. return cmp > 0
  1686. })
  1687. if index >= 0 {
  1688. // cut off excess
  1689. res.hashes[i] = res.hashes[i][:index]
  1690. res.slots[i] = res.slots[i][:index]
  1691. }
  1692. // Forward the relevant storage chunk (even if created just now)
  1693. if res.cont {
  1694. res.subTask.Next = incHash(res.hashes[i][len(res.hashes[i])-1])
  1695. } else {
  1696. res.subTask.done = true
  1697. }
  1698. }
  1699. }
  1700. // Iterate over all the reconstructed trie nodes and push them to disk
  1701. // if the contract is fully delivered. If it's chunked, the trie nodes
  1702. // will be reconstructed later.
  1703. slots += len(res.hashes[i])
  1704. if i < len(res.hashes)-1 || res.subTask == nil {
  1705. it := res.nodes[i].NewIterator(nil, nil)
  1706. for it.Next() {
  1707. batch.Put(it.Key(), it.Value())
  1708. bytes += common.StorageSize(common.HashLength + len(it.Value()))
  1709. nodes++
  1710. }
  1711. it.Release()
  1712. }
  1713. // Persist the received storage segements. These flat state maybe
  1714. // outdated during the sync, but it can be fixed later during the
  1715. // snapshot generation.
  1716. for j := 0; j < len(res.hashes[i]); j++ {
  1717. rawdb.WriteStorageSnapshot(batch, account, res.hashes[i][j], res.slots[i][j])
  1718. bytes += common.StorageSize(1 + 2*common.HashLength + len(res.slots[i][j]))
  1719. // If we're storing large contracts, generate the trie nodes
  1720. // on the fly to not trash the gluing points
  1721. if i == len(res.hashes)-1 && res.subTask != nil {
  1722. res.subTask.genTrie.Update(res.hashes[i][j][:], res.slots[i][j])
  1723. }
  1724. }
  1725. }
  1726. // Large contracts could have generated new trie nodes, flush them to disk
  1727. if res.subTask != nil {
  1728. if res.subTask.done {
  1729. if root, err := res.subTask.genTrie.Commit(); err != nil {
  1730. log.Error("Failed to commit stack slots", "err", err)
  1731. } else if root == res.subTask.root {
  1732. // If the chunk's root is an overflown but full delivery, clear the heal request
  1733. for i, account := range res.mainTask.res.hashes {
  1734. if account == res.accounts[len(res.accounts)-1] {
  1735. res.mainTask.needHeal[i] = false
  1736. }
  1737. }
  1738. }
  1739. }
  1740. if data := res.subTask.genBatch.ValueSize(); data > ethdb.IdealBatchSize || res.subTask.done {
  1741. keys := res.subTask.genBatch.KeyCount()
  1742. if err := res.subTask.genBatch.Write(); err != nil {
  1743. log.Error("Failed to persist stack slots", "err", err)
  1744. }
  1745. res.subTask.genBatch.Reset()
  1746. bytes += common.StorageSize(keys*common.HashLength + data)
  1747. nodes += keys
  1748. }
  1749. }
  1750. // Flush anything written just now and update the stats
  1751. if err := batch.Write(); err != nil {
  1752. log.Crit("Failed to persist storage slots", "err", err)
  1753. }
  1754. s.storageSynced += uint64(slots)
  1755. s.storageBytes += bytes
  1756. log.Debug("Persisted set of storage slots", "accounts", len(res.hashes), "slots", slots, "nodes", nodes, "bytes", bytes)
  1757. // If this delivery completed the last pending task, forward the account task
  1758. // to the next chunk
  1759. if res.mainTask.pend == 0 {
  1760. s.forwardAccountTask(res.mainTask)
  1761. return
  1762. }
  1763. // Some accounts are still incomplete, leave as is for the storage and contract
  1764. // task assigners to pick up and fill.
  1765. }
  1766. // processTrienodeHealResponse integrates an already validated trienode response
  1767. // into the healer tasks.
  1768. func (s *Syncer) processTrienodeHealResponse(res *trienodeHealResponse) {
  1769. for i, hash := range res.hashes {
  1770. node := res.nodes[i]
  1771. // If the trie node was not delivered, reschedule it
  1772. if node == nil {
  1773. res.task.trieTasks[hash] = res.paths[i]
  1774. continue
  1775. }
  1776. // Push the trie node into the state syncer
  1777. s.trienodeHealSynced++
  1778. s.trienodeHealBytes += common.StorageSize(len(node))
  1779. err := s.healer.scheduler.Process(trie.SyncResult{Hash: hash, Data: node})
  1780. switch err {
  1781. case nil:
  1782. case trie.ErrAlreadyProcessed:
  1783. s.trienodeHealDups++
  1784. case trie.ErrNotRequested:
  1785. s.trienodeHealNops++
  1786. default:
  1787. log.Error("Invalid trienode processed", "hash", hash, "err", err)
  1788. }
  1789. }
  1790. batch := s.db.NewBatch()
  1791. if err := s.healer.scheduler.Commit(batch); err != nil {
  1792. log.Error("Failed to commit healing data", "err", err)
  1793. }
  1794. if err := batch.Write(); err != nil {
  1795. log.Crit("Failed to persist healing data", "err", err)
  1796. }
  1797. log.Debug("Persisted set of healing data", "type", "trienodes", "bytes", common.StorageSize(batch.ValueSize()))
  1798. }
  1799. // processBytecodeHealResponse integrates an already validated bytecode response
  1800. // into the healer tasks.
  1801. func (s *Syncer) processBytecodeHealResponse(res *bytecodeHealResponse) {
  1802. for i, hash := range res.hashes {
  1803. node := res.codes[i]
  1804. // If the trie node was not delivered, reschedule it
  1805. if node == nil {
  1806. res.task.codeTasks[hash] = struct{}{}
  1807. continue
  1808. }
  1809. // Push the trie node into the state syncer
  1810. s.bytecodeHealSynced++
  1811. s.bytecodeHealBytes += common.StorageSize(len(node))
  1812. err := s.healer.scheduler.Process(trie.SyncResult{Hash: hash, Data: node})
  1813. switch err {
  1814. case nil:
  1815. case trie.ErrAlreadyProcessed:
  1816. s.bytecodeHealDups++
  1817. case trie.ErrNotRequested:
  1818. s.bytecodeHealNops++
  1819. default:
  1820. log.Error("Invalid bytecode processed", "hash", hash, "err", err)
  1821. }
  1822. }
  1823. batch := s.db.NewBatch()
  1824. if err := s.healer.scheduler.Commit(batch); err != nil {
  1825. log.Error("Failed to commit healing data", "err", err)
  1826. }
  1827. if err := batch.Write(); err != nil {
  1828. log.Crit("Failed to persist healing data", "err", err)
  1829. }
  1830. log.Debug("Persisted set of healing data", "type", "bytecode", "bytes", common.StorageSize(batch.ValueSize()))
  1831. }
  1832. // forwardAccountTask takes a filled account task and persists anything available
  1833. // into the database, after which it forwards the next account marker so that the
  1834. // task's next chunk may be filled.
  1835. func (s *Syncer) forwardAccountTask(task *accountTask) {
  1836. // Remove any pending delivery
  1837. res := task.res
  1838. if res == nil {
  1839. return // nothing to forward
  1840. }
  1841. task.res = nil
  1842. // Persist the received account segements. These flat state maybe
  1843. // outdated during the sync, but it can be fixed later during the
  1844. // snapshot generation.
  1845. var (
  1846. nodes int
  1847. bytes common.StorageSize
  1848. )
  1849. batch := s.db.NewBatch()
  1850. for i, hash := range res.hashes {
  1851. if task.needCode[i] || task.needState[i] {
  1852. break
  1853. }
  1854. slim := snapshot.SlimAccountRLP(res.accounts[i].Nonce, res.accounts[i].Balance, res.accounts[i].Root, res.accounts[i].CodeHash)
  1855. rawdb.WriteAccountSnapshot(batch, hash, slim)
  1856. bytes += common.StorageSize(1 + common.HashLength + len(slim))
  1857. // If the task is complete, drop it into the stack trie to generate
  1858. // account trie nodes for it
  1859. if !task.needHeal[i] {
  1860. full, err := snapshot.FullAccountRLP(slim) // TODO(karalabe): Slim parsing can be omitted
  1861. if err != nil {
  1862. panic(err) // Really shouldn't ever happen
  1863. }
  1864. task.genTrie.Update(hash[:], full)
  1865. }
  1866. }
  1867. // Flush anything written just now and update the stats
  1868. if err := batch.Write(); err != nil {
  1869. log.Crit("Failed to persist accounts", "err", err)
  1870. }
  1871. s.accountBytes += bytes
  1872. s.accountSynced += uint64(len(res.accounts))
  1873. // Task filling persisted, push it the chunk marker forward to the first
  1874. // account still missing data.
  1875. for i, hash := range res.hashes {
  1876. if task.needCode[i] || task.needState[i] {
  1877. return
  1878. }
  1879. task.Next = incHash(hash)
  1880. }
  1881. // All accounts marked as complete, track if the entire task is done
  1882. task.done = !res.cont
  1883. // Stack trie could have generated trie nodes, push them to disk (we need to
  1884. // flush after finalizing task.done. It's fine even if we crash and lose this
  1885. // write as it will only cause more data to be downloaded during heal.
  1886. if task.done {
  1887. if _, err := task.genTrie.Commit(); err != nil {
  1888. log.Error("Failed to commit stack account", "err", err)
  1889. }
  1890. }
  1891. if data := task.genBatch.ValueSize(); data > ethdb.IdealBatchSize || task.done {
  1892. keys := task.genBatch.KeyCount()
  1893. if err := task.genBatch.Write(); err != nil {
  1894. log.Error("Failed to persist stack account", "err", err)
  1895. }
  1896. task.genBatch.Reset()
  1897. nodes += keys
  1898. bytes += common.StorageSize(keys*common.HashLength + data)
  1899. }
  1900. log.Debug("Persisted range of accounts", "accounts", len(res.accounts), "nodes", nodes, "bytes", bytes)
  1901. }
  1902. // OnAccounts is a callback method to invoke when a range of accounts are
  1903. // received from a remote peer.
  1904. func (s *Syncer) OnAccounts(peer SyncPeer, id uint64, hashes []common.Hash, accounts [][]byte, proof [][]byte) error {
  1905. size := common.StorageSize(len(hashes) * common.HashLength)
  1906. for _, account := range accounts {
  1907. size += common.StorageSize(len(account))
  1908. }
  1909. for _, node := range proof {
  1910. size += common.StorageSize(len(node))
  1911. }
  1912. logger := peer.Log().New("reqid", id)
  1913. logger.Trace("Delivering range of accounts", "hashes", len(hashes), "accounts", len(accounts), "proofs", len(proof), "bytes", size)
  1914. // Whether or not the response is valid, we can mark the peer as idle and
  1915. // notify the scheduler to assign a new task. If the response is invalid,
  1916. // we'll drop the peer in a bit.
  1917. s.lock.Lock()
  1918. if _, ok := s.peers[peer.ID()]; ok {
  1919. s.accountIdlers[peer.ID()] = struct{}{}
  1920. }
  1921. select {
  1922. case s.update <- struct{}{}:
  1923. default:
  1924. }
  1925. // Ensure the response is for a valid request
  1926. req, ok := s.accountReqs[id]
  1927. if !ok {
  1928. // Request stale, perhaps the peer timed out but came through in the end
  1929. logger.Warn("Unexpected account range packet")
  1930. s.lock.Unlock()
  1931. return nil
  1932. }
  1933. delete(s.accountReqs, id)
  1934. // Clean up the request timeout timer, we'll see how to proceed further based
  1935. // on the actual delivered content
  1936. if !req.timeout.Stop() {
  1937. // The timeout is already triggered, and this request will be reverted+rescheduled
  1938. s.lock.Unlock()
  1939. return nil
  1940. }
  1941. // Response is valid, but check if peer is signalling that it does not have
  1942. // the requested data. For account range queries that means the state being
  1943. // retrieved was either already pruned remotely, or the peer is not yet
  1944. // synced to our head.
  1945. if len(hashes) == 0 && len(accounts) == 0 && len(proof) == 0 {
  1946. logger.Debug("Peer rejected account range request", "root", s.root)
  1947. s.statelessPeers[peer.ID()] = struct{}{}
  1948. s.lock.Unlock()
  1949. // Signal this request as failed, and ready for rescheduling
  1950. s.scheduleRevertAccountRequest(req)
  1951. return nil
  1952. }
  1953. root := s.root
  1954. s.lock.Unlock()
  1955. // Reconstruct a partial trie from the response and verify it
  1956. keys := make([][]byte, len(hashes))
  1957. for i, key := range hashes {
  1958. keys[i] = common.CopyBytes(key[:])
  1959. }
  1960. nodes := make(light.NodeList, len(proof))
  1961. for i, node := range proof {
  1962. nodes[i] = node
  1963. }
  1964. proofdb := nodes.NodeSet()
  1965. var end []byte
  1966. if len(keys) > 0 {
  1967. end = keys[len(keys)-1]
  1968. }
  1969. _, cont, err := trie.VerifyRangeProof(root, req.origin[:], end, keys, accounts, proofdb)
  1970. if err != nil {
  1971. logger.Warn("Account range failed proof", "err", err)
  1972. // Signal this request as failed, and ready for rescheduling
  1973. s.scheduleRevertAccountRequest(req)
  1974. return err
  1975. }
  1976. accs := make([]*state.Account, len(accounts))
  1977. for i, account := range accounts {
  1978. acc := new(state.Account)
  1979. if err := rlp.DecodeBytes(account, acc); err != nil {
  1980. panic(err) // We created these blobs, we must be able to decode them
  1981. }
  1982. accs[i] = acc
  1983. }
  1984. response := &accountResponse{
  1985. task: req.task,
  1986. hashes: hashes,
  1987. accounts: accs,
  1988. cont: cont,
  1989. }
  1990. select {
  1991. case req.deliver <- response:
  1992. case <-req.cancel:
  1993. case <-req.stale:
  1994. }
  1995. return nil
  1996. }
  1997. // OnByteCodes is a callback method to invoke when a batch of contract
  1998. // bytes codes are received from a remote peer.
  1999. func (s *Syncer) OnByteCodes(peer SyncPeer, id uint64, bytecodes [][]byte) error {
  2000. s.lock.RLock()
  2001. syncing := !s.snapped
  2002. s.lock.RUnlock()
  2003. if syncing {
  2004. return s.onByteCodes(peer, id, bytecodes)
  2005. }
  2006. return s.onHealByteCodes(peer, id, bytecodes)
  2007. }
  2008. // onByteCodes is a callback method to invoke when a batch of contract
  2009. // bytes codes are received from a remote peer in the syncing phase.
  2010. func (s *Syncer) onByteCodes(peer SyncPeer, id uint64, bytecodes [][]byte) error {
  2011. var size common.StorageSize
  2012. for _, code := range bytecodes {
  2013. size += common.StorageSize(len(code))
  2014. }
  2015. logger := peer.Log().New("reqid", id)
  2016. logger.Trace("Delivering set of bytecodes", "bytecodes", len(bytecodes), "bytes", size)
  2017. // Whether or not the response is valid, we can mark the peer as idle and
  2018. // notify the scheduler to assign a new task. If the response is invalid,
  2019. // we'll drop the peer in a bit.
  2020. s.lock.Lock()
  2021. if _, ok := s.peers[peer.ID()]; ok {
  2022. s.bytecodeIdlers[peer.ID()] = struct{}{}
  2023. }
  2024. select {
  2025. case s.update <- struct{}{}:
  2026. default:
  2027. }
  2028. // Ensure the response is for a valid request
  2029. req, ok := s.bytecodeReqs[id]
  2030. if !ok {
  2031. // Request stale, perhaps the peer timed out but came through in the end
  2032. logger.Warn("Unexpected bytecode packet")
  2033. s.lock.Unlock()
  2034. return nil
  2035. }
  2036. delete(s.bytecodeReqs, id)
  2037. // Clean up the request timeout timer, we'll see how to proceed further based
  2038. // on the actual delivered content
  2039. if !req.timeout.Stop() {
  2040. // The timeout is already triggered, and this request will be reverted+rescheduled
  2041. s.lock.Unlock()
  2042. return nil
  2043. }
  2044. // Response is valid, but check if peer is signalling that it does not have
  2045. // the requested data. For bytecode range queries that means the peer is not
  2046. // yet synced.
  2047. if len(bytecodes) == 0 {
  2048. logger.Debug("Peer rejected bytecode request")
  2049. s.statelessPeers[peer.ID()] = struct{}{}
  2050. s.lock.Unlock()
  2051. // Signal this request as failed, and ready for rescheduling
  2052. s.scheduleRevertBytecodeRequest(req)
  2053. return nil
  2054. }
  2055. s.lock.Unlock()
  2056. // Cross reference the requested bytecodes with the response to find gaps
  2057. // that the serving node is missing
  2058. hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState)
  2059. hash := make([]byte, 32)
  2060. codes := make([][]byte, len(req.hashes))
  2061. for i, j := 0, 0; i < len(bytecodes); i++ {
  2062. // Find the next hash that we've been served, leaving misses with nils
  2063. hasher.Reset()
  2064. hasher.Write(bytecodes[i])
  2065. hasher.Read(hash)
  2066. for j < len(req.hashes) && !bytes.Equal(hash, req.hashes[j][:]) {
  2067. j++
  2068. }
  2069. if j < len(req.hashes) {
  2070. codes[j] = bytecodes[i]
  2071. j++
  2072. continue
  2073. }
  2074. // We've either ran out of hashes, or got unrequested data
  2075. logger.Warn("Unexpected bytecodes", "count", len(bytecodes)-i)
  2076. // Signal this request as failed, and ready for rescheduling
  2077. s.scheduleRevertBytecodeRequest(req)
  2078. return errors.New("unexpected bytecode")
  2079. }
  2080. // Response validated, send it to the scheduler for filling
  2081. response := &bytecodeResponse{
  2082. task: req.task,
  2083. hashes: req.hashes,
  2084. codes: codes,
  2085. }
  2086. select {
  2087. case req.deliver <- response:
  2088. case <-req.cancel:
  2089. case <-req.stale:
  2090. }
  2091. return nil
  2092. }
  2093. // OnStorage is a callback method to invoke when ranges of storage slots
  2094. // are received from a remote peer.
  2095. func (s *Syncer) OnStorage(peer SyncPeer, id uint64, hashes [][]common.Hash, slots [][][]byte, proof [][]byte) error {
  2096. // Gather some trace stats to aid in debugging issues
  2097. var (
  2098. hashCount int
  2099. slotCount int
  2100. size common.StorageSize
  2101. )
  2102. for _, hashset := range hashes {
  2103. size += common.StorageSize(common.HashLength * len(hashset))
  2104. hashCount += len(hashset)
  2105. }
  2106. for _, slotset := range slots {
  2107. for _, slot := range slotset {
  2108. size += common.StorageSize(len(slot))
  2109. }
  2110. slotCount += len(slotset)
  2111. }
  2112. for _, node := range proof {
  2113. size += common.StorageSize(len(node))
  2114. }
  2115. logger := peer.Log().New("reqid", id)
  2116. logger.Trace("Delivering ranges of storage slots", "accounts", len(hashes), "hashes", hashCount, "slots", slotCount, "proofs", len(proof), "size", size)
  2117. // Whether or not the response is valid, we can mark the peer as idle and
  2118. // notify the scheduler to assign a new task. If the response is invalid,
  2119. // we'll drop the peer in a bit.
  2120. s.lock.Lock()
  2121. if _, ok := s.peers[peer.ID()]; ok {
  2122. s.storageIdlers[peer.ID()] = struct{}{}
  2123. }
  2124. select {
  2125. case s.update <- struct{}{}:
  2126. default:
  2127. }
  2128. // Ensure the response is for a valid request
  2129. req, ok := s.storageReqs[id]
  2130. if !ok {
  2131. // Request stale, perhaps the peer timed out but came through in the end
  2132. logger.Warn("Unexpected storage ranges packet")
  2133. s.lock.Unlock()
  2134. return nil
  2135. }
  2136. delete(s.storageReqs, id)
  2137. // Clean up the request timeout timer, we'll see how to proceed further based
  2138. // on the actual delivered content
  2139. if !req.timeout.Stop() {
  2140. // The timeout is already triggered, and this request will be reverted+rescheduled
  2141. s.lock.Unlock()
  2142. return nil
  2143. }
  2144. // Reject the response if the hash sets and slot sets don't match, or if the
  2145. // peer sent more data than requested.
  2146. if len(hashes) != len(slots) {
  2147. s.lock.Unlock()
  2148. s.scheduleRevertStorageRequest(req) // reschedule request
  2149. logger.Warn("Hash and slot set size mismatch", "hashset", len(hashes), "slotset", len(slots))
  2150. return errors.New("hash and slot set size mismatch")
  2151. }
  2152. if len(hashes) > len(req.accounts) {
  2153. s.lock.Unlock()
  2154. s.scheduleRevertStorageRequest(req) // reschedule request
  2155. logger.Warn("Hash set larger than requested", "hashset", len(hashes), "requested", len(req.accounts))
  2156. return errors.New("hash set larger than requested")
  2157. }
  2158. // Response is valid, but check if peer is signalling that it does not have
  2159. // the requested data. For storage range queries that means the state being
  2160. // retrieved was either already pruned remotely, or the peer is not yet
  2161. // synced to our head.
  2162. if len(hashes) == 0 {
  2163. logger.Debug("Peer rejected storage request")
  2164. s.statelessPeers[peer.ID()] = struct{}{}
  2165. s.lock.Unlock()
  2166. s.scheduleRevertStorageRequest(req) // reschedule request
  2167. return nil
  2168. }
  2169. s.lock.Unlock()
  2170. // Reconstruct the partial tries from the response and verify them
  2171. var (
  2172. dbs = make([]ethdb.KeyValueStore, len(hashes))
  2173. cont bool
  2174. )
  2175. for i := 0; i < len(hashes); i++ {
  2176. // Convert the keys and proofs into an internal format
  2177. keys := make([][]byte, len(hashes[i]))
  2178. for j, key := range hashes[i] {
  2179. keys[j] = common.CopyBytes(key[:])
  2180. }
  2181. nodes := make(light.NodeList, 0, len(proof))
  2182. if i == len(hashes)-1 {
  2183. for _, node := range proof {
  2184. nodes = append(nodes, node)
  2185. }
  2186. }
  2187. var err error
  2188. if len(nodes) == 0 {
  2189. // No proof has been attached, the response must cover the entire key
  2190. // space and hash to the origin root.
  2191. dbs[i], _, err = trie.VerifyRangeProof(req.roots[i], nil, nil, keys, slots[i], nil)
  2192. if err != nil {
  2193. s.scheduleRevertStorageRequest(req) // reschedule request
  2194. logger.Warn("Storage slots failed proof", "err", err)
  2195. return err
  2196. }
  2197. } else {
  2198. // A proof was attached, the response is only partial, check that the
  2199. // returned data is indeed part of the storage trie
  2200. proofdb := nodes.NodeSet()
  2201. var end []byte
  2202. if len(keys) > 0 {
  2203. end = keys[len(keys)-1]
  2204. }
  2205. dbs[i], cont, err = trie.VerifyRangeProof(req.roots[i], req.origin[:], end, keys, slots[i], proofdb)
  2206. if err != nil {
  2207. s.scheduleRevertStorageRequest(req) // reschedule request
  2208. logger.Warn("Storage range failed proof", "err", err)
  2209. return err
  2210. }
  2211. }
  2212. }
  2213. // Partial tries reconstructed, send them to the scheduler for storage filling
  2214. response := &storageResponse{
  2215. mainTask: req.mainTask,
  2216. subTask: req.subTask,
  2217. accounts: req.accounts,
  2218. roots: req.roots,
  2219. hashes: hashes,
  2220. slots: slots,
  2221. nodes: dbs,
  2222. cont: cont,
  2223. }
  2224. select {
  2225. case req.deliver <- response:
  2226. case <-req.cancel:
  2227. case <-req.stale:
  2228. }
  2229. return nil
  2230. }
  2231. // OnTrieNodes is a callback method to invoke when a batch of trie nodes
  2232. // are received from a remote peer.
  2233. func (s *Syncer) OnTrieNodes(peer SyncPeer, id uint64, trienodes [][]byte) error {
  2234. var size common.StorageSize
  2235. for _, node := range trienodes {
  2236. size += common.StorageSize(len(node))
  2237. }
  2238. logger := peer.Log().New("reqid", id)
  2239. logger.Trace("Delivering set of healing trienodes", "trienodes", len(trienodes), "bytes", size)
  2240. // Whether or not the response is valid, we can mark the peer as idle and
  2241. // notify the scheduler to assign a new task. If the response is invalid,
  2242. // we'll drop the peer in a bit.
  2243. s.lock.Lock()
  2244. if _, ok := s.peers[peer.ID()]; ok {
  2245. s.trienodeHealIdlers[peer.ID()] = struct{}{}
  2246. }
  2247. select {
  2248. case s.update <- struct{}{}:
  2249. default:
  2250. }
  2251. // Ensure the response is for a valid request
  2252. req, ok := s.trienodeHealReqs[id]
  2253. if !ok {
  2254. // Request stale, perhaps the peer timed out but came through in the end
  2255. logger.Warn("Unexpected trienode heal packet")
  2256. s.lock.Unlock()
  2257. return nil
  2258. }
  2259. delete(s.trienodeHealReqs, id)
  2260. // Clean up the request timeout timer, we'll see how to proceed further based
  2261. // on the actual delivered content
  2262. if !req.timeout.Stop() {
  2263. // The timeout is already triggered, and this request will be reverted+rescheduled
  2264. s.lock.Unlock()
  2265. return nil
  2266. }
  2267. // Response is valid, but check if peer is signalling that it does not have
  2268. // the requested data. For bytecode range queries that means the peer is not
  2269. // yet synced.
  2270. if len(trienodes) == 0 {
  2271. logger.Debug("Peer rejected trienode heal request")
  2272. s.statelessPeers[peer.ID()] = struct{}{}
  2273. s.lock.Unlock()
  2274. // Signal this request as failed, and ready for rescheduling
  2275. s.scheduleRevertTrienodeHealRequest(req)
  2276. return nil
  2277. }
  2278. s.lock.Unlock()
  2279. // Cross reference the requested trienodes with the response to find gaps
  2280. // that the serving node is missing
  2281. hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState)
  2282. hash := make([]byte, 32)
  2283. nodes := make([][]byte, len(req.hashes))
  2284. for i, j := 0, 0; i < len(trienodes); i++ {
  2285. // Find the next hash that we've been served, leaving misses with nils
  2286. hasher.Reset()
  2287. hasher.Write(trienodes[i])
  2288. hasher.Read(hash)
  2289. for j < len(req.hashes) && !bytes.Equal(hash, req.hashes[j][:]) {
  2290. j++
  2291. }
  2292. if j < len(req.hashes) {
  2293. nodes[j] = trienodes[i]
  2294. j++
  2295. continue
  2296. }
  2297. // We've either ran out of hashes, or got unrequested data
  2298. logger.Warn("Unexpected healing trienodes", "count", len(trienodes)-i)
  2299. // Signal this request as failed, and ready for rescheduling
  2300. s.scheduleRevertTrienodeHealRequest(req)
  2301. return errors.New("unexpected healing trienode")
  2302. }
  2303. // Response validated, send it to the scheduler for filling
  2304. response := &trienodeHealResponse{
  2305. task: req.task,
  2306. hashes: req.hashes,
  2307. paths: req.paths,
  2308. nodes: nodes,
  2309. }
  2310. select {
  2311. case req.deliver <- response:
  2312. case <-req.cancel:
  2313. case <-req.stale:
  2314. }
  2315. return nil
  2316. }
  2317. // onHealByteCodes is a callback method to invoke when a batch of contract
  2318. // bytes codes are received from a remote peer in the healing phase.
  2319. func (s *Syncer) onHealByteCodes(peer SyncPeer, id uint64, bytecodes [][]byte) error {
  2320. var size common.StorageSize
  2321. for _, code := range bytecodes {
  2322. size += common.StorageSize(len(code))
  2323. }
  2324. logger := peer.Log().New("reqid", id)
  2325. logger.Trace("Delivering set of healing bytecodes", "bytecodes", len(bytecodes), "bytes", size)
  2326. // Whether or not the response is valid, we can mark the peer as idle and
  2327. // notify the scheduler to assign a new task. If the response is invalid,
  2328. // we'll drop the peer in a bit.
  2329. s.lock.Lock()
  2330. if _, ok := s.peers[peer.ID()]; ok {
  2331. s.bytecodeHealIdlers[peer.ID()] = struct{}{}
  2332. }
  2333. select {
  2334. case s.update <- struct{}{}:
  2335. default:
  2336. }
  2337. // Ensure the response is for a valid request
  2338. req, ok := s.bytecodeHealReqs[id]
  2339. if !ok {
  2340. // Request stale, perhaps the peer timed out but came through in the end
  2341. logger.Warn("Unexpected bytecode heal packet")
  2342. s.lock.Unlock()
  2343. return nil
  2344. }
  2345. delete(s.bytecodeHealReqs, id)
  2346. // Clean up the request timeout timer, we'll see how to proceed further based
  2347. // on the actual delivered content
  2348. if !req.timeout.Stop() {
  2349. // The timeout is already triggered, and this request will be reverted+rescheduled
  2350. s.lock.Unlock()
  2351. return nil
  2352. }
  2353. // Response is valid, but check if peer is signalling that it does not have
  2354. // the requested data. For bytecode range queries that means the peer is not
  2355. // yet synced.
  2356. if len(bytecodes) == 0 {
  2357. logger.Debug("Peer rejected bytecode heal request")
  2358. s.statelessPeers[peer.ID()] = struct{}{}
  2359. s.lock.Unlock()
  2360. // Signal this request as failed, and ready for rescheduling
  2361. s.scheduleRevertBytecodeHealRequest(req)
  2362. return nil
  2363. }
  2364. s.lock.Unlock()
  2365. // Cross reference the requested bytecodes with the response to find gaps
  2366. // that the serving node is missing
  2367. hasher := sha3.NewLegacyKeccak256().(crypto.KeccakState)
  2368. hash := make([]byte, 32)
  2369. codes := make([][]byte, len(req.hashes))
  2370. for i, j := 0, 0; i < len(bytecodes); i++ {
  2371. // Find the next hash that we've been served, leaving misses with nils
  2372. hasher.Reset()
  2373. hasher.Write(bytecodes[i])
  2374. hasher.Read(hash)
  2375. for j < len(req.hashes) && !bytes.Equal(hash, req.hashes[j][:]) {
  2376. j++
  2377. }
  2378. if j < len(req.hashes) {
  2379. codes[j] = bytecodes[i]
  2380. j++
  2381. continue
  2382. }
  2383. // We've either ran out of hashes, or got unrequested data
  2384. logger.Warn("Unexpected healing bytecodes", "count", len(bytecodes)-i)
  2385. // Signal this request as failed, and ready for rescheduling
  2386. s.scheduleRevertBytecodeHealRequest(req)
  2387. return errors.New("unexpected healing bytecode")
  2388. }
  2389. // Response validated, send it to the scheduler for filling
  2390. response := &bytecodeHealResponse{
  2391. task: req.task,
  2392. hashes: req.hashes,
  2393. codes: codes,
  2394. }
  2395. select {
  2396. case req.deliver <- response:
  2397. case <-req.cancel:
  2398. case <-req.stale:
  2399. }
  2400. return nil
  2401. }
  2402. // onHealState is a callback method to invoke when a flat state(account
  2403. // or storage slot) is downloded during the healing stage. The flat states
  2404. // can be persisted blindly and can be fixed later in the generation stage.
  2405. // Note it's not concurrent safe, please handle the concurrent issue outside.
  2406. func (s *Syncer) onHealState(paths [][]byte, value []byte) error {
  2407. if len(paths) == 1 {
  2408. var account state.Account
  2409. if err := rlp.DecodeBytes(value, &account); err != nil {
  2410. return nil
  2411. }
  2412. blob := snapshot.SlimAccountRLP(account.Nonce, account.Balance, account.Root, account.CodeHash)
  2413. rawdb.WriteAccountSnapshot(s.stateWriter, common.BytesToHash(paths[0]), blob)
  2414. s.accountHealed += 1
  2415. s.accountHealedBytes += common.StorageSize(1 + common.HashLength + len(blob))
  2416. }
  2417. if len(paths) == 2 {
  2418. rawdb.WriteStorageSnapshot(s.stateWriter, common.BytesToHash(paths[0]), common.BytesToHash(paths[1]), value)
  2419. s.storageHealed += 1
  2420. s.storageHealedBytes += common.StorageSize(1 + 2*common.HashLength + len(value))
  2421. }
  2422. if s.stateWriter.ValueSize() > ethdb.IdealBatchSize {
  2423. s.stateWriter.Write() // It's fine to ignore the error here
  2424. s.stateWriter.Reset()
  2425. }
  2426. return nil
  2427. }
  2428. // hashSpace is the total size of the 256 bit hash space for accounts.
  2429. var hashSpace = new(big.Int).Exp(common.Big2, common.Big256, nil)
  2430. // report calculates various status reports and provides it to the user.
  2431. func (s *Syncer) report(force bool) {
  2432. if len(s.tasks) > 0 {
  2433. s.reportSyncProgress(force)
  2434. return
  2435. }
  2436. s.reportHealProgress(force)
  2437. }
  2438. // reportSyncProgress calculates various status reports and provides it to the user.
  2439. func (s *Syncer) reportSyncProgress(force bool) {
  2440. // Don't report all the events, just occasionally
  2441. if !force && time.Since(s.logTime) < 8*time.Second {
  2442. return
  2443. }
  2444. // Don't report anything until we have a meaningful progress
  2445. synced := s.accountBytes + s.bytecodeBytes + s.storageBytes
  2446. if synced == 0 {
  2447. return
  2448. }
  2449. accountGaps := new(big.Int)
  2450. for _, task := range s.tasks {
  2451. accountGaps.Add(accountGaps, new(big.Int).Sub(task.Last.Big(), task.Next.Big()))
  2452. }
  2453. accountFills := new(big.Int).Sub(hashSpace, accountGaps)
  2454. if accountFills.BitLen() == 0 {
  2455. return
  2456. }
  2457. s.logTime = time.Now()
  2458. estBytes := float64(new(big.Int).Div(
  2459. new(big.Int).Mul(new(big.Int).SetUint64(uint64(synced)), hashSpace),
  2460. accountFills,
  2461. ).Uint64())
  2462. elapsed := time.Since(s.startTime)
  2463. estTime := elapsed / time.Duration(synced) * time.Duration(estBytes)
  2464. // Create a mega progress report
  2465. var (
  2466. progress = fmt.Sprintf("%.2f%%", float64(synced)*100/estBytes)
  2467. accounts = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(s.accountSynced), s.accountBytes.TerminalString())
  2468. storage = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(s.storageSynced), s.storageBytes.TerminalString())
  2469. bytecode = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(s.bytecodeSynced), s.bytecodeBytes.TerminalString())
  2470. )
  2471. log.Info("State sync in progress", "synced", progress, "state", synced,
  2472. "accounts", accounts, "slots", storage, "codes", bytecode, "eta", common.PrettyDuration(estTime-elapsed))
  2473. }
  2474. // reportHealProgress calculates various status reports and provides it to the user.
  2475. func (s *Syncer) reportHealProgress(force bool) {
  2476. // Don't report all the events, just occasionally
  2477. if !force && time.Since(s.logTime) < 8*time.Second {
  2478. return
  2479. }
  2480. s.logTime = time.Now()
  2481. // Create a mega progress report
  2482. var (
  2483. trienode = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(s.trienodeHealSynced), s.trienodeHealBytes.TerminalString())
  2484. bytecode = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(s.bytecodeHealSynced), s.bytecodeHealBytes.TerminalString())
  2485. accounts = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(s.accountHealed), s.accountHealedBytes.TerminalString())
  2486. storage = fmt.Sprintf("%v@%v", log.FormatLogfmtUint64(s.storageHealed), s.storageHealedBytes.TerminalString())
  2487. )
  2488. log.Info("State heal in progress", "accounts", accounts, "slots", storage,
  2489. "codes", bytecode, "nodes", trienode, "pending", s.healer.scheduler.Pending())
  2490. }
  2491. // estimateRemainingSlots tries to determine roughly how many slots are left in
  2492. // a contract storage, based on the number of keys and the last hash. This method
  2493. // assumes that the hashes are lexicographically ordered and evenly distributed.
  2494. func estimateRemainingSlots(hashes int, last common.Hash) (uint64, error) {
  2495. if last == (common.Hash{}) {
  2496. return 0, errors.New("last hash empty")
  2497. }
  2498. space := new(big.Int).Mul(math.MaxBig256, big.NewInt(int64(hashes)))
  2499. space.Div(space, last.Big())
  2500. if !space.IsUint64() {
  2501. // Gigantic address space probably due to too few or malicious slots
  2502. return 0, errors.New("too few slots for estimation")
  2503. }
  2504. return space.Uint64() - uint64(hashes), nil
  2505. }