Skip to content

Commit

Permalink
accounts: add blockByNumberNoLock() to avoid double-lock (#20983)
Browse files Browse the repository at this point in the history
* abi/bind/backends: testcase for double-lock

* accounts: add blockByNumberNoLock to avoid double-lock

* backend/simulated: use stateroot, not blockhash for retrieveing state

Co-authored-by: Martin Holst Swende <martin@swende.se>
  • Loading branch information
BurtonQin and holiman committed May 19, 2020
1 parent e0987f6 commit d5b7d1c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
10 changes: 8 additions & 2 deletions accounts/abi/bind/backends/simulated.go
Expand Up @@ -133,11 +133,11 @@ func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *
if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
return b.blockchain.State()
}
block, err := b.BlockByNumber(ctx, blockNumber)
block, err := b.blockByNumberNoLock(ctx, blockNumber)
if err != nil {
return nil, err
}
return b.blockchain.StateAt(block.Hash())
return b.blockchain.StateAt(block.Root())
}

// CodeAt returns the code associated with a certain account in the blockchain.
Expand Down Expand Up @@ -244,6 +244,12 @@ func (b *SimulatedBackend) BlockByNumber(ctx context.Context, number *big.Int) (
b.mu.Lock()
defer b.mu.Unlock()

return b.blockByNumberNoLock(ctx, number)
}

// blockByNumberNoLock retrieves a block from the database by number, caching it
// (associated with its hash) if found without Lock.
func (b *SimulatedBackend) blockByNumberNoLock(ctx context.Context, number *big.Int) (*types.Block, error) {
if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 {
return b.blockchain.CurrentBlock(), nil
}
Expand Down
10 changes: 10 additions & 0 deletions accounts/abi/bind/backends/simulated_test.go
Expand Up @@ -268,6 +268,16 @@ func TestSimulatedBackend_NonceAt(t *testing.T) {
if newNonce != nonce+uint64(1) {
t.Errorf("received incorrect nonce. expected 1, got %v", nonce)
}
// create some more blocks
sim.Commit()
// Check that we can get data for an older block/state
newNonce, err = sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
if err != nil {
t.Fatalf("could not get nonce for test addr: %v", err)
}
if newNonce != nonce+uint64(1) {
t.Fatalf("received incorrect nonce. expected 1, got %v", nonce)
}
}

func TestSimulatedBackend_SendTransaction(t *testing.T) {
Expand Down

0 comments on commit d5b7d1c

Please sign in to comment.