sync.go 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763
  1. // Copyright 2020 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package snap
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "math/big"
  23. "math/rand"
  24. "sort"
  25. "sync"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/math"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/state/snapshot"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/light"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/rlp"
  38. "github.com/ethereum/go-ethereum/trie"
  39. "golang.org/x/crypto/sha3"
  40. )
  41. var (
  42. // emptyRoot is the known root hash of an empty trie.
  43. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  44. // emptyCode is the known hash of the empty EVM bytecode.
  45. emptyCode = crypto.Keccak256Hash(nil)
  46. )
  47. const (
  48. // maxRequestSize is the maximum number of bytes to request from a remote peer.
  49. maxRequestSize = 128 * 1024
  50. // maxStorageSetRequestCount is the maximum number of contracts to request the
  51. // storage of in a single query. If this number is too low, we're not filling
  52. // responses fully and waste round trip times. If it's too high, we're capping
  53. // responses and waste bandwidth.
  54. maxStorageSetRequestCount = maxRequestSize / 1024
  55. // maxCodeRequestCount is the maximum number of bytecode blobs to request in a
  56. // single query. If this number is too low, we're not filling responses fully
  57. // and waste round trip times. If it's too high, we're capping responses and
  58. // waste bandwidth.
  59. //
  60. // Depoyed bytecodes are currently capped at 24KB, so the minimum request
  61. // size should be maxRequestSize / 24K. Assuming that most contracts do not
  62. // come close to that, requesting 4x should be a good approximation.
  63. maxCodeRequestCount = maxRequestSize / (24 * 1024) * 4
  64. // maxTrieRequestCount is the maximum number of trie node blobs to request in
  65. // a single query. If this number is too low, we're not filling responses fully
  66. // and waste round trip times. If it's too high, we're capping responses and
  67. // waste bandwidth.
  68. maxTrieRequestCount = 256
  69. )
  70. var (
  71. // accountConcurrency is the number of chunks to split the account trie into
  72. // to allow concurrent retrievals.
  73. accountConcurrency = 16
  74. // storageConcurrency is the number of chunks to split the a large contract
  75. // storage trie into to allow concurrent retrievals.
  76. storageConcurrency = 16
  77. // requestTimeout is the maximum time a peer is allowed to spend on serving
  78. // a single network request.
  79. requestTimeout = 15 * time.Second // TODO(karalabe): Make it dynamic ala fast-sync?
  80. )
  81. // ErrCancelled is returned from snap syncing if the operation was prematurely
  82. // terminated.
  83. var ErrCancelled = errors.New("sync cancelled")
  84. // accountRequest tracks a pending account range request to ensure responses are
  85. // to actual requests and to validate any security constraints.
  86. //
  87. // Concurrency note: account requests and responses are handled concurrently from
  88. // the main runloop to allow Merkle proof verifications on the peer's thread and
  89. // to drop on invalid response. The request struct must contain all the data to
  90. // construct the response without accessing runloop internals (i.e. task). That
  91. // is only included to allow the runloop to match a response to the task being
  92. // synced without having yet another set of maps.
  93. type accountRequest struct {
  94. peer string // Peer to which this request is assigned
  95. id uint64 // Request ID of this request
  96. deliver chan *accountResponse // Channel to deliver successful response on
  97. revert chan *accountRequest // Channel to deliver request failure on
  98. cancel chan struct{} // Channel to track sync cancellation
  99. timeout *time.Timer // Timer to track delivery timeout
  100. stale chan struct{} // Channel to signal the request was dropped
  101. origin common.Hash // First account requested to allow continuation checks
  102. limit common.Hash // Last account requested to allow non-overlapping chunking
  103. task *accountTask // Task which this request is filling (only access fields through the runloop!!)
  104. }
  105. // accountResponse is an already Merkle-verified remote response to an account
  106. // range request. It contains the subtrie for the requested account range and
  107. // the database that's going to be filled with the internal nodes on commit.
  108. type accountResponse struct {
  109. task *accountTask // Task which this request is filling
  110. hashes []common.Hash // Account hashes in the returned range
  111. accounts []*state.Account // Expanded accounts in the returned range
  112. cont bool // Whether the account range has a continuation
  113. }
  114. // bytecodeRequest tracks a pending bytecode request to ensure responses are to
  115. // actual requests and to validate any security constraints.
  116. //
  117. // Concurrency note: bytecode requests and responses are handled concurrently from
  118. // the main runloop to allow Keccak256 hash verifications on the peer's thread and
  119. // to drop on invalid response. The request struct must contain all the data to
  120. // construct the response without accessing runloop internals (i.e. task). That
  121. // is only included to allow the runloop to match a response to the task being
  122. // synced without having yet another set of maps.
  123. type bytecodeRequest struct {
  124. peer string // Peer to which this request is assigned
  125. id uint64 // Request ID of this request
  126. deliver chan *bytecodeResponse // Channel to deliver successful response on
  127. revert chan *bytecodeRequest // Channel to deliver request failure on
  128. cancel chan struct{} // Channel to track sync cancellation
  129. timeout *time.Timer // Timer to track delivery timeout
  130. stale chan struct{} // Channel to signal the request was dropped
  131. hashes []common.Hash // Bytecode hashes to validate responses
  132. task *accountTask // Task which this request is filling (only access fields through the runloop!!)
  133. }
  134. // bytecodeResponse is an already verified remote response to a bytecode request.
  135. type bytecodeResponse struct {
  136. task *accountTask // Task which this request is filling
  137. hashes []common.Hash // Hashes of the bytecode to avoid double hashing
  138. codes [][]byte // Actual bytecodes to store into the database (nil = missing)
  139. }
  140. // storageRequest tracks a pending storage ranges request to ensure responses are
  141. // to actual requests and to validate any security constraints.
  142. //
  143. // Concurrency note: storage requests and responses are handled concurrently from
  144. // the main runloop to allow Merkel proof verifications on the peer's thread and
  145. // to drop on invalid response. The request struct must contain all the data to
  146. // construct the response without accessing runloop internals (i.e. tasks). That
  147. // is only included to allow the runloop to match a response to the task being
  148. // synced without having yet another set of maps.
  149. type storageRequest struct {
  150. peer string // Peer to which this request is assigned
  151. id uint64 // Request ID of this request
  152. deliver chan *storageResponse // Channel to deliver successful response on
  153. revert chan *storageRequest // Channel to deliver request failure on
  154. cancel chan struct{} // Channel to track sync cancellation
  155. timeout *time.Timer // Timer to track delivery timeout
  156. stale chan struct{} // Channel to signal the request was dropped
  157. accounts []common.Hash // Account hashes to validate responses
  158. roots []common.Hash // Storage roots to validate responses
  159. origin common.Hash // First storage slot requested to allow continuation checks
  160. limit common.Hash // Last storage slot requested to allow non-overlapping chunking
  161. mainTask *accountTask // Task which this response belongs to (only access fields through the runloop!!)
  162. subTask *storageTask // Task which this response is filling (only access fields through the runloop!!)
  163. }
  164. // storageResponse is an already Merkle-verified remote response to a storage
  165. // range request. It contains the subtries for the requested storage ranges and
  166. // the databases that's going to be filled with the internal nodes on commit.
  167. type storageResponse struct {
  168. mainTask *accountTask // Task which this response belongs to
  169. subTask *storageTask // Task which this response is filling
  170. accounts []common.Hash // Account hashes requested, may be only partially filled
  171. roots []common.Hash // Storage roots requested, may be only partially filled
  172. hashes [][]common.Hash // Storage slot hashes in the returned range
  173. slots [][][]byte // Storage slot values in the returned range
  174. cont bool // Whether the last storage range has a continuation
  175. }
  176. // trienodeHealRequest tracks a pending state trie request to ensure responses
  177. // are to actual requests and to validate any security constraints.
  178. //
  179. // Concurrency note: trie node requests and responses are handled concurrently from
  180. // the main runloop to allow Keccak256 hash verifications on the peer's thread and
  181. // to drop on invalid response. The request struct must contain all the data to
  182. // construct the response without accessing runloop internals (i.e. task). That
  183. // is only included to allow the runloop to match a response to the task being
  184. // synced without having yet another set of maps.
  185. type trienodeHealRequest struct {
  186. peer string // Peer to which this request is assigned
  187. id uint64 // Request ID of this request
  188. deliver chan *trienodeHealResponse // Channel to deliver successful response on
  189. revert chan *trienodeHealRequest // Channel to deliver request failure on
  190. cancel chan struct{} // Channel to track sync cancellation
  191. timeout *time.Timer // Timer to track delivery timeout
  192. stale chan struct{} // Channel to signal the request was dropped
  193. hashes []common.Hash // Trie node hashes to validate responses
  194. paths []trie.SyncPath // Trie node paths requested for rescheduling
  195. task *healTask // Task which this request is filling (only access fields through the runloop!!)
  196. }
  197. // trienodeHealResponse is an already verified remote response to a trie node request.
  198. type trienodeHealResponse struct {
  199. task *healTask // Task which this request is filling
  200. hashes []common.Hash // Hashes of the trie nodes to avoid double hashing
  201. paths []trie.SyncPath // Trie node paths requested for rescheduling missing ones
  202. nodes [][]byte // Actual trie nodes to store into the database (nil = missing)
  203. }
  204. // bytecodeHealRequest tracks a pending bytecode request to ensure responses are to
  205. // actual requests and to validate any security constraints.
  206. //
  207. // Concurrency note: bytecode requests and responses are handled concurrently from
  208. // the main runloop to allow Keccak256 hash verifications on the peer's thread and
  209. // to drop on invalid response. The request struct must contain all the data to
  210. // construct the response without accessing runloop internals (i.e. task). That
  211. // is only included to allow the runloop to match a response to the task being
  212. // synced without having yet another set of maps.
  213. type bytecodeHealRequest struct {
  214. peer string // Peer to which this request is assigned
  215. id uint64 // Request ID of this request
  216. deliver chan *bytecodeHealResponse // Channel to deliver successful response on
  217. revert chan *bytecodeHealRequest // Channel to deliver request failure on
  218. cancel chan struct{} // Channel to track sync cancellation
  219. timeout *time.Timer // Timer to track delivery timeout
  220. stale chan struct{} // Channel to signal the request was dropped
  221. hashes []common.Hash // Bytecode hashes to validate responses
  222. task *healTask // Task which this request is filling (only access fields through the runloop!!)
  223. }
  224. // bytecodeHealResponse is an already verified remote response to a bytecode request.
  225. type bytecodeHealResponse struct {
  226. task *healTask // Task which this request is filling
  227. hashes []common.Hash // Hashes of the bytecode to avoid double hashing
  228. codes [][]byte // Actual bytecodes to store into the database (nil = missing)
  229. }
  230. // accountTask represents the sync task for a chunk of the account snapshot.
  231. type accountTask struct {
  232. // These fields get serialized to leveldb on shutdown
  233. Next common.Hash // Next account to sync in this interval
  234. Last common.Hash // Last account to sync in this interval
  235. SubTasks map[common.Hash][]*storageTask // Storage intervals needing fetching for large contracts
  236. // These fields are internals used during runtime
  237. req *accountRequest // Pending request to fill this task
  238. res *accountResponse // Validate response filling this task
  239. pend int // Number of pending subtasks for this round
  240. needCode []bool // Flags whether the filling accounts need code retrieval
  241. needState []bool // Flags whether the filling accounts need storage retrieval
  242. needHeal []bool // Flags whether the filling accounts's state was chunked and need healing
  243. codeTasks map[common.Hash]struct{} // Code hashes that need retrieval
  244. stateTasks map[common.Hash]common.Hash // Account hashes->roots that need full state retrieval
  245. genBatch ethdb.Batch // Batch used by the node generator
  246. genTrie *trie.StackTrie // Node generator from storage slots
  247. done bool // Flag whether the task can be removed
  248. }
  249. // storageTask represents the sync task for a chunk of the storage snapshot.
  250. type storageTask struct {
  251. Next common.Hash // Next account to sync in this interval
  252. Last common.Hash // Last account to sync in this interval
  253. // These fields are internals used during runtime
  254. root common.Hash // Storage root hash for this instance
  255. req *storageRequest // Pending request to fill this task
  256. genBatch ethdb.Batch // Batch used by the node generator
  257. genTrie *trie.StackTrie // Node generator from storage slots
  258. done bool // Flag whether the task can be removed
  259. }
  260. // healTask represents the sync task for healing the snap-synced chunk boundaries.
  261. type healTask struct {
  262. scheduler *trie.Sync // State trie sync scheduler defining the tasks
  263. trieTasks map[common.Hash]trie.SyncPath // Set of trie node tasks currently queued for retrieval
  264. codeTasks map[common.Hash]struct{} // Set of byte code tasks currently queued for retrieval
  265. }
  266. // syncProgress is a database entry to allow suspending and resuming a snapshot state
  267. // sync. Opposed to full and fast sync, there is no way to restart a suspended
  268. // snap sync without prior knowledge of the suspension point.
  269. type syncProgress struct {
  270. Tasks []*accountTask // The suspended account tasks (contract tasks within)
  271. // Status report during syncing phase
  272. AccountSynced uint64 // Number of accounts downloaded
  273. AccountBytes common.StorageSize // Number of account trie bytes persisted to disk
  274. BytecodeSynced uint64 // Number of bytecodes downloaded
  275. BytecodeBytes common.StorageSize // Number of bytecode bytes downloaded
  276. StorageSynced uint64 // Number of storage slots downloaded
  277. StorageBytes common.StorageSize // Number of storage trie bytes persisted to disk
  278. // Status report during healing phase
  279. TrienodeHealSynced uint64 // Number of state trie nodes downloaded
  280. TrienodeHealBytes common.StorageSize // Number of state trie bytes persisted to disk
  281. TrienodeHealDups uint64 // Number of state trie nodes already processed
  282. TrienodeHealNops uint64 // Number of state trie nodes not requested
  283. BytecodeHealSynced uint64 // Number of bytecodes downloaded
  284. BytecodeHealBytes common.StorageSize // Number of bytecodes persisted to disk
  285. BytecodeHealDups uint64 // Number of bytecodes already processed
  286. BytecodeHealNops uint64 // Number of bytecodes not requested
  287. }
  288. // SyncPeer abstracts out the methods required for a peer to be synced against
  289. // with the goal of allowing the construction of mock peers without the full
  290. // blown networking.
  291. type SyncPeer interface {
  292. // ID retrieves the peer's unique identifier.
  293. ID() string
  294. // RequestAccountRange fetches a batch of accounts rooted in a specific account
  295. // trie, starting with the origin.
  296. RequestAccountRange(id uint64, root, origin, limit common.Hash, bytes uint64) error
  297. // RequestStorageRanges fetches a batch of storage slots belonging to one or
  298. // more accounts. If slots from only one accout is requested, an origin marker
  299. // may also be used to retrieve from there.
  300. RequestStorageRanges(id uint64, root common.Hash, accounts []common.Hash, origin, limit []byte, bytes uint64) error
  301. // RequestByteCodes fetches a batch of bytecodes by hash.
  302. RequestByteCodes(id uint64, hashes []common.Hash, bytes uint64) error
  303. // RequestTrieNodes fetches a batch of account or storage trie nodes rooted in
  304. // a specificstate trie.
  305. RequestTrieNodes(id uint64, root common.Hash, paths []TrieNodePathSet, bytes uint64) error
  306. // Log retrieves the peer's own contextual logger.
  307. Log() log.Logger
  308. }
  309. // Syncer is an Ethereum account and storage trie syncer based on snapshots and
  310. // the snap protocol. It's purpose is to download all the accounts and storage
  311. // slots from remote peers and reassemble chunks of the state trie, on top of
  312. // which a state sync can be run to fix any gaps / overlaps.
  313. //
  314. // Every network request has a variety of failure events:
  315. // - The peer disconnects after task assignment, failing to send the request
  316. // - The peer disconnects after sending the request, before delivering on it
  317. // - The peer remains connected, but does not deliver a response in time
  318. // - The peer delivers a stale response after a previous timeout
  319. // - The peer delivers a refusal to serve the requested state
  320. type Syncer struct {
  321. db ethdb.KeyValueStore // Database to store the trie nodes into (and dedup)
  322. root common.Hash // Current state trie root being synced
  323. tasks []*accountTask // Current account task set being synced
  324. snapped bool // Flag to signal that snap phase is done
  325. healer *healTask // Current state healing task being executed
  326. update chan struct{} // Notification channel for possible sync progression
  327. peers map[string]SyncPeer // Currently active peers to download from
  328. peerJoin *event.Feed // Event feed to react to peers joining
  329. peerDrop *event.Feed // Event feed to react to peers dropping
  330. // Request tracking during syncing phase
  331. statelessPeers map[string]struct{} // Peers that failed to deliver state data
  332. accountIdlers map[string]struct{} // Peers that aren't serving account requests
  333. bytecodeIdlers map[string]struct{} // Peers that aren't serving bytecode requests
  334. storageIdlers map[string]struct{} // Peers that aren't serving storage requests
  335. accountReqs map[uint64]*accountRequest // Account requests currently running
  336. bytecodeReqs map[uint64]*bytecodeRequest // Bytecode requests currently running
  337. storageReqs map[uint64]*storageRequest // Storage requests currently running
  338. accountSynced uint64 // Number of accounts downloaded
  339. accountBytes common.StorageSize // Number of account trie bytes persisted to disk
  340. bytecodeSynced uint64 // Number of bytecodes downloaded
  341. bytecodeBytes common.StorageSize // Number of bytecode bytes downloaded
  342. storageSynced uint64 // Number of storage slots downloaded
  343. storageBytes common.StorageSize // Number of storage trie bytes persisted to disk
  344. // Request tracking during healing phase
  345. trienodeHealIdlers map[string]struct{} // Peers that aren't serving trie node requests
  346. bytecodeHealIdlers map[string]struct{} // Peers that aren't serving bytecode requests
  347. trienodeHealReqs map[uint64]*trienodeHealRequest // Trie node requests currently running
  348. bytecodeHealReqs map[uint64]*bytecodeHealRequest // Bytecode requests currently running
  349. trienodeHealSynced uint64 // Number of state trie nodes downloaded
  350. trienodeHealBytes common.StorageSize // Number of state trie bytes persisted to disk
  351. trienodeHealDups uint64 // Number of state trie nodes already processed
  352. trienodeHealNops uint64 // Number of state trie nodes not requested
  353. bytecodeHealSynced uint64 // Number of bytecodes downloaded
  354. bytecodeHealBytes common.StorageSize // Number of bytecodes persisted to disk
  355. bytecodeHealDups uint64 // Number of bytecodes already processed
  356. bytecodeHealNops uint64 // Number of bytecodes not requested
  357. stateWriter ethdb.Batch // Shared batch writer used for persisting raw states
  358. accountHealed uint64 // Number of accounts downloaded during the healing stage
  359. accountHealedBytes common.StorageSize // Number of raw account bytes persisted to disk during the healing stage
  360. storageHealed uint64 // Number of storage slots downloaded during the healing stage
  361. storageHealedBytes common.StorageSize // Number of raw storage bytes persisted to disk during the healing stage
  362. startTime time.Time // Time instance when snapshot sync started
  363. logTime time.Time // Time instance when status was last reported
  364. pend sync.WaitGroup // Tracks network request goroutines for graceful shutdown
  365. lock sync.RWMutex // Protects fields that can change outside of sync (peers, reqs, root)
  366. }
  367. // NewSyncer creates a new snapshot syncer to download the Ethereum state over the
  368. // snap protocol.
  369. func NewSyncer(db ethdb.KeyValueStore) *Syncer {
  370. return &Syncer{
  371. db: db,
  372. peers: make(map[string]SyncPeer),
  373. peerJoin: new(event.Feed),
  374. peerDrop: new(event.Feed),
  375. update: make(chan struct{}, 1),
  376. accountIdlers: make(map[string]struct{}),
  377. storageIdlers: make(map[string]struct{}),
  378. bytecodeIdlers: make(map[string]struct{}),
  379. accountReqs: make(map[uint64]*accountRequest),
  380. storageReqs: make(map[uint64]*storageRequest),
  381. bytecodeReqs: make(map[uint64]*bytecodeRequest),
  382. trienodeHealIdlers: make(map[string]struct{}),
  383. bytecodeHealIdlers: make(map[string]struct{}),
  384. trienodeHealReqs: make(map[uint64]*trienodeHealRequest),
  385. bytecodeHealReqs: make(map[uint64]*bytecodeHealRequest),
  386. stateWriter: db.NewBatch(),
  387. }
  388. }
  389. // Register injects a new data source into the syncer's peerset.
  390. func (s *Syncer) Register(peer SyncPeer) error {
  391. // Make sure the peer is not registered yet
  392. id := peer.ID()
  393. s.lock.Lock()
  394. if _, ok := s.peers[id]; ok {
  395. log.Error("Snap peer already registered", "id", id)
  396. s.lock.Unlock()
  397. return errors.New("already registered")
  398. }
  399. s.peers[id] = peer
  400. // Mark the peer as idle, even if no sync is running
  401. s.accountIdlers[id] = struct{}{}
  402. s.storageIdlers[id] = struct{}{}
  403. s.bytecodeIdlers[id] = struct{}{}
  404. s.trienodeHealIdlers[id] = struct{}{}
  405. s.bytecodeHealIdlers[id] = struct{}{}
  406. s.lock.Unlock()
  407. // Notify any active syncs that a new peer can be assigned data
  408. s.peerJoin.Send(id)
  409. return nil
  410. }
  411. // Unregister injects a new data source into the syncer's peerset.
  412. func (s *Syncer) Unregister(id string) error {
  413. // Remove all traces of the peer from the registry
  414. s.lock.Lock()
  415. if _, ok := s.peers[id]; !ok {
  416. log.Error("Snap peer not registered", "id", id)
  417. s.lock.Unlock()
  418. return errors.New("not registered")
  419. }
  420. delete(s.peers, id)
  421. // Remove status markers, even if no sync is running
  422. delete(s.statelessPeers, id)
  423. delete(s.accountIdlers, id)
  424. delete(s.storageIdlers, id)
  425. delete(s.bytecodeIdlers, id)
  426. delete(s.trienodeHealIdlers, id)
  427. delete(s.bytecodeHealIdlers, id)
  428. s.lock.Unlock()
  429. // Notify any active syncs that pending requests need to be reverted
  430. s.peerDrop.Send(id)
  431. return nil
  432. }
  433. // Sync starts (or resumes a previous) sync cycle to iterate over an state trie
  434. // with the given root and reconstruct the nodes based on the snapshot leaves.
  435. // Previously downloaded segments will not be redownloaded of fixed, rather any
  436. // errors will be healed after the leaves are fully accumulated.
  437. func (s *Syncer) Sync(root common.Hash, cancel chan struct{}) error {
  438. // Move the trie root from any previous value, revert stateless markers for
  439. // any peers and initialize the syncer if it was not yet run
  440. s.lock.Lock()
  441. s.root = root
  442. s.healer = &healTask{
  443. scheduler: state.NewStateSync(root, s.db, nil, s.onHealState),
  444. trieTasks: make(map[common.Hash]trie.SyncPath),
  445. codeTasks: make(map[common.Hash]struct{}),
  446. }
  447. s.statelessPeers = make(map[string]struct{})
  448. s.lock.Unlock()
  449. if s.startTime == (time.Time{}) {
  450. s.startTime = time.Now()
  451. }
  452. // Retrieve the previous sync status from LevelDB and abort if already synced
  453. s.loadSyncStatus()
  454. if len(s.tasks) == 0 && s.healer.scheduler.Pending() == 0 {
  455. log.Debug("Snapshot sync already completed")
  456. return nil
  457. }
  458. // If sync is still not finished, we need to ensure that any marker is wiped.
  459. // Otherwise, it may happen that requests for e.g. genesis-data is delivered
  460. // from the snapshot data, instead of from the trie
  461. snapshot.ClearSnapshotMarker(s.db)
  462. defer func() { // Persist any progress, independent of failure
  463. for _, task := range s.tasks {
  464. s.forwardAccountTask(task)
  465. }
  466. s.cleanAccountTasks()
  467. s.saveSyncStatus()
  468. }()
  469. log.Debug("Starting snapshot sync cycle", "root", root)
  470. // Flush out the last committed raw states
  471. defer func() {
  472. if s.stateWriter.ValueSize() > 0 {
  473. s.stateWriter.Write()
  474. s.stateWriter.Reset()
  475. }
  476. }()
  477. defer s.report(true)
  478. // Whether sync completed or not, disregard any future packets
  479. defer func() {
  480. log.Debug("Terminating snapshot sync cycle", "root", root)
  481. s.lock.Lock()
  482. s.accountReqs = make(map[uint64]*accountRequest)
  483. s.storageReqs = make(map[uint64]*storageRequest)
  484. s.bytecodeReqs = make(map[uint64]*bytecodeRequest)
  485. s.trienodeHealReqs = make(map[uint64]*trienodeHealRequest)
  486. s.bytecodeHealReqs = make(map[uint64]*bytecodeHealRequest)
  487. s.lock.Unlock()
  488. }()
  489. // Keep scheduling sync tasks
  490. peerJoin := make(chan string, 16)
  491. peerJoinSub := s.peerJoin.Subscribe(peerJoin)
  492. defer peerJoinSub.Unsubscribe()
  493. peerDrop := make(chan string, 16)
  494. peerDropSub := s.peerDrop.Subscribe(peerDrop)
  495. defer peerDropSub.Unsubscribe()
  496. // Create a set of unique channels for this sync cycle. We need these to be
  497. // ephemeral so a data race doesn't accidentally deliver something stale on
  498. // a persistent channel across syncs (yup, this happened)
  499. var (
  500. accountReqFails = make(chan *accountRequest)
  501. storageReqFails = make(chan *storageRequest)
  502. bytecodeReqFails = make(chan *bytecodeRequest)
  503. accountResps = make(chan *accountResponse)
  504. storageResps = make(chan *storageResponse)
  505. bytecodeResps = make(chan *bytecodeResponse)
  506. trienodeHealReqFails = make(chan *trienodeHealRequest)
  507. bytecodeHealReqFails = make(chan *bytecodeHealRequest)
  508. trienodeHealResps = make(chan *trienodeHealResponse)
  509. bytecodeHealResps = make(chan *bytecodeHealResponse)
  510. )
  511. for {
  512. // Remove all completed tasks and terminate sync if everything's done
  513. s.cleanStorageTasks()
  514. s.cleanAccountTasks()
  515. if len(s.tasks) == 0 && s.healer.scheduler.Pending() == 0 {
  516. return nil
  517. }
  518. // Assign all the data retrieval tasks to any free peers
  519. s.assignAccountTasks(accountResps, accountReqFails, cancel)
  520. s.assignBytecodeTasks(bytecodeResps, bytecodeReqFails, cancel)
  521. s.assignStorageTasks(storageResps, storageReqFails, cancel)
  522. if len(s.tasks) == 0 {
  523. // Sync phase done, run heal phase
  524. s.assignTrienodeHealTasks(trienodeHealResps, trienodeHealReqFails, cancel)
  525. s.assignBytecodeHealTasks(bytecodeHealResps, bytecodeHealReqFails, cancel)
  526. }
  527. // Wait for something to happen
  528. select {
  529. case <-s.update:
  530. // Something happened (new peer, delivery, timeout), recheck tasks
  531. case <-peerJoin:
  532. // A new peer joined, try to schedule it new tasks
  533. case id := <-peerDrop:
  534. s.revertRequests(id)
  535. case <-cancel:
  536. return ErrCancelled
  537. case req := <-accountReqFails:
  538. s.revertAccountRequest(req)
  539. case req := <-bytecodeReqFails:
  540. s.revertBytecodeRequest(req)
  541. case req := <-storageReqFails:
  542. s.revertStorageRequest(req)
  543. case req := <-trienodeHealReqFails:
  544. s.revertTrienodeHealRequest(req)
  545. case req := <-bytecodeHealReqFails:
  546. s.revertBytecodeHealRequest(req)
  547. case res := <-accountResps:
  548. s.processAccountResponse(res)
  549. case res := <-bytecodeResps:
  550. s.processBytecodeResponse(res)
  551. case res := <-storageResps:
  552. s.processStorageResponse(res)
  553. case res := <-trienodeHealResps:
  554. s.processTrienodeHealResponse(res)
  555. case res := <-bytecodeHealResps:
  556. s.processBytecodeHealResponse(res)
  557. }
  558. // Report stats if something meaningful happened
  559. s.report(false)
  560. }
  561. }
  562. // loadSyncStatus retrieves a previously aborted sync status from the database,
  563. // or generates a fresh one if none is available.
  564. func (s *Syncer) loadSyncStatus() {
  565. var progress syncProgress
  566. if status := rawdb.ReadSnapshotSyncStatus(s.db); status != nil {
  567. if err := json.Unmarshal(status, &progress); err != nil {
  568. log.Error("Failed to decode snap sync status", "err", err)
  569. } else {
  570. for _, task := range progress.Tasks {
  571. log.Debug("Scheduled account sync task", "from", task.Next, "last", task.Last)
  572. }
  573. s.tasks = progress.Tasks
  574. for _, task := range s.tasks {
  575. task.genBatch = ethdb.HookedBatch{
  576. Batch: s.db.NewBatch(),
  577. OnPut: func(key []byte, value []byte) {
  578. s.accountBytes += common.StorageSize(len(key) + len(value))
  579. },
  580. }
  581. task.genTrie = trie.NewStackTrie(task.genBatch)
  582. for _, subtasks := range task.SubTasks {
  583. for _, subtask := range subtasks {
  584. subtask.genBatch = ethdb.HookedBatch{
  585. Batch: s.db.NewBatch(),
  586. OnPut: func(key []byte, value []byte) {
  587. s.storageBytes += common.StorageSize(len(key) + len(value))
  588. },
  589. }
  590. subtask.genTrie = trie.NewStackTrie(task.genBatch)
  591. }
  592. }
  593. }
  594. s.snapped = len(s.tasks) == 0
  595. s.accountSynced = progress.AccountSynced
  596. s.accountBytes = progress.AccountBytes
  597. s.bytecodeSynced = progress.BytecodeSynced
  598. s.bytecodeBytes = progress.BytecodeBytes
  599. s.storageSynced = progress.StorageSynced
  600. s.storageBytes = progress.StorageBytes
  601. s.trienodeHealSynced = progress.TrienodeHealSynced
  602. s.trienodeHealBytes = progress.TrienodeHealBytes
  603. s.bytecodeHealSynced = progress.BytecodeHealSynced
  604. s.bytecodeHealBytes = progress.BytecodeHealBytes
  605. return
  606. }
  607. }
  608. // Either we've failed to decode the previus state, or there was none.
  609. // Start a fresh sync by chunking up the account range and scheduling
  610. // them for retrieval.
  611. s.tasks = nil
  612. s.accountSynced, s.accountBytes = 0, 0
  613. s.bytecodeSynced, s.bytecodeBytes = 0, 0
  614. s.storageSynced, s.storageBytes = 0, 0
  615. s.trienodeHealSynced, s.trienodeHealBytes = 0, 0
  616. s.bytecodeHealSynced, s.bytecodeHealBytes = 0, 0
  617. var next common.Hash
  618. step := new(big.Int).Sub(
  619. new(big.Int).Div(
  620. new(big.Int).Exp(common.Big2, common.Big256, nil),
  621. big.NewInt(int64(accountConcurrency)),
  622. ), common.Big1,
  623. )
  624. for i := 0; i < accountConcurrency; i++ {
  625. last := common.BigToHash(new(big.Int).Add(next.Big(), step))
  626. if i == accountConcurrency-1 {
  627. // Make sure we don't overflow if the step is not a proper divisor
  628. last = common.HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
  629. }
  630. batch := ethdb.HookedBatch{
  631. Batch: s.db.NewBatch(),
  632. OnPut: func(key []byte, value []byte) {
  633. s.accountBytes += common.StorageSize(len(key) + len(value))
  634. },
  635. }
  636. s.tasks = append(s.tasks, &accountTask{
  637. Next: next,
  638. Last: last,
  639. SubTasks: make(map[common.Hash][]*storageTask),
  640. genBatch: batch,
  641. genTrie: trie.NewStackTrie(batch),
  642. })
  643. log.Debug("Created account sync task", "from", next, "last", last)
  644. next = common.BigToHash(new(big.Int).Add(last.Big(), common.Big1))
  645. }
  646. }
  647. // saveSyncStatus marshals the remaining sync tasks into leveldb.
  648. func (s *Syncer) saveSyncStatus() {
  649. // Serialize any partial progress to disk before spinning down
  650. for _, task := range s.tasks {
  651. if err := task.genBatch.Write(); err != nil {
  652. log.Error("Failed to persist account slots", "err", err)
  653. }
  654. for _, subtasks := range task.SubTasks {
  655. for _, subtask := range subtasks {
  656. if err := subtask.genBatch.Write(); err != nil {
  657. log.Error("Failed to persist storage slots", "err", err)
  658. }
  659. }
  660. }
  661. }
  662. // Store the actual progress markers
  663. progress := &syncProgress{
  664. Tasks: s.tasks,
  665. AccountSynced: s.accountSynced,
  666. AccountBytes: s.accountBytes,
  667. BytecodeSynced: s.bytecodeSynced,
  668. BytecodeBytes: s.bytecodeBytes,
  669. StorageSynced: s.storageSynced,
  670. StorageBytes: s.storageBytes,
  671. TrienodeHealSynced: s.trienodeHealSynced,
  672. TrienodeHealBytes: s.trienodeHealBytes,
  673. BytecodeHealSynced: s.bytecodeHealSynced,
  674. BytecodeHealBytes: s.bytecodeHealBytes,
  675. }
  676. status, err := json.Marshal(progress)
  677. if err != nil {
  678. panic(err) // This can only fail during implementation
  679. }
  680. rawdb.WriteSnapshotSyncStatus(s.db, status)
  681. }
  682. // cleanAccountTasks removes account range retrieval tasks that have already been
  683. // completed.
  684. func (s *Syncer) cleanAccountTasks() {
  685. // If the sync was already done before, don't even bother
  686. if len(s.tasks) == 0 {
  687. return
  688. }
  689. // Sync wasn't finished previously, check for any task that can be finalized
  690. for i := 0; i < len(s.tasks); i++ {
  691. if s.tasks[i].done {
  692. s.tasks = append(s.tasks[:i], s.tasks[i+1:]...)
  693. i--
  694. }
  695. }
  696. // If everything was just finalized just, generate the account trie and start heal
  697. if len(s.tasks) == 0 {
  698. s.lock.Lock()
  699. s.snapped = true
  700. s.lock.Unlock()
  701. // Push the final sync report
  702. s.reportSyncProgress(true)
  703. }
  704. }
  705. // cleanStorageTasks iterates over all the account tasks and storage sub-tasks
  706. // within, cleaning any that have been completed.
  707. func (s *Syncer) cleanStorageTasks() {
  708. for _, task := range s.tasks {
  709. for account, subtasks := range task.SubTasks {
  710. // Remove storage range retrieval tasks that completed
  711. for j := 0; j < len(subtasks); j++ {
  712. if subtasks[j].done {
  713. subtasks = append(subtasks[:j], subtasks[j+1:]...)
  714. j--
  715. }
  716. }
  717. if len(subtasks) > 0 {
  718. task.SubTasks[account] = subtasks
  719. continue
  720. }
  721. // If all storage chunks are done, mark the account as done too
  722. for j, hash := range task.res.hashes {
  723. if hash == account {
  724. task.needState[j] = false
  725. }
  726. }
  727. delete(task.SubTasks, account)
  728. task.pend--
  729. // If this was the last pending task, forward the account task
  730. if task.pend == 0 {
  731. s.forwardAccountTask(task)
  732. }
  733. }
  734. }
  735. }
  736. // assignAccountTasks attempts to match idle peers to pending account range
  737. // retrievals.
  738. func (s *Syncer) assignAccountTasks(success chan *accountResponse, fail chan *accountRequest, cancel chan struct{}) {
  739. s.lock.Lock()
  740. defer s.lock.Unlock()
  741. // If there are no idle peers, short circuit assignment
  742. if len(s.accountIdlers) == 0 {
  743. return
  744. }
  745. // Iterate over all the tasks and try to find a pending one
  746. for _, task := range s.tasks {
  747. // Skip any tasks already filling
  748. if task.req != nil || task.res != nil {
  749. continue
  750. }
  751. // Task pending retrieval, try to find an idle peer. If no such peer
  752. // exists, we probably assigned tasks for all (or they are stateless).
  753. // Abort the entire assignment mechanism.
  754. var idle string
  755. for id := range s.accountIdlers {
  756. // If the peer rejected a query in this sync cycle, don't bother asking
  757. // again for anything, it's either out of sync or already pruned
  758. if _, ok := s.statelessPeers[id]; ok {
  759. continue
  760. }
  761. idle = id
  762. break
  763. }
  764. if idle == "" {
  765. return
  766. }
  767. peer := s.peers[idle]
  768. // Matched a pending task to an idle peer, allocate a unique request id
  769. var reqid uint64
  770. for {
  771. reqid = uint64(rand.Int63())
  772. if reqid == 0 {
  773. continue
  774. }
  775. if _, ok := s.accountReqs[reqid]; ok {
  776. continue
  777. }
  778. break
  779. }
  780. // Generate the network query and send it to the peer
  781. req := &accountRequest{
  782. peer: idle,
  783. id: reqid,
  784. deliver: success,
  785. revert: fail,
  786. cancel: cancel,
  787. stale: make(chan struct{}),
  788. origin: task.Next,
  789. limit: task.Last,
  790. task: task,
  791. }
  792. req.timeout = time.AfterFunc(requestTimeout, func() {
  793. peer.Log().Debug("Account range request timed out", "reqid", reqid)
  794. s.scheduleRevertAccountRequest(req)
  795. })
  796. s.accountReqs[reqid] = req
  797. delete(s.accountIdlers, idle)
  798. s.pend.Add(1)
  799. go func(root common.Hash) {
  800. defer s.pend.Done()
  801. // Attempt to send the remote request and revert if it fails
  802. if err := peer.RequestAccountRange(reqid, root, req.origin, req.limit, maxRequestSize); err != nil {
  803. peer.Log().Debug("Failed to request account range", "err", err)
  804. s.scheduleRevertAccountRequest(req)
  805. }
  806. }(s.root)
  807. // Inject the request into the task to block further assignments
  808. task.req = req
  809. }
  810. }
  811. // assignBytecodeTasks attempts to match idle peers to pending code retrievals.
  812. func (s *Syncer) assignBytecodeTasks(success chan *bytecodeResponse, fail chan *bytecodeRequest, cancel chan struct{}) {
  813. s.lock.Lock()
  814. defer s.lock.Unlock()
  815. // If there are no idle peers, short circuit assignment
  816. if len(s.bytecodeIdlers) == 0 {
  817. return
  818. }
  819. // Iterate over all the tasks and try to find a pending one
  820. for _, task := range s.tasks {
  821. // Skip any tasks not in the bytecode retrieval phase
  822. if task.res == nil {
  823. continue
  824. }
  825. // Skip tasks that are already retrieving (or done with) all codes
  826. if len(task.codeTasks) == 0 {
  827. continue
  828. }
  829. // Task pending retrieval, try to find an idle peer. If no such peer
  830. // exists, we probably assigned tasks for all (or they are stateless).
  831. // Abort the entire assignment mechanism.
  832. var idle string
  833. for id := range s.bytecodeIdlers {
  834. // If the peer rejected a query in this sync cycle, don't bother asking
  835. // again for anything, it's either out of sync or already pruned
  836. if _, ok := s.statelessPeers[id]; ok {
  837. continue
  838. }
  839. idle = id
  840. break
  841. }
  842. if idle == "" {
  843. return
  844. }
  845. peer := s.peers[idle]
  846. // Matched a pending task to an idle peer, allocate a unique request id
  847. var reqid uint64
  848. for {
  849. reqid = uint64(rand.Int63())
  850. if reqid == 0 {
  851. continue
  852. }
  853. if _, ok := s.bytecodeReqs[reqid]; ok {
  854. continue
  855. }
  856. break
  857. }
  858. // Generate the network query and send it to the peer
  859. hashes := make([]common.Hash, 0, maxCodeRequestCount)
  860. for hash := range task.codeTasks {
  861. delete(task.codeTasks, hash)
  862. hashes = append(hashes, hash)
  863. if len(hashes) >= maxCodeRequestCount {
  864. break
  865. }
  866. }
  867. req := &bytecodeRequest{
  868. peer: idle,
  869. id: reqid,
  870. deliver: success,
  871. revert: fail,
  872. cancel: cancel,
  873. stale: make(chan struct{}),
  874. hashes: hashes,
  875. task: task,
  876. }
  877. req.timeout = time.AfterFunc(requestTimeout, func() {
  878. peer.Log().Debug("Bytecode request timed out", "reqid", reqid)
  879. s.scheduleRevertBytecodeRequest(req)
  880. })
  881. s.bytecodeReqs[reqid] = req
  882. delete(s.bytecodeIdlers, idle)
  883. s.pend.Add(1)
  884. go func() {
  885. defer s.pend.Done()
  886. // Attempt to send the remote request and revert if it fails
  887. if err := peer.RequestByteCodes(reqid, hashes, maxRequestSize); err != nil {
  888. log.Debug("Failed to request bytecodes", "err", err)
  889. s.scheduleRevertBytecodeRequest(req)
  890. }
  891. }()
  892. }
  893. }
  894. // assignStorageTasks attempts to match idle peers to pending storage range
  895. // retrievals.
  896. func (s *Syncer) assignStorageTasks(success chan *storageResponse, fail chan *storageRequest, cancel chan struct{}) {
  897. s.lock.Lock()
  898. defer s.lock.Unlock()
  899. // If there are no idle peers, short circuit assignment
  900. if len(s.storageIdlers) == 0 {
  901. return
  902. }
  903. // Iterate over all the tasks and try to find a pending one
  904. for _, task := range s.tasks {
  905. // Skip any tasks not in the storage retrieval phase
  906. if task.res == nil {
  907. continue
  908. }
  909. // Skip tasks that are already retrieving (or done with) all small states
  910. if len(task.SubTasks) == 0 && len(task.stateTasks) == 0 {
  911. continue
  912. }
  913. // Task pending retrieval, try to find an idle peer. If no such peer
  914. // exists, we probably assigned tasks for all (or they are stateless).
  915. // Abort the entire assignment mechanism.
  916. var idle string
  917. for id := range s.storageIdlers {
  918. // If the peer rejected a query in this sync cycle, don't bother asking
  919. // again for anything, it's either out of sync or already pruned
  920. if _, ok := s.statelessPeers[id]; ok {
  921. continue
  922. }
  923. idle = id
  924. break
  925. }
  926. if idle == "" {
  927. return
  928. }
  929. peer := s.peers[idle]
  930. // Matched a pending task to an idle peer, allocate a unique request id
  931. var reqid uint64
  932. for {
  933. reqid = uint64(rand.Int63())
  934. if reqid == 0 {
  935. continue
  936. }
  937. if _, ok := s.storageReqs[reqid]; ok {
  938. continue
  939. }
  940. break
  941. }
  942. // Generate the network query and send it to the peer. If there are
  943. // large contract tasks pending, complete those before diving into
  944. // even more new contracts.
  945. var (
  946. accounts = make([]common.Hash, 0, maxStorageSetRequestCount)
  947. roots = make([]common.Hash, 0, maxStorageSetRequestCount)
  948. subtask *storageTask
  949. )
  950. for account, subtasks := range task.SubTasks {
  951. for _, st := range subtasks {
  952. // Skip any subtasks already filling
  953. if st.req != nil {
  954. continue
  955. }
  956. // Found an incomplete storage chunk, schedule it
  957. accounts = append(accounts, account)
  958. roots = append(roots, st.root)
  959. subtask = st
  960. break // Large contract chunks are downloaded individually
  961. }
  962. if subtask != nil {
  963. break // Large contract chunks are downloaded individually
  964. }
  965. }
  966. if subtask == nil {
  967. // No large contract required retrieval, but small ones available
  968. for acccount, root := range task.stateTasks {
  969. delete(task.stateTasks, acccount)
  970. accounts = append(accounts, acccount)
  971. roots = append(roots, root)
  972. if len(accounts) >= maxStorageSetRequestCount {
  973. break
  974. }
  975. }
  976. }
  977. // If nothing was found, it means this task is actually already fully
  978. // retrieving, but large contracts are hard to detect. Skip to the next.
  979. if len(accounts) == 0 {
  980. continue
  981. }
  982. req := &storageRequest{
  983. peer: idle,
  984. id: reqid,
  985. deliver: success,
  986. revert: fail,
  987. cancel: cancel,
  988. stale: make(chan struct{}),
  989. accounts: accounts,
  990. roots: roots,
  991. mainTask: task,
  992. subTask: subtask,
  993. }
  994. if subtask != nil {
  995. req.origin = subtask.Next
  996. req.limit = subtask.Last
  997. }
  998. req.timeout = time.AfterFunc(requestTimeout, func() {
  999. peer.Log().Debug("Storage request timed out", "reqid", reqid)
  1000. s.scheduleRevertStorageRequest(req)
  1001. })
  1002. s.storageReqs[reqid] = req
  1003. delete(s.storageIdlers, idle)
  1004. s.pend.Add(1)
  1005. go func(root common.Hash) {
  1006. defer s.pend.Done()
  1007. // Attempt to send the remote request and revert if it fails
  1008. var origin, limit []byte
  1009. if subtask != nil {
  1010. origin, limit = req.origin[:], req.limit[:]
  1011. }
  1012. if err := peer.RequestStorageRanges(reqid, root, accounts, origin, limit, maxRequestSize); err != nil {
  1013. log.Debug("Failed to request storage", "err", err)
  1014. s.scheduleRevertStorageRequest(req)
  1015. }
  1016. }(s.root)
  1017. // Inject the request into the subtask to block further assignments
  1018. if subtask != nil {
  1019. subtask.req = req
  1020. }
  1021. }
  1022. }
  1023. // assignTrienodeHealTasks attempts to match idle peers to trie node requests to
  1024. // heal any trie errors caused by the snap sync's chunked retrieval model.
  1025. func (s *Syncer) assignTrienodeHealTasks(success chan *trienodeHealResponse, fail chan *trienodeHealRequest, cancel chan struct{}) {
  1026. s.lock.Lock()
  1027. defer s.lock.Unlock()
  1028. // If there are no idle peers, short circuit assignment
  1029. if len(s.trienodeHealIdlers) == 0 {
  1030. return
  1031. }
  1032. // Iterate over pending tasks and try to find a peer to retrieve with
  1033. for len(s.healer.trieTasks) > 0 || s.healer.scheduler.Pending() > 0 {
  1034. // If there are not enough trie tasks queued to fully assign, fill the
  1035. // queue from the state sync scheduler. The trie synced schedules these
  1036. // together with bytecodes, so we need to queue them combined.
  1037. var (
  1038. have = len(s.healer.trieTasks) + len(s.healer.codeTasks)
  1039. want = maxTrieRequestCount + maxCodeRequestCount
  1040. )
  1041. if have < want {
  1042. nodes, paths, codes := s.healer.scheduler.Missing(want - have)
  1043. for i, hash := range nodes {
  1044. s.healer.trieTasks[hash] = paths[i]
  1045. }
  1046. for _, hash := range codes {
  1047. s.healer.codeTasks[hash] = struct{}{}
  1048. }
  1049. }
  1050. // If all the heal tasks are bytecodes or already downloading, bail
  1051. if len(s.healer.trieTasks) == 0 {
  1052. return
  1053. }
  1054. // Task pending retrieval, try to find an idle peer. If no such peer
  1055. // exists, we probably assigned tasks for all (or they are stateless).
  1056. // Abort the entire assignment mechanism.
  1057. var idle string
  1058. for id := range s.trienodeHealIdlers {
  1059. // If the peer rejected a query in this sync cycle, don't bother asking
  1060. // again for anything, it's either out of sync or already pruned
  1061. if _, ok := s.statelessPeers[id]; ok {
  1062. continue
  1063. }
  1064. idle = id
  1065. break
  1066. }
  1067. if idle == "" {
  1068. return
  1069. }
  1070. peer := s.peers[idle]
  1071. // Matched a pending task to an idle peer, allocate a unique request id
  1072. var reqid uint64
  1073. for {
  1074. reqid = uint64(rand.Int63())
  1075. if reqid == 0 {
  1076. continue
  1077. }
  1078. if _, ok := s.trienodeHealReqs[reqid]; ok {
  1079. continue
  1080. }
  1081. break
  1082. }
  1083. // Generate the network query and send it to the peer
  1084. var (
  1085. hashes = make([]common.Hash, 0, maxTrieRequestCount)
  1086. paths = make([]trie.SyncPath, 0, maxTrieRequestCount)
  1087. pathsets = make([]TrieNodePathSet, 0, maxTrieRequestCount)
  1088. )
  1089. for hash, pathset := range s.healer.trieTasks {
  1090. delete(s.healer.trieTasks, hash)
  1091. hashes = append(hashes, hash)
  1092. paths = append(paths, pathset)
  1093. pathsets = append(pathsets, [][]byte(pathset)) // TODO(karalabe): group requests by account hash
  1094. if len(hashes) >= maxTrieRequestCount {
  1095. break
  1096. }
  1097. }
  1098. req := &trienodeHealRequest{
  1099. peer: idle,
  1100. id: reqid,
  1101. deliver: success,
  1102. revert: fail,
  1103. cancel: cancel,
  1104. stale: make(chan struct{}),
  1105. hashes: hashes,
  1106. paths: paths,
  1107. task: s.healer,
  1108. }
  1109. req.timeout = time.AfterFunc(requestTimeout, func() {
  1110. peer.Log().Debug("Trienode heal request timed out", "reqid", reqid)
  1111. s.scheduleRevertTrienodeHealRequest(req)
  1112. })
  1113. s.trienodeHealReqs[reqid] = req
  1114. delete(s.trienodeHealIdlers, idle)
  1115. s.pend.Add(1)
  1116. go func(root common.Hash) {
  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. }(s.root)
  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. go 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. }