github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/ledger/common/convert/convert.go (about)

     1  package convert
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/onflow/flow-go/ledger"
     7  	"github.com/onflow/flow-go/model/flow"
     8  )
     9  
    10  // UnexpectedLedgerKeyFormat is returned when a ledger key is not in the expected format
    11  var UnexpectedLedgerKeyFormat = fmt.Errorf("unexpected ledger key format")
    12  
    13  // LedgerKeyToRegisterID converts a ledger key to a register id
    14  // returns an UnexpectedLedgerKeyFormat error if the key is not in the expected format
    15  func LedgerKeyToRegisterID(key ledger.Key) (flow.RegisterID, error) {
    16  	parts := key.KeyParts
    17  	if len(parts) != 2 ||
    18  		parts[0].Type != ledger.KeyPartOwner ||
    19  		parts[1].Type != ledger.KeyPartKey {
    20  		return flow.RegisterID{}, fmt.Errorf("ledger key %s: %w", key.String(), UnexpectedLedgerKeyFormat)
    21  	}
    22  
    23  	return flow.NewRegisterID(
    24  		flow.BytesToAddress(parts[0].Value),
    25  		string(parts[1].Value),
    26  	), nil
    27  }
    28  
    29  // RegisterIDToLedgerKey converts a register id to a ledger key
    30  func RegisterIDToLedgerKey(registerID flow.RegisterID) ledger.Key {
    31  	return ledger.Key{
    32  		KeyParts: []ledger.KeyPart{
    33  			{
    34  				Type:  ledger.KeyPartOwner,
    35  				Value: []byte(registerID.Owner),
    36  			},
    37  			{
    38  				Type:  ledger.KeyPartKey,
    39  				Value: []byte(registerID.Key),
    40  			},
    41  		},
    42  	}
    43  }
    44  
    45  // PayloadToRegister converts a payload to a register id and value
    46  func PayloadToRegister(payload *ledger.Payload) (flow.RegisterID, flow.RegisterValue, error) {
    47  	key, err := payload.Key()
    48  	if err != nil {
    49  		return flow.RegisterID{}, flow.RegisterValue{}, fmt.Errorf("could not parse register key from payload: %w", err)
    50  	}
    51  	regID, err := LedgerKeyToRegisterID(key)
    52  	if err != nil {
    53  		return flow.RegisterID{}, flow.RegisterValue{}, fmt.Errorf("could not convert register key into register id: %w", err)
    54  	}
    55  
    56  	return regID, payload.Value(), nil
    57  }