sync.go 9.1 KB

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