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