sync.go 11 KB

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