github.com/MikyChow/arbitrum-go-ethereum@v0.0.0-20230306102812-078da49636de/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/MikyChow/arbitrum-go-ethereum/common" 27 "github.com/MikyChow/arbitrum-go-ethereum/core" 28 "github.com/MikyChow/arbitrum-go-ethereum/core/rawdb" 29 "github.com/MikyChow/arbitrum-go-ethereum/core/state" 30 "github.com/MikyChow/arbitrum-go-ethereum/core/types" 31 "github.com/MikyChow/arbitrum-go-ethereum/ethdb" 32 "github.com/MikyChow/arbitrum-go-ethereum/event" 33 "github.com/MikyChow/arbitrum-go-ethereum/log" 34 "github.com/MikyChow/arbitrum-go-ethereum/params" 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 istanbul bool // Fork indicator whether we are in the istanbul stage. 71 eip2718 bool // Fork indicator whether we are in the eip2718 stage. 72 } 73 74 // TxRelayBackend provides an interface to the mechanism that forwards transactions 75 // to the ETH network. The implementations of the functions should be non-blocking. 76 // 77 // Send instructs backend to forward new transactions 78 // NewHead notifies backend about a new head after processed by the tx pool, 79 // 80 // including mined and rolled back transactions since the last event 81 // 82 // Discard notifies backend about transactions that should be discarded either 83 // 84 // because they have been replaced by a re-send or because they have been mined 85 // long ago and no 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 loopup 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 } 322 323 // Stop stops the light transaction pool 324 func (pool *TxPool) Stop() { 325 // Unsubscribe all subscriptions registered from txpool 326 pool.scope.Close() 327 // Unsubscribe subscriptions registered from blockchain 328 pool.chainHeadSub.Unsubscribe() 329 close(pool.quit) 330 log.Info("Transaction pool stopped") 331 } 332 333 // SubscribeNewTxsEvent registers a subscription of core.NewTxsEvent and 334 // starts sending event to the given channel. 335 func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription { 336 return pool.scope.Track(pool.txFeed.Subscribe(ch)) 337 } 338 339 // Stats returns the number of currently pending (locally created) transactions 340 func (pool *TxPool) Stats() (pending int) { 341 pool.mu.RLock() 342 defer pool.mu.RUnlock() 343 344 pending = len(pool.pending) 345 return 346 } 347 348 // validateTx checks whether a transaction is valid according to the consensus rules. 349 func (pool *TxPool) validateTx(ctx context.Context, tx *types.Transaction) error { 350 // Validate sender 351 var ( 352 from common.Address 353 err error 354 ) 355 356 // Validate the transaction sender and it's sig. Throw 357 // if the from fields is invalid. 358 if from, err = types.Sender(pool.signer, tx); err != nil { 359 return core.ErrInvalidSender 360 } 361 // Last but not least check for nonce errors 362 currentState := pool.currentState(ctx) 363 if n := currentState.GetNonce(from); n > tx.Nonce() { 364 return core.ErrNonceTooLow 365 } 366 367 // Check the transaction doesn't exceed the current 368 // block limit gas. 369 header := pool.chain.GetHeaderByHash(pool.head) 370 if header.GasLimit < tx.Gas() { 371 return core.ErrGasLimit 372 } 373 374 // Transactions can't be negative. This may never happen 375 // using RLP decoded transactions but may occur if you create 376 // a transaction using the RPC for example. 377 if tx.Value().Sign() < 0 { 378 return core.ErrNegativeValue 379 } 380 381 // Transactor should have enough funds to cover the costs 382 // cost == V + GP * GL 383 if b := currentState.GetBalance(from); b.Cmp(tx.Cost()) < 0 { 384 return core.ErrInsufficientFunds 385 } 386 387 // Should supply enough intrinsic gas 388 gas, err := core.IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, pool.istanbul) 389 if err != nil { 390 return err 391 } 392 if tx.Gas() < gas { 393 return core.ErrIntrinsicGas 394 } 395 return currentState.Error() 396 } 397 398 // add validates a new transaction and sets its state pending if processable. 399 // It also updates the locally stored nonce if necessary. 400 func (pool *TxPool) add(ctx context.Context, tx *types.Transaction) error { 401 hash := tx.Hash() 402 403 if pool.pending[hash] != nil { 404 return fmt.Errorf("known transaction (%x)", hash[:4]) 405 } 406 err := pool.validateTx(ctx, tx) 407 if err != nil { 408 return err 409 } 410 411 if _, ok := pool.pending[hash]; !ok { 412 pool.pending[hash] = tx 413 414 nonce := tx.Nonce() + 1 415 416 addr, _ := types.Sender(pool.signer, tx) 417 if nonce > pool.nonce[addr] { 418 pool.nonce[addr] = nonce 419 } 420 421 // Notify the subscribers. This event is posted in a goroutine 422 // because it's possible that somewhere during the post "Remove transaction" 423 // gets called which will then wait for the global tx pool lock and deadlock. 424 go pool.txFeed.Send(core.NewTxsEvent{Txs: types.Transactions{tx}}) 425 } 426 427 // Print a log message if low enough level is set 428 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()) 429 return nil 430 } 431 432 // Add adds a transaction to the pool if valid and passes it to the tx relay 433 // backend 434 func (pool *TxPool) Add(ctx context.Context, tx *types.Transaction) error { 435 pool.mu.Lock() 436 defer pool.mu.Unlock() 437 data, err := tx.MarshalBinary() 438 if err != nil { 439 return err 440 } 441 442 if err := pool.add(ctx, tx); err != nil { 443 return err 444 } 445 //fmt.Println("Send", tx.Hash()) 446 pool.relay.Send(types.Transactions{tx}) 447 448 pool.chainDb.Put(tx.Hash().Bytes(), data) 449 return nil 450 } 451 452 // AddTransactions adds all valid transactions to the pool and passes them to 453 // the tx relay backend 454 func (pool *TxPool) AddBatch(ctx context.Context, txs []*types.Transaction) { 455 pool.mu.Lock() 456 defer pool.mu.Unlock() 457 var sendTx types.Transactions 458 459 for _, tx := range txs { 460 if err := pool.add(ctx, tx); err == nil { 461 sendTx = append(sendTx, tx) 462 } 463 } 464 if len(sendTx) > 0 { 465 pool.relay.Send(sendTx) 466 } 467 } 468 469 // GetTransaction returns a transaction if it is contained in the pool 470 // and nil otherwise. 471 func (pool *TxPool) GetTransaction(hash common.Hash) *types.Transaction { 472 // check the txs first 473 if tx, ok := pool.pending[hash]; ok { 474 return tx 475 } 476 return nil 477 } 478 479 // GetTransactions returns all currently processable transactions. 480 // The returned slice may be modified by the caller. 481 func (pool *TxPool) GetTransactions() (txs types.Transactions, err error) { 482 pool.mu.RLock() 483 defer pool.mu.RUnlock() 484 485 txs = make(types.Transactions, len(pool.pending)) 486 i := 0 487 for _, tx := range pool.pending { 488 txs[i] = tx 489 i++ 490 } 491 return txs, nil 492 } 493 494 // Content retrieves the data content of the transaction pool, returning all the 495 // pending as well as queued transactions, grouped by account and nonce. 496 func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) { 497 pool.mu.RLock() 498 defer pool.mu.RUnlock() 499 500 // Retrieve all the pending transactions and sort by account and by nonce 501 pending := make(map[common.Address]types.Transactions) 502 for _, tx := range pool.pending { 503 account, _ := types.Sender(pool.signer, tx) 504 pending[account] = append(pending[account], tx) 505 } 506 // There are no queued transactions in a light pool, just return an empty map 507 queued := make(map[common.Address]types.Transactions) 508 return pending, queued 509 } 510 511 // ContentFrom retrieves the data content of the transaction pool, returning the 512 // pending as well as queued transactions of this address, grouped by nonce. 513 func (pool *TxPool) ContentFrom(addr common.Address) (types.Transactions, types.Transactions) { 514 pool.mu.RLock() 515 defer pool.mu.RUnlock() 516 517 // Retrieve the pending transactions and sort by nonce 518 var pending types.Transactions 519 for _, tx := range pool.pending { 520 account, _ := types.Sender(pool.signer, tx) 521 if account != addr { 522 continue 523 } 524 pending = append(pending, tx) 525 } 526 // There are no queued transactions in a light pool, just return an empty map 527 return pending, types.Transactions{} 528 } 529 530 // RemoveTransactions removes all given transactions from the pool. 531 func (pool *TxPool) RemoveTransactions(txs types.Transactions) { 532 pool.mu.Lock() 533 defer pool.mu.Unlock() 534 535 var hashes []common.Hash 536 batch := pool.chainDb.NewBatch() 537 for _, tx := range txs { 538 hash := tx.Hash() 539 delete(pool.pending, hash) 540 batch.Delete(hash.Bytes()) 541 hashes = append(hashes, hash) 542 } 543 batch.Write() 544 pool.relay.Discard(hashes) 545 } 546 547 // RemoveTx removes the transaction with the given hash from the pool. 548 func (pool *TxPool) RemoveTx(hash common.Hash) { 549 pool.mu.Lock() 550 defer pool.mu.Unlock() 551 // delete from pending pool 552 delete(pool.pending, hash) 553 pool.chainDb.Delete(hash[:]) 554 pool.relay.Discard([]common.Hash{hash}) 555 }