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