Skip to content

Commit

Permalink
BeaconState: Use copy on write for validator index map (#4713)
Browse files Browse the repository at this point in the history
* Use copy on write for validator index map
* Merge refs/heads/master into copy-on-write-2
  • Loading branch information
prestonvanloon committed Feb 2, 2020
1 parent b7e6012 commit f432f78
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
9 changes: 9 additions & 0 deletions beacon-chain/state/getters.go
Expand Up @@ -324,6 +324,15 @@ func (b *BeaconState) ValidatorIndexByPubkey(key [48]byte) (uint64, bool) {
return idx, ok
}

func (b *BeaconState) validatorIndexMap() map[[48]byte]uint64 {
m := make(map[[48]byte]uint64, len(b.valIdxMap))

for k, v := range b.valIdxMap {
m[k] = v
}
return m
}

// PubkeyAtIndex returns the pubkey at the given
// validator index.
func (b *BeaconState) PubkeyAtIndex(idx uint64) [48]byte {
Expand Down
8 changes: 4 additions & 4 deletions beacon-chain/state/setters.go
Expand Up @@ -228,10 +228,10 @@ func (b *BeaconState) UpdateValidatorAtIndex(idx uint64, val *ethpb.Validator) e
// SetValidatorIndexByPubkey updates the validator index mapping maintained internally to
// a given input 48-byte, public key.
func (b *BeaconState) SetValidatorIndexByPubkey(pubKey [48]byte, validatorIdx uint64) {
b.lock.Lock()
b.valIdxMap[pubKey] = validatorIdx
b.markFieldAsDirty(validators)
b.lock.Unlock()
// Copy on write since this is a shared map.
m := b.validatorIndexMap()
m[pubKey] = validatorIdx
b.valIdxMap = m
}

// SetBalances for the beacon state. This PR updates the entire
Expand Down
8 changes: 3 additions & 5 deletions beacon-chain/state/types.go
Expand Up @@ -84,17 +84,15 @@ func (b *BeaconState) Copy() *BeaconState {
FinalizedCheckpoint: b.FinalizedCheckpoint(),
},
dirtyFields: make(map[fieldIndex]interface{}, 20),
valIdxMap: make(map[[48]byte]uint64, len(b.valIdxMap)),

// Copy on write validator index map.
valIdxMap: b.valIdxMap,
}

for i := range b.dirtyFields {
dst.dirtyFields[i] = true
}

for i := range b.valIdxMap {
dst.valIdxMap[i] = b.valIdxMap[i]
}

dst.merkleLayers = make([][][]byte, len(b.merkleLayers))
for i, layer := range b.merkleLayers {
dst.merkleLayers[i] = make([][]byte, len(layer))
Expand Down

0 comments on commit f432f78

Please sign in to comment.