sync.go 95 KB

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