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