Skip to content

Commit d5b7d1c

Browse files
BurtonQinholiman
andauthored
accounts: add blockByNumberNoLock() to avoid double-lock (#20983)
* 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>
1 parent e0987f6 commit d5b7d1c

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,11 +133,11 @@ func (b *SimulatedBackend) stateByBlockNumber(ctx context.Context, blockNumber *
133133
if blockNumber == nil || blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) == 0 {
134134
return b.blockchain.State()
135135
}
136-
block, err := b.BlockByNumber(ctx, blockNumber)
136+
block, err := b.blockByNumberNoLock(ctx, blockNumber)
137137
if err != nil {
138138
return nil, err
139139
}
140-
return b.blockchain.StateAt(block.Hash())
140+
return b.blockchain.StateAt(block.Root())
141141
}
142142

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

247+
return b.blockByNumberNoLock(ctx, number)
248+
}
249+
250+
// blockByNumberNoLock retrieves a block from the database by number, caching it
251+
// (associated with its hash) if found without Lock.
252+
func (b *SimulatedBackend) blockByNumberNoLock(ctx context.Context, number *big.Int) (*types.Block, error) {
247253
if number == nil || number.Cmp(b.pendingBlock.Number()) == 0 {
248254
return b.blockchain.CurrentBlock(), nil
249255
}

‎accounts/abi/bind/backends/simulated_test.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,16 @@ func TestSimulatedBackend_NonceAt(t *testing.T) {
268268
if newNonce != nonce+uint64(1) {
269269
t.Errorf("received incorrect nonce. expected 1, got %v", nonce)
270270
}
271+
// create some more blocks
272+
sim.Commit()
273+
// Check that we can get data for an older block/state
274+
newNonce, err = sim.NonceAt(bgCtx, testAddr, big.NewInt(1))
275+
if err != nil {
276+
t.Fatalf("could not get nonce for test addr: %v", err)
277+
}
278+
if newNonce != nonce+uint64(1) {
279+
t.Fatalf("received incorrect nonce. expected 1, got %v", nonce)
280+
}
271281
}
272282

273283
func TestSimulatedBackend_SendTransaction(t *testing.T) {

0 commit comments

Comments
 (0)