sync.go 93 KB

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