sync.go 94 KB

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