github.com/theQRL/go-zond@v0.1.1/light/txpool.go (about) 1 // Copyright 2016 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 light 18 19 import ( 20 "context" 21 "fmt" 22 "math/big" 23 "sync" 24 "time" 25 26 "github.com/theQRL/go-zond/common" 27 "github.com/theQRL/go-zond/core" 28 "github.com/theQRL/go-zond/core/rawdb" 29 "github.com/theQRL/go-zond/core/state" 30 "github.com/theQRL/go-zond/core/txpool" 31 "github.com/theQRL/go-zond/core/types" 32 "github.com/theQRL/go-zond/zonddb" 33 "github.com/theQRL/go-zond/event" 34 "github.com/theQRL/go-zond/log" 35 "github.com/theQRL/go-zond/params" 36 ) 37 38 const ( 39 // chainHeadChanSize is the size of channel listening to ChainHeadEvent. 40 chainHeadChanSize = 10 41 ) 42 43 // txPermanent is the number of mined blocks after a mined transaction is 44 // considered permanent and no rollback is expected 45 var txPermanent = uint64(500) 46 47 // TxPool implements the transaction pool for light clients, which keeps track 48 // of the status of locally created transactions, detecting if they are included 49 // in a block (mined) or rolled back. There are no queued transactions since we 50 // always receive all locally signed transactions in the same order as they are 51 // created. 52 type TxPool struct { 53 config *params.ChainConfig 54 signer types.Signer 55 quit chan bool 56 txFeed event.Feed 57 scope event.SubscriptionScope 58 chainHeadCh chan core.ChainHeadEvent 59 chainHeadSub event.Subscription 60 mu sync.RWMutex 61 chain *LightChain 62 odr OdrBackend 63 chainDb zonddb.Database 64 relay TxRelayBackend 65 head common.Hash 66 nonce map[common.Address]uint64 // "pending" nonce 67 pending map[common.Hash]*types.Transaction // pending transactions by tx hash 68 mined map[common.Hash][]*types.Transaction // mined transactions by block hash 69 clearIdx uint64 // earliest block nr that can contain mined tx info 70 71 istanbul bool // Fork indicator whether we are in the istanbul stage. 72 eip2718 bool // Fork indicator whether we are in the eip2718 stage. 73 shanghai bool // Fork indicator whether we are in the shanghai stage. 74 } 75 76 // TxRelayBackend provides an interface to the mechanism that forwards transactions to the 77 // ETH network. The implementations of the functions should be non-blocking. 78 // 79 // Send instructs backend to forward new transactions NewHead notifies backend about a new 80 // head after processed by the tx pool, including mined and rolled back transactions since 81 // the last event. 82 // 83 // Discard notifies backend about transactions that should be discarded either because 84 // they have been replaced by a re-send or because they have been mined long ago and no 85 // rollback is expected. 86 type TxRelayBackend interface { 87 Send(txs types.Transactions) 88 NewHead(head common.Hash, mined []common.Hash, rollback []common.Hash) 89 Discard(hashes []common.Hash) 90 } 91 92 // NewTxPool creates a new light transaction pool 93 func NewTxPool(config *params.ChainConfig, chain *LightChain, relay TxRelayBackend) *TxPool { 94 pool := &TxPool{ 95 config: config, 96 signer: types.LatestSigner(config), 97 nonce: make(map[common.Address]uint64), 98 pending: make(map[common.Hash]*types.Transaction), 99 mined: make(map[common.Hash][]*types.Transaction), 100 quit: make(chan bool), 101 chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize), 102 chain: chain, 103 relay: relay, 104 odr: chain.Odr(), 105 chainDb: chain.Odr().Database(), 106 head: chain.CurrentHeader().Hash(), 107 clearIdx: chain.CurrentHeader().Number.Uint64(), 108 } 109 // Subscribe events from blockchain 110 pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh) 111 go pool.eventLoop() 112 113 return pool 114 } 115 116 // currentState returns the light state of the current head header 117 func (pool *TxPool) currentState(ctx context.Context) *state.StateDB { 118 return NewState(ctx, pool.chain.CurrentHeader(), pool.odr) 119 } 120 121 // GetNonce returns the "pending" nonce of a given address. It always queries 122 // the nonce belonging to the latest header too in order to detect if another 123 // client using the same key sent a transaction. 124 func (pool *TxPool) GetNonce(ctx context.Context, addr common.Address) (uint64, error) { 125 state := pool.currentState(ctx) 126 nonce := state.GetNonce(addr) 127 if state.Error() != nil { 128 return 0, state.Error() 129 } 130 sn, ok := pool.nonce[addr] 131 if ok && sn > nonce { 132 nonce = sn 133 } 134 if !ok || sn < nonce { 135 pool.nonce[addr] = nonce 136 } 137 return nonce, nil 138 } 139 140 // txStateChanges stores the recent changes between pending/mined states of 141 // transactions. True means mined, false means rolled back, no entry means no change 142 type txStateChanges map[common.Hash]bool 143 144 // setState sets the status of a tx to either recently mined or recently rolled back 145 func (txc txStateChanges) setState(txHash common.Hash, mined bool) { 146 val, ent := txc[txHash] 147 if ent && (val != mined) { 148 delete(txc, txHash) 149 } else { 150 txc[txHash] = mined 151 } 152 } 153 154 // getLists creates lists of mined and rolled back tx hashes 155 func (txc txStateChanges) getLists() (mined []common.Hash, rollback []common.Hash) { 156 for hash, val := range txc { 157 if val { 158 mined = append(mined, hash) 159 } else { 160 rollback = append(rollback, hash) 161 } 162 } 163 return 164 } 165 166 // checkMinedTxs checks newly added blocks for the currently pending transactions 167 // and marks them as mined if necessary. It also stores block position in the db 168 // and adds them to the received txStateChanges map. 169 func (pool *TxPool) checkMinedTxs(ctx context.Context, hash common.Hash, number uint64, txc txStateChanges) error { 170 // If no transactions are pending, we don't care about anything 171 if len(pool.pending) == 0 { 172 return nil 173 } 174 block, err := GetBlock(ctx, pool.odr, hash, number) 175 if err != nil { 176 return err 177 } 178 // Gather all the local transaction mined in this block 179 list := pool.mined[hash] 180 for _, tx := range block.Transactions() { 181 if _, ok := pool.pending[tx.Hash()]; ok { 182 list = append(list, tx) 183 } 184 } 185 // If some transactions have been mined, write the needed data to disk and update 186 if list != nil { 187 // Retrieve all the receipts belonging to this block and write the lookup table 188 if _, err := GetBlockReceipts(ctx, pool.odr, hash, number); err != nil { // ODR caches, ignore results 189 return err 190 } 191 rawdb.WriteTxLookupEntriesByBlock(pool.chainDb, block) 192 193 // Update the transaction pool's state 194 for _, tx := range list { 195 delete(pool.pending, tx.Hash()) 196 txc.setState(tx.Hash(), true) 197 } 198 pool.mined[hash] = list 199 } 200 return nil 201 } 202 203 // rollbackTxs marks the transactions contained in recently rolled back blocks 204 // as rolled back. It also removes any positional lookup entries. 205 func (pool *TxPool) rollbackTxs(hash common.Hash, txc txStateChanges) { 206 batch := pool.chainDb.NewBatch() 207 if list, ok := pool.mined[hash]; ok { 208 for _, tx := range list { 209 txHash := tx.Hash() 210 rawdb.DeleteTxLookupEntry(batch, txHash) 211 pool.pending[txHash] = tx 212 txc.setState(txHash, false) 213 } 214 delete(pool.mined, hash) 215 } 216 batch.Write() 217 } 218 219 // reorgOnNewHead sets a new head header, processing (and rolling back if necessary) 220 // the blocks since the last known head and returns a txStateChanges map containing 221 // the recently mined and rolled back transaction hashes. If an error (context 222 // timeout) occurs during checking new blocks, it leaves the locally known head 223 // at the latest checked block and still returns a valid txStateChanges, making it 224 // possible to continue checking the missing blocks at the next chain head event 225 func (pool *TxPool) reorgOnNewHead(ctx context.Context, newHeader *types.Header) (txStateChanges, error) { 226 txc := make(txStateChanges) 227 oldh := pool.chain.GetHeaderByHash(pool.head) 228 newh := newHeader 229 // find common ancestor, create list of rolled back and new block hashes 230 var oldHashes, newHashes []common.Hash 231 for oldh.Hash() != newh.Hash() { 232 if oldh.Number.Uint64() >= newh.Number.Uint64() { 233 oldHashes = append(oldHashes, oldh.Hash()) 234 oldh = pool.chain.GetHeader(oldh.ParentHash, oldh.Number.Uint64()-1) 235 } 236 if oldh.Number.Uint64() < newh.Number.Uint64() { 237 newHashes = append(newHashes, newh.Hash()) 238 newh = pool.chain.GetHeader(newh.ParentHash, newh.Number.Uint64()-1) 239 if newh == nil { 240 // happens when CHT syncing, nothing to do 241 newh = oldh 242 } 243 } 244 } 245 if oldh.Number.Uint64() < pool.clearIdx { 246 pool.clearIdx = oldh.Number.Uint64() 247 } 248 // roll back old blocks 249 for _, hash := range oldHashes { 250 pool.rollbackTxs(hash, txc) 251 } 252 pool.head = oldh.Hash() 253 // check mined txs of new blocks (array is in reversed order) 254 for i := len(newHashes) - 1; i >= 0; i-- { 255 hash := newHashes[i] 256 if err := pool.checkMinedTxs(ctx, hash, newHeader.Number.Uint64()-uint64(i), txc); err != nil { 257 return txc, err 258 } 259 pool.head = hash 260 } 261 262 // clear old mined tx entries of old blocks 263 if idx := newHeader.Number.Uint64(); idx > pool.clearIdx+txPermanent { 264 idx2 := idx - txPermanent 265 if len(pool.mined) > 0 { 266 for i := pool.clearIdx; i < idx2; i++ { 267 hash := rawdb.ReadCanonicalHash(pool.chainDb, i) 268 if list, ok := pool.mined[hash]; ok { 269 hashes := make([]common.Hash, len(list)) 270 for i, tx := range list { 271 hashes[i] = tx.Hash() 272 } 273 pool.relay.Discard(hashes) 274 delete(pool.mined, hash) 275 } 276 } 277 } 278 pool.clearIdx = idx2 279 } 280 281 return txc, nil 282 } 283 284 // blockCheckTimeout is the time limit for checking new blocks for mined 285 // transactions. Checking resumes at the next chain head event if timed out. 286 const blockCheckTimeout = time.Second * 3 287 288 // eventLoop processes chain head events and also notifies the tx relay backend 289 // about the new head hash and tx state changes 290 func (pool *TxPool) eventLoop() { 291 for { 292 select { 293 case ev := <-pool.chainHeadCh: 294 pool.setNewHead(ev.Block.Header()) 295 // hack in order to avoid hogging the lock; this part will 296 // be replaced by a subsequent PR. 297 time.Sleep(time.Millisecond) 298 299 // System stopped 300 case <-pool.chainHeadSub.Err(): 301 return 302 } 303 } 304 } 305 306 func (pool *TxPool) setNewHead(head *types.Header) { 307 pool.mu.Lock() 308 defer pool.mu.Unlock() 309 310 ctx, cancel := context.WithTimeout(context.Background(), blockCheckTimeout) 311 defer cancel() 312 313 txc, _ := pool.reorgOnNewHead(ctx, head) 314 m, r := txc.getLists() 315 pool.relay.NewHead(pool.head, m, r) 316 317 // Update fork indicator by next pending block number 318 next := new(big.Int).Add(head.Number, big.NewInt(1)) 319 pool.istanbul = pool.config.IsIstanbul(next) 320 pool.eip2718 = pool.config.IsBerlin(next) 321 pool.shanghai = pool.config.IsShanghai(next, uint64(time.Now().Unix())) 322 } 323 324 // Stop stops the light transaction pool 325 func (pool *TxPool) Stop() { 326 // Unsubscribe all subscriptions registered from txpool 327 pool.scope.Close() 328 // Unsubscribe subscriptions registered from blockchain 329 pool.chainHeadSub.Unsubscribe() 330 close(pool.quit) 331 log.Info("Transaction pool stopped") 332 } 333 334 // SubscribeNewTxsEvent registers a subscription of core.NewTxsEvent and 335 // starts sending event to the given channel. 336 func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription { 337 return pool.scope.Track(pool.txFeed.Subscribe(ch)) 338 } 339 340 // Stats returns the number of currently pending (locally created) transactions 341 func (pool *TxPool) Stats() (pending int) { 342 pool.mu.RLock() 343 defer pool.mu.RUnlock() 344 345 pending = len(pool.pending) 346 return 347 } 348 349 // validateTx checks whether a transaction is valid according to the consensus rules. 350 func (pool *TxPool) validateTx(ctx context.Context, tx *types.Transaction) error { 351 // Validate sender 352 var ( 353 from common.Address 354 err error 355 ) 356 357 // Validate the transaction sender and it's sig. Throw 358 // if the from fields is invalid. 359 if from, err = types.Sender(pool.signer, tx); err != nil { 360 return txpool.ErrInvalidSender 361 } 362 // Last but not least check for nonce errors 363 currentState := pool.currentState(ctx) 364 if n := currentState.GetNonce(from); n > tx.Nonce() { 365 return core.ErrNonceTooLow 366 } 367 368 // Check the transaction doesn't exceed the current 369 // block limit gas. 370 header := pool.chain.GetHeaderByHash(pool.head) 371 if header.GasLimit < tx.Gas() { 372 return txpool.ErrGasLimit 373 } 374 375 // Transactions can't be negative. This may never happen 376 // using RLP decoded transactions but may occur if you create 377 // a transaction using the RPC for example. 378 if tx.Value().Sign() < 0 { 379 return txpool.ErrNegativeValue 380 } 381 382 // Transactor should have enough funds to cover the costs 383 // cost == V + GP * GL 384 if b := currentState.GetBalance(from); b.Cmp(tx.Cost()) < 0 { 385 return core.ErrInsufficientFunds 386 } 387 388 // Should supply enough intrinsic gas 389 gas, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, pool.istanbul, pool.shanghai) 390 if err != nil { 391 return err 392 } 393 if tx.Gas() < gas { 394 return core.ErrIntrinsicGas 395 } 396 return currentState.Error() 397 } 398 399 // add validates a new transaction and sets its state pending if processable. 400 // It also updates the locally stored nonce if necessary. 401 func (pool *TxPool) add(ctx context.Context, tx *types.Transaction) error { 402 hash := tx.Hash() 403 404 if pool.pending[hash] != nil { 405 return fmt.Errorf("known transaction (%x)", hash[:4]) 406 } 407 err := pool.validateTx(ctx, tx) 408 if err != nil { 409 return err 410 } 411 412 if _, ok := pool.pending[hash]; !ok { 413 pool.pending[hash] = tx 414 415 nonce := tx.Nonce() + 1 416 417 addr, _ := types.Sender(pool.signer, tx) 418 if nonce > pool.nonce[addr] { 419 pool.nonce[addr] = nonce 420 } 421 422 // Notify the subscribers. This event is posted in a goroutine 423 // because it's possible that somewhere during the post "Remove transaction" 424 // gets called which will then wait for the global tx pool lock and deadlock. 425 go pool.txFeed.Send(core.NewTxsEvent{Txs: types.Transactions{tx}}) 426 } 427 428 // Print a log message if low enough level is set 429 log.Debug("Pooled new transaction", "hash", hash, "from", log.Lazy{Fn: func() common.Address { from, _ := types.Sender(pool.signer, tx); return from }}, "to", tx.To()) 430 return nil 431 } 432 433 // Add adds a transaction to the pool if valid and passes it to the tx relay 434 // backend 435 func (pool *TxPool) Add(ctx context.Context, tx *types.Transaction) error { 436 pool.mu.Lock() 437 defer pool.mu.Unlock() 438 data, err := tx.MarshalBinary() 439 if err != nil { 440 return err 441 } 442 443 if err := pool.add(ctx, tx); err != nil { 444 return err 445 } 446 //fmt.Println("Send", tx.Hash()) 447 pool.relay.Send(types.Transactions{tx}) 448 449 pool.chainDb.Put(tx.Hash().Bytes(), data) 450 return nil 451 } 452 453 // AddBatch adds all valid transactions to the pool and passes them to 454 // the tx relay backend 455 func (pool *TxPool) AddBatch(ctx context.Context, txs []*types.Transaction) { 456 pool.mu.Lock() 457 defer pool.mu.Unlock() 458 var sendTx types.Transactions 459 460 for _, tx := range txs { 461 if err := pool.add(ctx, tx); err == nil { 462 sendTx = append(sendTx, tx) 463 } 464 } 465 if len(sendTx) > 0 { 466 pool.relay.Send(sendTx) 467 } 468 } 469 470 // GetTransaction returns a transaction if it is contained in the pool 471 // and nil otherwise. 472 func (pool *TxPool) GetTransaction(hash common.Hash) *types.Transaction { 473 // check the txs first 474 if tx, ok := pool.pending[hash]; ok { 475 return tx 476 } 477 return nil 478 } 479 480 // GetTransactions returns all currently processable transactions. 481 // The returned slice may be modified by the caller. 482 func (pool *TxPool) GetTransactions() (txs types.Transactions, err error) { 483 pool.mu.RLock() 484 defer pool.mu.RUnlock() 485 486 txs = make(types.Transactions, len(pool.pending)) 487 i := 0 488 for _, tx := range pool.pending { 489 txs[i] = tx 490 i++ 491 } 492 return txs, nil 493 } 494 495 // Content retrieves the data content of the transaction pool, returning all the 496 // pending as well as queued transactions, grouped by account and nonce. 497 func (pool *TxPool) Content() (map[common.Address][]*types.Transaction, map[common.Address][]*types.Transaction) { 498 pool.mu.RLock() 499 defer pool.mu.RUnlock() 500 501 // Retrieve all the pending transactions and sort by account and by nonce 502 pending := make(map[common.Address][]*types.Transaction) 503 for _, tx := range pool.pending { 504 account, _ := types.Sender(pool.signer, tx) 505 pending[account] = append(pending[account], tx) 506 } 507 // There are no queued transactions in a light pool, just return an empty map 508 queued := make(map[common.Address][]*types.Transaction) 509 return pending, queued 510 } 511 512 // ContentFrom retrieves the data content of the transaction pool, returning the 513 // pending as well as queued transactions of this address, grouped by nonce. 514 func (pool *TxPool) ContentFrom(addr common.Address) ([]*types.Transaction, []*types.Transaction) { 515 pool.mu.RLock() 516 defer pool.mu.RUnlock() 517 518 // Retrieve the pending transactions and sort by nonce 519 var pending []*types.Transaction 520 for _, tx := range pool.pending { 521 account, _ := types.Sender(pool.signer, tx) 522 if account != addr { 523 continue 524 } 525 pending = append(pending, tx) 526 } 527 // There are no queued transactions in a light pool, just return an empty map 528 return pending, []*types.Transaction{} 529 } 530 531 // RemoveTransactions removes all given transactions from the pool. 532 func (pool *TxPool) RemoveTransactions(txs types.Transactions) { 533 pool.mu.Lock() 534 defer pool.mu.Unlock() 535 536 var hashes []common.Hash 537 batch := pool.chainDb.NewBatch() 538 for _, tx := range txs { 539 hash := tx.Hash() 540 delete(pool.pending, hash) 541 batch.Delete(hash.Bytes()) 542 hashes = append(hashes, hash) 543 } 544 batch.Write() 545 pool.relay.Discard(hashes) 546 } 547 548 // RemoveTx removes the transaction with the given hash from the pool. 549 func (pool *TxPool) RemoveTx(hash common.Hash) { 550 pool.mu.Lock() 551 defer pool.mu.Unlock() 552 // delete from pending pool 553 delete(pool.pending, hash) 554 pool.chainDb.Delete(hash[:]) 555 pool.relay.Discard([]common.Hash{hash}) 556 }