storage: fix BoltDB batched Put()

It must copy both the value and the key because they can be reused for other
purposes between Put() and PutBatch(). This actually happens with values in
headers processing, leading to wrong data being written into the DB.

Extend the batch test to check for that.
This commit is contained in:
Roman Khimov 2019-09-22 20:11:34 +03:00
parent 5a0f08f2c0
commit ac5d2f94d3
2 changed files with 13 additions and 3 deletions

View file

@ -36,7 +36,11 @@ func (b *BoltDBBatch) Len() int {
// Put implements the Batch interface.
func (b *BoltDBBatch) Put(k, v []byte) {
b.mem[&k] = v
vcopy := make([]byte, len(v))
copy(vcopy, v)
kcopy := make([]byte, len(k))
copy(kcopy, k)
b.mem[&kcopy] = vcopy
}
// NewBoltDBStore returns a new ready to use BoltDB storage with created bucket.

View file

@ -26,11 +26,17 @@ func TestBoltDBBatch_Len(t *testing.T) {
func TestBoltDBBatch_PutBatchAndGet(t *testing.T) {
key := []byte("foo")
keycopy := make([]byte, len(key))
copy(keycopy, key)
value := []byte("bar")
batch := &BoltDBBatch{mem: map[*[]byte][]byte{&key: value}}
valuecopy := make([]byte, len(value))
copy(valuecopy, value)
boltDBStore := openStore(t)
batch := boltDBStore.Batch()
batch.Put(keycopy, valuecopy)
copy(valuecopy, key)
copy(keycopy, value)
errPut := boltDBStore.PutBatch(batch)
assert.Nil(t, errPut, "Error while PutBatch")