sync.go 101 KB

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