github.com/prysmaticlabs/prysm@v1.4.4/beacon-chain/state/v1/setters_state.go (about)

     1  package v1
     2  
     3  import (
     4  	"github.com/pkg/errors"
     5  	"github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil"
     6  )
     7  
     8  // SetStateRoots for the beacon state. Updates the state roots
     9  // to a new value by overwriting the previous value.
    10  func (b *BeaconState) SetStateRoots(val [][]byte) error {
    11  	if !b.hasInnerState() {
    12  		return ErrNilInnerState
    13  	}
    14  	b.lock.Lock()
    15  	defer b.lock.Unlock()
    16  
    17  	b.sharedFieldReferences[stateRoots].MinusRef()
    18  	b.sharedFieldReferences[stateRoots] = stateutil.NewRef(1)
    19  
    20  	b.state.StateRoots = val
    21  	b.markFieldAsDirty(stateRoots)
    22  	b.rebuildTrie[stateRoots] = true
    23  	return nil
    24  }
    25  
    26  // UpdateStateRootAtIndex for the beacon state. Updates the state root
    27  // at a specific index to a new value.
    28  func (b *BeaconState) UpdateStateRootAtIndex(idx uint64, stateRoot [32]byte) error {
    29  	if !b.hasInnerState() {
    30  		return ErrNilInnerState
    31  	}
    32  
    33  	b.lock.RLock()
    34  	if uint64(len(b.state.StateRoots)) <= idx {
    35  		b.lock.RUnlock()
    36  		return errors.Errorf("invalid index provided %d", idx)
    37  	}
    38  	b.lock.RUnlock()
    39  
    40  	b.lock.Lock()
    41  	defer b.lock.Unlock()
    42  
    43  	// Check if we hold the only reference to the shared state roots slice.
    44  	r := b.state.StateRoots
    45  	if ref := b.sharedFieldReferences[stateRoots]; ref.Refs() > 1 {
    46  		// Copy elements in underlying array by reference.
    47  		r = make([][]byte, len(b.state.StateRoots))
    48  		copy(r, b.state.StateRoots)
    49  		ref.MinusRef()
    50  		b.sharedFieldReferences[stateRoots] = stateutil.NewRef(1)
    51  	}
    52  
    53  	r[idx] = stateRoot[:]
    54  	b.state.StateRoots = r
    55  
    56  	b.markFieldAsDirty(stateRoots)
    57  	b.addDirtyIndices(stateRoots, []uint64{idx})
    58  	return nil
    59  }