light/*:golint updates for this or self warning

This commit is contained in:
Kiel barry 2018-04-27 17:15:55 -07:00
parent 0040e916cc
commit 0a57bbfa99
3 changed files with 148 additions and 148 deletions

View file

@ -115,45 +115,45 @@ func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.
} }
// addTrustedCheckpoint adds a trusted checkpoint to the blockchain // addTrustedCheckpoint adds a trusted checkpoint to the blockchain
func (self *LightChain) addTrustedCheckpoint(cp trustedCheckpoint) { func (bc *LightChain) addTrustedCheckpoint(cp trustedCheckpoint) {
if self.odr.ChtIndexer() != nil { if bc.odr.ChtIndexer() != nil {
StoreChtRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.chtRoot) StoreChtRoot(bc.chainDb, cp.sectionIdx, cp.sectionHead, cp.chtRoot)
self.odr.ChtIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead) bc.odr.ChtIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
} }
if self.odr.BloomTrieIndexer() != nil { if bc.odr.BloomTrieIndexer() != nil {
StoreBloomTrieRoot(self.chainDb, cp.sectionIdx, cp.sectionHead, cp.bloomTrieRoot) StoreBloomTrieRoot(bc.chainDb, cp.sectionIdx, cp.sectionHead, cp.bloomTrieRoot)
self.odr.BloomTrieIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead) bc.odr.BloomTrieIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
} }
if self.odr.BloomIndexer() != nil { if bc.odr.BloomIndexer() != nil {
self.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead) bc.odr.BloomIndexer().AddKnownSectionHead(cp.sectionIdx, cp.sectionHead)
} }
log.Info("Added trusted checkpoint", "chain", cp.name, "block", (cp.sectionIdx+1)*CHTFrequencyClient-1, "hash", cp.sectionHead) log.Info("Added trusted checkpoint", "chain", cp.name, "block", (cp.sectionIdx+1)*CHTFrequencyClient-1, "hash", cp.sectionHead)
} }
func (self *LightChain) getProcInterrupt() bool { func (bc *LightChain) getProcInterrupt() bool {
return atomic.LoadInt32(&self.procInterrupt) == 1 return atomic.LoadInt32(&bc.procInterrupt) == 1
} }
// Odr returns the ODR backend of the chain // Odr returns the ODR backend of the chain
func (self *LightChain) Odr() OdrBackend { func (bc *LightChain) Odr() OdrBackend {
return self.odr return bc.odr
} }
// loadLastState loads the last known chain state from the database. This method // loadLastState loads the last known chain state from the database. This method
// assumes that the chain manager mutex is held. // assumes that the chain manager mutex is held.
func (self *LightChain) loadLastState() error { func (bc *LightChain) loadLastState() error {
if head := core.GetHeadHeaderHash(self.chainDb); head == (common.Hash{}) { if head := core.GetHeadHeaderHash(bc.chainDb); head == (common.Hash{}) {
// Corrupt or empty database, init from scratch // Corrupt or empty database, init from scratch
self.Reset() bc.Reset()
} else { } else {
if header := self.GetHeaderByHash(head); header != nil { if header := bc.GetHeaderByHash(head); header != nil {
self.hc.SetCurrentHeader(header) bc.hc.SetCurrentHeader(header)
} }
} }
// Issue a status log and return // Issue a status log and return
header := self.hc.CurrentHeader() header := bc.hc.CurrentHeader()
headerTd := self.GetTd(header.Hash(), header.Number.Uint64()) headerTd := bc.GetTd(header.Hash(), header.Number.Uint64())
log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd) log.Info("Loaded most recent local header", "number", header.Number, "hash", header.Hash(), "td", headerTd)
return nil return nil
@ -170,8 +170,8 @@ func (bc *LightChain) SetHead(head uint64) {
} }
// GasLimit returns the gas limit of the current HEAD block. // GasLimit returns the gas limit of the current HEAD block.
func (self *LightChain) GasLimit() uint64 { func (bc *LightChain) GasLimit() uint64 {
return self.hc.CurrentHeader().GasLimit return bc.hc.CurrentHeader().GasLimit
} }
// Reset purges the entire blockchain, restoring it to its genesis state. // Reset purges the entire blockchain, restoring it to its genesis state.
@ -217,34 +217,34 @@ func (bc *LightChain) State() (*state.StateDB, error) {
// GetBody retrieves a block body (transactions and uncles) from the database // GetBody retrieves a block body (transactions and uncles) from the database
// or ODR service by hash, caching it if found. // or ODR service by hash, caching it if found.
func (self *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) { func (bc *LightChain) GetBody(ctx context.Context, hash common.Hash) (*types.Body, error) {
// Short circuit if the body's already in the cache, retrieve otherwise // Short circuit if the body's already in the cache, retrieve otherwise
if cached, ok := self.bodyCache.Get(hash); ok { if cached, ok := bc.bodyCache.Get(hash); ok {
body := cached.(*types.Body) body := cached.(*types.Body)
return body, nil return body, nil
} }
body, err := GetBody(ctx, self.odr, hash, self.hc.GetBlockNumber(hash)) body, err := GetBody(ctx, bc.odr, hash, bc.hc.GetBlockNumber(hash))
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Cache the found body for next time and return // Cache the found body for next time and return
self.bodyCache.Add(hash, body) bc.bodyCache.Add(hash, body)
return body, nil return body, nil
} }
// GetBodyRLP retrieves a block body in RLP encoding from the database or // GetBodyRLP retrieves a block body in RLP encoding from the database or
// ODR service by hash, caching it if found. // ODR service by hash, caching it if found.
func (self *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) { func (bc *LightChain) GetBodyRLP(ctx context.Context, hash common.Hash) (rlp.RawValue, error) {
// Short circuit if the body's already in the cache, retrieve otherwise // Short circuit if the body's already in the cache, retrieve otherwise
if cached, ok := self.bodyRLPCache.Get(hash); ok { if cached, ok := bc.bodyRLPCache.Get(hash); ok {
return cached.(rlp.RawValue), nil return cached.(rlp.RawValue), nil
} }
body, err := GetBodyRLP(ctx, self.odr, hash, self.hc.GetBlockNumber(hash)) body, err := GetBodyRLP(ctx, bc.odr, hash, bc.hc.GetBlockNumber(hash))
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Cache the found body for next time and return // Cache the found body for next time and return
self.bodyRLPCache.Add(hash, body) bc.bodyRLPCache.Add(hash, body)
return body, nil return body, nil
} }
@ -257,34 +257,34 @@ func (bc *LightChain) HasBlock(hash common.Hash, number uint64) bool {
// GetBlock retrieves a block from the database or ODR service by hash and number, // GetBlock retrieves a block from the database or ODR service by hash and number,
// caching it if found. // caching it if found.
func (self *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) { func (bc *LightChain) GetBlock(ctx context.Context, hash common.Hash, number uint64) (*types.Block, error) {
// Short circuit if the block's already in the cache, retrieve otherwise // Short circuit if the block's already in the cache, retrieve otherwise
if block, ok := self.blockCache.Get(hash); ok { if block, ok := bc.blockCache.Get(hash); ok {
return block.(*types.Block), nil return block.(*types.Block), nil
} }
block, err := GetBlock(ctx, self.odr, hash, number) block, err := GetBlock(ctx, bc.odr, hash, number)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// Cache the found block for next time and return // Cache the found block for next time and return
self.blockCache.Add(block.Hash(), block) bc.blockCache.Add(block.Hash(), block)
return block, nil return block, nil
} }
// GetBlockByHash retrieves a block from the database or ODR service by hash, // GetBlockByHash retrieves a block from the database or ODR service by hash,
// caching it if found. // caching it if found.
func (self *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { func (bc *LightChain) GetBlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
return self.GetBlock(ctx, hash, self.hc.GetBlockNumber(hash)) return bc.GetBlock(ctx, hash, bc.hc.GetBlockNumber(hash))
} }
// GetBlockByNumber retrieves a block from the database or ODR service by // GetBlockByNumber retrieves a block from the database or ODR service by
// number, caching it (associated with its hash) if found. // number, caching it (associated with its hash) if found.
func (self *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) { func (bc *LightChain) GetBlockByNumber(ctx context.Context, number uint64) (*types.Block, error) {
hash, err := GetCanonicalHash(ctx, self.odr, number) hash, err := GetCanonicalHash(ctx, bc.odr, number)
if hash == (common.Hash{}) || err != nil { if hash == (common.Hash{}) || err != nil {
return nil, err return nil, err
} }
return self.GetBlock(ctx, hash, number) return bc.GetBlock(ctx, hash, number)
} }
// Stop stops the blockchain service. If any imports are currently in progress // Stop stops the blockchain service. If any imports are currently in progress
@ -302,31 +302,31 @@ func (bc *LightChain) Stop() {
// Rollback is designed to remove a chain of links from the database that aren't // Rollback is designed to remove a chain of links from the database that aren't
// certain enough to be valid. // certain enough to be valid.
func (self *LightChain) Rollback(chain []common.Hash) { func (bc *LightChain) Rollback(chain []common.Hash) {
self.mu.Lock() bc.mu.Lock()
defer self.mu.Unlock() defer bc.mu.Unlock()
for i := len(chain) - 1; i >= 0; i-- { for i := len(chain) - 1; i >= 0; i-- {
hash := chain[i] hash := chain[i]
if head := self.hc.CurrentHeader(); head.Hash() == hash { if head := bc.hc.CurrentHeader(); head.Hash() == hash {
self.hc.SetCurrentHeader(self.GetHeader(head.ParentHash, head.Number.Uint64()-1)) bc.hc.SetCurrentHeader(bc.GetHeader(head.ParentHash, head.Number.Uint64()-1))
} }
} }
} }
// postChainEvents iterates over the events generated by a chain insertion and // postChainEvents iterates over the events generated by a chain insertion and
// posts them into the event feed. // posts them into the event feed.
func (self *LightChain) postChainEvents(events []interface{}) { func (bc *LightChain) postChainEvents(events []interface{}) {
for _, event := range events { for _, event := range events {
switch ev := event.(type) { switch ev := event.(type) {
case core.ChainEvent: case core.ChainEvent:
if self.CurrentHeader().Hash() == ev.Hash { if bc.CurrentHeader().Hash() == ev.Hash {
self.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block}) bc.chainHeadFeed.Send(core.ChainHeadEvent{Block: ev.Block})
} }
self.chainFeed.Send(ev) bc.chainFeed.Send(ev)
case core.ChainSideEvent: case core.ChainSideEvent:
self.chainSideFeed.Send(ev) bc.chainSideFeed.Send(ev)
} }
} }
} }
@ -342,28 +342,28 @@ func (self *LightChain) postChainEvents(events []interface{}) {
// //
// In the case of a light chain, InsertHeaderChain also creates and posts light // In the case of a light chain, InsertHeaderChain also creates and posts light
// chain events when necessary. // chain events when necessary.
func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) { func (bc *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
start := time.Now() start := time.Now()
if i, err := self.hc.ValidateHeaderChain(chain, checkFreq); err != nil { if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
return i, err return i, err
} }
// Make sure only one thread manipulates the chain at once // Make sure only one thread manipulates the chain at once
self.chainmu.Lock() bc.chainmu.Lock()
defer func() { defer func() {
self.chainmu.Unlock() bc.chainmu.Unlock()
time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation time.Sleep(time.Millisecond * 10) // ugly hack; do not hog chain lock in case syncing is CPU-limited by validation
}() }()
self.wg.Add(1) bc.wg.Add(1)
defer self.wg.Done() defer bc.wg.Done()
var events []interface{} var events []interface{}
whFunc := func(header *types.Header) error { whFunc := func(header *types.Header) error {
self.mu.Lock() bc.mu.Lock()
defer self.mu.Unlock() defer bc.mu.Unlock()
status, err := self.hc.WriteHeader(header) status, err := bc.hc.WriteHeader(header)
switch status { switch status {
case core.CanonStatTy: case core.CanonStatTy:
@ -376,39 +376,39 @@ func (self *LightChain) InsertHeaderChain(chain []*types.Header, checkFreq int)
} }
return err return err
} }
i, err := self.hc.InsertHeaderChain(chain, whFunc, start) i, err := bc.hc.InsertHeaderChain(chain, whFunc, start)
self.postChainEvents(events) bc.postChainEvents(events)
return i, err return i, err
} }
// CurrentHeader retrieves the current head header of the canonical chain. The // CurrentHeader retrieves the current head header of the canonical chain. The
// header is retrieved from the HeaderChain's internal cache. // header is retrieved from the HeaderChain's internal cache.
func (self *LightChain) CurrentHeader() *types.Header { func (bc *LightChain) CurrentHeader() *types.Header {
return self.hc.CurrentHeader() return bc.hc.CurrentHeader()
} }
// GetTd retrieves a block's total difficulty in the canonical chain from the // GetTd retrieves a block's total difficulty in the canonical chain from the
// database by hash and number, caching it if found. // database by hash and number, caching it if found.
func (self *LightChain) GetTd(hash common.Hash, number uint64) *big.Int { func (bc *LightChain) GetTd(hash common.Hash, number uint64) *big.Int {
return self.hc.GetTd(hash, number) return bc.hc.GetTd(hash, number)
} }
// GetTdByHash retrieves a block's total difficulty in the canonical chain from the // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
// database by hash, caching it if found. // database by hash, caching it if found.
func (self *LightChain) GetTdByHash(hash common.Hash) *big.Int { func (bc *LightChain) GetTdByHash(hash common.Hash) *big.Int {
return self.hc.GetTdByHash(hash) return bc.hc.GetTdByHash(hash)
} }
// GetHeader retrieves a block header from the database by hash and number, // GetHeader retrieves a block header from the database by hash and number,
// caching it if found. // caching it if found.
func (self *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header { func (bc *LightChain) GetHeader(hash common.Hash, number uint64) *types.Header {
return self.hc.GetHeader(hash, number) return bc.hc.GetHeader(hash, number)
} }
// GetHeaderByHash retrieves a block header from the database by hash, caching it if // GetHeaderByHash retrieves a block header from the database by hash, caching it if
// found. // found.
func (self *LightChain) GetHeaderByHash(hash common.Hash) *types.Header { func (bc *LightChain) GetHeaderByHash(hash common.Hash) *types.Header {
return self.hc.GetHeaderByHash(hash) return bc.hc.GetHeaderByHash(hash)
} }
// HasHeader checks if a block header is present in the database or not, caching // HasHeader checks if a block header is present in the database or not, caching
@ -419,43 +419,43 @@ func (bc *LightChain) HasHeader(hash common.Hash, number uint64) bool {
// GetBlockHashesFromHash retrieves a number of block hashes starting at a given // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
// hash, fetching towards the genesis block. // hash, fetching towards the genesis block.
func (self *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash { func (bc *LightChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
return self.hc.GetBlockHashesFromHash(hash, max) return bc.hc.GetBlockHashesFromHash(hash, max)
} }
// GetHeaderByNumber retrieves a block header from the database by number, // GetHeaderByNumber retrieves a block header from the database by number,
// caching it (associated with its hash) if found. // caching it (associated with its hash) if found.
func (self *LightChain) GetHeaderByNumber(number uint64) *types.Header { func (bc *LightChain) GetHeaderByNumber(number uint64) *types.Header {
return self.hc.GetHeaderByNumber(number) return bc.hc.GetHeaderByNumber(number)
} }
// GetHeaderByNumberOdr retrieves a block header from the database or network // GetHeaderByNumberOdr retrieves a block header from the database or network
// by number, caching it (associated with its hash) if found. // by number, caching it (associated with its hash) if found.
func (self *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) { func (bc *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) (*types.Header, error) {
if header := self.hc.GetHeaderByNumber(number); header != nil { if header := bc.hc.GetHeaderByNumber(number); header != nil {
return header, nil return header, nil
} }
return GetHeaderByNumber(ctx, self.odr, number) return GetHeaderByNumber(ctx, bc.odr, number)
} }
// Config retrieves the header chain's chain configuration. // Config retrieves the header chain's chain configuration.
func (self *LightChain) Config() *params.ChainConfig { return self.hc.Config() } func (bc *LightChain) Config() *params.ChainConfig { return bc.hc.Config() }
func (self *LightChain) SyncCht(ctx context.Context) bool { func (bc *LightChain) SyncCht(ctx context.Context) bool {
if self.odr.ChtIndexer() == nil { if bc.odr.ChtIndexer() == nil {
return false return false
} }
headNum := self.CurrentHeader().Number.Uint64() headNum := bc.CurrentHeader().Number.Uint64()
chtCount, _, _ := self.odr.ChtIndexer().Sections() chtCount, _, _ := bc.odr.ChtIndexer().Sections()
if headNum+1 < chtCount*CHTFrequencyClient { if headNum+1 < chtCount*CHTFrequencyClient {
num := chtCount*CHTFrequencyClient - 1 num := chtCount*CHTFrequencyClient - 1
header, err := GetHeaderByNumber(ctx, self.odr, num) header, err := GetHeaderByNumber(ctx, bc.odr, num)
if header != nil && err == nil { if header != nil && err == nil {
self.mu.Lock() bc.mu.Lock()
if self.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() { if bc.hc.CurrentHeader().Number.Uint64() < header.Number.Uint64() {
self.hc.SetCurrentHeader(header) bc.hc.SetCurrentHeader(header)
} }
self.mu.Unlock() bc.mu.Unlock()
return true return true
} }
} }
@ -464,38 +464,38 @@ func (self *LightChain) SyncCht(ctx context.Context) bool {
// LockChain locks the chain mutex for reading so that multiple canonical hashes can be // LockChain locks the chain mutex for reading so that multiple canonical hashes can be
// retrieved while it is guaranteed that they belong to the same version of the chain // retrieved while it is guaranteed that they belong to the same version of the chain
func (self *LightChain) LockChain() { func (bc *LightChain) LockChain() {
self.chainmu.RLock() bc.chainmu.RLock()
} }
// UnlockChain unlocks the chain mutex // UnlockChain unlocks the chain mutex
func (self *LightChain) UnlockChain() { func (bc *LightChain) UnlockChain() {
self.chainmu.RUnlock() bc.chainmu.RUnlock()
} }
// SubscribeChainEvent registers a subscription of ChainEvent. // SubscribeChainEvent registers a subscription of ChainEvent.
func (self *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { func (bc *LightChain) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
return self.scope.Track(self.chainFeed.Subscribe(ch)) return bc.scope.Track(bc.chainFeed.Subscribe(ch))
} }
// SubscribeChainHeadEvent registers a subscription of ChainHeadEvent. // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
func (self *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription { func (bc *LightChain) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
return self.scope.Track(self.chainHeadFeed.Subscribe(ch)) return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
} }
// SubscribeChainSideEvent registers a subscription of ChainSideEvent. // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
func (self *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription { func (bc *LightChain) SubscribeChainSideEvent(ch chan<- core.ChainSideEvent) event.Subscription {
return self.scope.Track(self.chainSideFeed.Subscribe(ch)) return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
} }
// SubscribeLogsEvent implements the interface of filters.Backend // SubscribeLogsEvent implements the interface of filters.Backend
// LightChain does not send logs events, so return an empty subscription. // LightChain does not send logs events, so return an empty subscription.
func (self *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { func (bc *LightChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
return self.scope.Track(new(event.Feed).Subscribe(ch)) return bc.scope.Track(new(event.Feed).Subscribe(ch))
} }
// SubscribeRemovedLogsEvent implements the interface of filters.Backend // SubscribeRemovedLogsEvent implements the interface of filters.Backend
// LightChain does not send core.RemovedLogsEvent, so return an empty subscription. // LightChain does not send core.RemovedLogsEvent, so return an empty subscription.
func (self *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { func (bc *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
return self.scope.Track(new(event.Feed).Subscribe(ch)) return bc.scope.Track(new(event.Feed).Subscribe(ch))
} }

View file

@ -388,81 +388,81 @@ func (pool *TxPool) validateTx(ctx context.Context, tx *types.Transaction) error
// add validates a new transaction and sets its state pending if processable. // add validates a new transaction and sets its state pending if processable.
// It also updates the locally stored nonce if necessary. // It also updates the locally stored nonce if necessary.
func (self *TxPool) add(ctx context.Context, tx *types.Transaction) error { func (pool *TxPool) add(ctx context.Context, tx *types.Transaction) error {
hash := tx.Hash() hash := tx.Hash()
if self.pending[hash] != nil { if pool.pending[hash] != nil {
return fmt.Errorf("Known transaction (%x)", hash[:4]) return fmt.Errorf("Known transaction (%x)", hash[:4])
} }
err := self.validateTx(ctx, tx) err := pool.validateTx(ctx, tx)
if err != nil { if err != nil {
return err return err
} }
if _, ok := self.pending[hash]; !ok { if _, ok := pool.pending[hash]; !ok {
self.pending[hash] = tx pool.pending[hash] = tx
nonce := tx.Nonce() + 1 nonce := tx.Nonce() + 1
addr, _ := types.Sender(self.signer, tx) addr, _ := types.Sender(pool.signer, tx)
if nonce > self.nonce[addr] { if nonce > pool.nonce[addr] {
self.nonce[addr] = nonce pool.nonce[addr] = nonce
} }
// Notify the subscribers. This event is posted in a goroutine // Notify the subscribers. This event is posted in a goroutine
// because it's possible that somewhere during the post "Remove transaction" // because it's possible that somewhere during the post "Remove transaction"
// gets called which will then wait for the global tx pool lock and deadlock. // gets called which will then wait for the global tx pool lock and deadlock.
go self.txFeed.Send(core.TxPreEvent{Tx: tx}) go pool.txFeed.Send(core.TxPreEvent{Tx: tx})
} }
// Print a log message if low enough level is set // Print a log message if low enough level is set
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()) 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())
return nil return nil
} }
// Add adds a transaction to the pool if valid and passes it to the tx relay // Add adds a transaction to the pool if valid and passes it to the tx relay
// backend // backend
func (self *TxPool) Add(ctx context.Context, tx *types.Transaction) error { func (pool *TxPool) Add(ctx context.Context, tx *types.Transaction) error {
self.mu.Lock() pool.mu.Lock()
defer self.mu.Unlock() defer pool.mu.Unlock()
data, err := rlp.EncodeToBytes(tx) data, err := rlp.EncodeToBytes(tx)
if err != nil { if err != nil {
return err return err
} }
if err := self.add(ctx, tx); err != nil { if err := pool.add(ctx, tx); err != nil {
return err return err
} }
//fmt.Println("Send", tx.Hash()) //fmt.Println("Send", tx.Hash())
self.relay.Send(types.Transactions{tx}) pool.relay.Send(types.Transactions{tx})
self.chainDb.Put(tx.Hash().Bytes(), data) pool.chainDb.Put(tx.Hash().Bytes(), data)
return nil return nil
} }
// AddTransactions adds all valid transactions to the pool and passes them to // AddBatch adds all valid transactions to the pool and passes them to
// the tx relay backend // the tx relay backend
func (self *TxPool) AddBatch(ctx context.Context, txs []*types.Transaction) { func (pool *TxPool) AddBatch(ctx context.Context, txs []*types.Transaction) {
self.mu.Lock() pool.mu.Lock()
defer self.mu.Unlock() defer pool.mu.Unlock()
var sendTx types.Transactions var sendTx types.Transactions
for _, tx := range txs { for _, tx := range txs {
if err := self.add(ctx, tx); err == nil { if err := pool.add(ctx, tx); err == nil {
sendTx = append(sendTx, tx) sendTx = append(sendTx, tx)
} }
} }
if len(sendTx) > 0 { if len(sendTx) > 0 {
self.relay.Send(sendTx) pool.relay.Send(sendTx)
} }
} }
// GetTransaction returns a transaction if it is contained in the pool // GetTransaction returns a transaction if it is contained in the pool
// and nil otherwise. // and nil otherwise.
func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction { func (pool *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
// check the txs first // check the txs first
if tx, ok := tp.pending[hash]; ok { if tx, ok := pool.pending[hash]; ok {
return tx return tx
} }
return nil return nil
@ -470,13 +470,13 @@ func (tp *TxPool) GetTransaction(hash common.Hash) *types.Transaction {
// GetTransactions returns all currently processable transactions. // GetTransactions returns all currently processable transactions.
// The returned slice may be modified by the caller. // The returned slice may be modified by the caller.
func (self *TxPool) GetTransactions() (txs types.Transactions, err error) { func (pool *TxPool) GetTransactions() (txs types.Transactions, err error) {
self.mu.RLock() pool.mu.RLock()
defer self.mu.RUnlock() defer pool.mu.RUnlock()
txs = make(types.Transactions, len(self.pending)) txs = make(types.Transactions, len(pool.pending))
i := 0 i := 0
for _, tx := range self.pending { for _, tx := range pool.pending {
txs[i] = tx txs[i] = tx
i++ i++
} }
@ -485,14 +485,14 @@ func (self *TxPool) GetTransactions() (txs types.Transactions, err error) {
// Content retrieves the data content of the transaction pool, returning all the // Content retrieves the data content of the transaction pool, returning all the
// pending as well as queued transactions, grouped by account and nonce. // pending as well as queued transactions, grouped by account and nonce.
func (self *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) { func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
self.mu.RLock() pool.mu.RLock()
defer self.mu.RUnlock() defer pool.mu.RUnlock()
// Retrieve all the pending transactions and sort by account and by nonce // Retrieve all the pending transactions and sort by account and by nonce
pending := make(map[common.Address]types.Transactions) pending := make(map[common.Address]types.Transactions)
for _, tx := range self.pending { for _, tx := range pool.pending {
account, _ := types.Sender(self.signer, tx) account, _ := types.Sender(pool.signer, tx)
pending[account] = append(pending[account], tx) pending[account] = append(pending[account], tx)
} }
// There are no queued transactions in a light pool, just return an empty map // There are no queued transactions in a light pool, just return an empty map
@ -501,18 +501,18 @@ func (self *TxPool) Content() (map[common.Address]types.Transactions, map[common
} }
// RemoveTransactions removes all given transactions from the pool. // RemoveTransactions removes all given transactions from the pool.
func (self *TxPool) RemoveTransactions(txs types.Transactions) { func (pool *TxPool) RemoveTransactions(txs types.Transactions) {
self.mu.Lock() pool.mu.Lock()
defer self.mu.Unlock() defer pool.mu.Unlock()
var hashes []common.Hash var hashes []common.Hash
for _, tx := range txs { for _, tx := range txs {
//self.RemoveTx(tx.Hash()) //pool.RemoveTx(tx.Hash())
hash := tx.Hash() hash := tx.Hash()
delete(self.pending, hash) delete(pool.pending, hash)
self.chainDb.Delete(hash[:]) pool.chainDb.Delete(hash[:])
hashes = append(hashes, hash) hashes = append(hashes, hash)
} }
self.relay.Discard(hashes) pool.relay.Discard(hashes)
} }
// RemoveTx removes the transaction with the given hash from the pool. // RemoveTx removes the transaction with the given hash from the pool.

View file

@ -36,19 +36,19 @@ type testTxRelay struct {
send, discard, mined chan int send, discard, mined chan int
} }
func (self *testTxRelay) Send(txs types.Transactions) { func (r *testTxRelay) Send(txs types.Transactions) {
self.send <- len(txs) r.send <- len(txs)
} }
func (self *testTxRelay) NewHead(head common.Hash, mined []common.Hash, rollback []common.Hash) { func (r *testTxRelay) NewHead(head common.Hash, mined []common.Hash, rollback []common.Hash) {
m := len(mined) m := len(mined)
if m != 0 { if m != 0 {
self.mined <- m r.mined <- m
} }
} }
func (self *testTxRelay) Discard(hashes []common.Hash) { func (r *testTxRelay) Discard(hashes []common.Hash) {
self.discard <- len(hashes) r.discard <- len(hashes)
} }
const poolTestTxs = 1000 const poolTestTxs = 1000