sync.go 89 KB

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