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