sync.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright 2015 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 trie
  17. import (
  18. "errors"
  19. "fmt"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/ethdb"
  22. "gopkg.in/karalabe/cookiejar.v2/collections/prque"
  23. )
  24. // ErrNotRequested is returned by the trie sync when it's requested to process a
  25. // node it did not request.
  26. var ErrNotRequested = errors.New("not requested")
  27. // ErrAlreadyProcessed is returned by the trie sync when it's requested to process a
  28. // node it already processed previously.
  29. var ErrAlreadyProcessed = errors.New("already processed")
  30. // request represents a scheduled or already in-flight state retrieval request.
  31. type request struct {
  32. hash common.Hash // Hash of the node data content to retrieve
  33. data []byte // Data content of the node, cached until all subtrees complete
  34. raw bool // Whether this is a raw entry (code) or a trie node
  35. parents []*request // Parent state nodes referencing this entry (notify all upon completion)
  36. depth int // Depth level within the trie the node is located to prioritise DFS
  37. deps int // Number of dependencies before allowed to commit this node
  38. callback LeafCallback // Callback to invoke if a leaf node it reached on this branch
  39. }
  40. // SyncResult is a simple list to return missing nodes along with their request
  41. // hashes.
  42. type SyncResult struct {
  43. Hash common.Hash // Hash of the originally unknown trie node
  44. Data []byte // Data content of the retrieved node
  45. }
  46. // syncMemBatch is an in-memory buffer of successfully downloaded but not yet
  47. // persisted data items.
  48. type syncMemBatch struct {
  49. batch map[common.Hash][]byte // In-memory membatch of recently completed items
  50. order []common.Hash // Order of completion to prevent out-of-order data loss
  51. }
  52. // newSyncMemBatch allocates a new memory-buffer for not-yet persisted trie nodes.
  53. func newSyncMemBatch() *syncMemBatch {
  54. return &syncMemBatch{
  55. batch: make(map[common.Hash][]byte),
  56. order: make([]common.Hash, 0, 256),
  57. }
  58. }
  59. // Sync is the main state trie synchronisation scheduler, which provides yet
  60. // unknown trie hashes to retrieve, accepts node data associated with said hashes
  61. // and reconstructs the trie step by step until all is done.
  62. type Sync struct {
  63. database DatabaseReader // Persistent database to check for existing entries
  64. membatch *syncMemBatch // Memory buffer to avoid frequest database writes
  65. requests map[common.Hash]*request // Pending requests pertaining to a key hash
  66. queue *prque.Prque // Priority queue with the pending requests
  67. }
  68. // NewSync creates a new trie data download scheduler.
  69. func NewSync(root common.Hash, database DatabaseReader, callback LeafCallback) *Sync {
  70. ts := &Sync{
  71. database: database,
  72. membatch: newSyncMemBatch(),
  73. requests: make(map[common.Hash]*request),
  74. queue: prque.New(),
  75. }
  76. ts.AddSubTrie(root, 0, common.Hash{}, callback)
  77. return ts
  78. }
  79. // AddSubTrie registers a new trie to the sync code, rooted at the designated parent.
  80. func (s *Sync) AddSubTrie(root common.Hash, depth int, parent common.Hash, callback LeafCallback) {
  81. // Short circuit if the trie is empty or already known
  82. if root == emptyRoot {
  83. return
  84. }
  85. if _, ok := s.membatch.batch[root]; ok {
  86. return
  87. }
  88. key := root.Bytes()
  89. blob, _ := s.database.Get(key)
  90. if local, err := decodeNode(key, blob, 0); local != nil && err == nil {
  91. return
  92. }
  93. // Assemble the new sub-trie sync request
  94. req := &request{
  95. hash: root,
  96. depth: depth,
  97. callback: callback,
  98. }
  99. // If this sub-trie has a designated parent, link them together
  100. if parent != (common.Hash{}) {
  101. ancestor := s.requests[parent]
  102. if ancestor == nil {
  103. panic(fmt.Sprintf("sub-trie ancestor not found: %x", parent))
  104. }
  105. ancestor.deps++
  106. req.parents = append(req.parents, ancestor)
  107. }
  108. s.schedule(req)
  109. }
  110. // AddRawEntry schedules the direct retrieval of a state entry that should not be
  111. // interpreted as a trie node, but rather accepted and stored into the database
  112. // as is. This method's goal is to support misc state metadata retrievals (e.g.
  113. // contract code).
  114. func (s *Sync) AddRawEntry(hash common.Hash, depth int, parent common.Hash) {
  115. // Short circuit if the entry is empty or already known
  116. if hash == emptyState {
  117. return
  118. }
  119. if _, ok := s.membatch.batch[hash]; ok {
  120. return
  121. }
  122. if ok, _ := s.database.Has(hash.Bytes()); ok {
  123. return
  124. }
  125. // Assemble the new sub-trie sync request
  126. req := &request{
  127. hash: hash,
  128. raw: true,
  129. depth: depth,
  130. }
  131. // If this sub-trie has a designated parent, link them together
  132. if parent != (common.Hash{}) {
  133. ancestor := s.requests[parent]
  134. if ancestor == nil {
  135. panic(fmt.Sprintf("raw-entry ancestor not found: %x", parent))
  136. }
  137. ancestor.deps++
  138. req.parents = append(req.parents, ancestor)
  139. }
  140. s.schedule(req)
  141. }
  142. // Missing retrieves the known missing nodes from the trie for retrieval.
  143. func (s *Sync) Missing(max int) []common.Hash {
  144. requests := []common.Hash{}
  145. for !s.queue.Empty() && (max == 0 || len(requests) < max) {
  146. requests = append(requests, s.queue.PopItem().(common.Hash))
  147. }
  148. return requests
  149. }
  150. // Process injects a batch of retrieved trie nodes data, returning if something
  151. // was committed to the database and also the index of an entry if processing of
  152. // it failed.
  153. func (s *Sync) Process(results []SyncResult) (bool, int, error) {
  154. committed := false
  155. for i, item := range results {
  156. // If the item was not requested, bail out
  157. request := s.requests[item.Hash]
  158. if request == nil {
  159. return committed, i, ErrNotRequested
  160. }
  161. if request.data != nil {
  162. return committed, i, ErrAlreadyProcessed
  163. }
  164. // If the item is a raw entry request, commit directly
  165. if request.raw {
  166. request.data = item.Data
  167. s.commit(request)
  168. committed = true
  169. continue
  170. }
  171. // Decode the node data content and update the request
  172. node, err := decodeNode(item.Hash[:], item.Data, 0)
  173. if err != nil {
  174. return committed, i, err
  175. }
  176. request.data = item.Data
  177. // Create and schedule a request for all the children nodes
  178. requests, err := s.children(request, node)
  179. if err != nil {
  180. return committed, i, err
  181. }
  182. if len(requests) == 0 && request.deps == 0 {
  183. s.commit(request)
  184. committed = true
  185. continue
  186. }
  187. request.deps += len(requests)
  188. for _, child := range requests {
  189. s.schedule(child)
  190. }
  191. }
  192. return committed, 0, nil
  193. }
  194. // Commit flushes the data stored in the internal membatch out to persistent
  195. // storage, returning the number of items written and any occurred error.
  196. func (s *Sync) Commit(dbw ethdb.Putter) (int, error) {
  197. // Dump the membatch into a database dbw
  198. for i, key := range s.membatch.order {
  199. if err := dbw.Put(key[:], s.membatch.batch[key]); err != nil {
  200. return i, err
  201. }
  202. }
  203. written := len(s.membatch.order)
  204. // Drop the membatch data and return
  205. s.membatch = newSyncMemBatch()
  206. return written, nil
  207. }
  208. // Pending returns the number of state entries currently pending for download.
  209. func (s *Sync) Pending() int {
  210. return len(s.requests)
  211. }
  212. // schedule inserts a new state retrieval request into the fetch queue. If there
  213. // is already a pending request for this node, the new request will be discarded
  214. // and only a parent reference added to the old one.
  215. func (s *Sync) schedule(req *request) {
  216. // If we're already requesting this node, add a new reference and stop
  217. if old, ok := s.requests[req.hash]; ok {
  218. old.parents = append(old.parents, req.parents...)
  219. return
  220. }
  221. // Schedule the request for future retrieval
  222. s.queue.Push(req.hash, float32(req.depth))
  223. s.requests[req.hash] = req
  224. }
  225. // children retrieves all the missing children of a state trie entry for future
  226. // retrieval scheduling.
  227. func (s *Sync) children(req *request, object node) ([]*request, error) {
  228. // Gather all the children of the node, irrelevant whether known or not
  229. type child struct {
  230. node node
  231. depth int
  232. }
  233. children := []child{}
  234. switch node := (object).(type) {
  235. case *shortNode:
  236. children = []child{{
  237. node: node.Val,
  238. depth: req.depth + len(node.Key),
  239. }}
  240. case *fullNode:
  241. for i := 0; i < 17; i++ {
  242. if node.Children[i] != nil {
  243. children = append(children, child{
  244. node: node.Children[i],
  245. depth: req.depth + 1,
  246. })
  247. }
  248. }
  249. default:
  250. panic(fmt.Sprintf("unknown node: %+v", node))
  251. }
  252. // Iterate over the children, and request all unknown ones
  253. requests := make([]*request, 0, len(children))
  254. for _, child := range children {
  255. // Notify any external watcher of a new key/value node
  256. if req.callback != nil {
  257. if node, ok := (child.node).(valueNode); ok {
  258. if err := req.callback(node, req.hash); err != nil {
  259. return nil, err
  260. }
  261. }
  262. }
  263. // If the child references another node, resolve or schedule
  264. if node, ok := (child.node).(hashNode); ok {
  265. // Try to resolve the node from the local database
  266. hash := common.BytesToHash(node)
  267. if _, ok := s.membatch.batch[hash]; ok {
  268. continue
  269. }
  270. if ok, _ := s.database.Has(node); ok {
  271. continue
  272. }
  273. // Locally unknown node, schedule for retrieval
  274. requests = append(requests, &request{
  275. hash: hash,
  276. parents: []*request{req},
  277. depth: child.depth,
  278. callback: req.callback,
  279. })
  280. }
  281. }
  282. return requests, nil
  283. }
  284. // commit finalizes a retrieval request and stores it into the membatch. If any
  285. // of the referencing parent requests complete due to this commit, they are also
  286. // committed themselves.
  287. func (s *Sync) commit(req *request) (err error) {
  288. // Write the node content to the membatch
  289. s.membatch.batch[req.hash] = req.data
  290. s.membatch.order = append(s.membatch.order, req.hash)
  291. delete(s.requests, req.hash)
  292. // Check all parents for completion
  293. for _, parent := range req.parents {
  294. parent.deps--
  295. if parent.deps == 0 {
  296. if err := s.commit(parent); err != nil {
  297. return err
  298. }
  299. }
  300. }
  301. return nil
  302. }