sync.go 9.3 KB

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