github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/x/wasm/types/json_matching.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	sdkerrors "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types/errors"
     7  )
     8  
     9  // IsJSONObjectWithTopLevelKey checks if the given bytes are a valid JSON object
    10  // with exactly one top-level key that is contained in the list of allowed keys.
    11  func IsJSONObjectWithTopLevelKey(jsonBytes []byte, allowedKeys []string) error {
    12  	document := map[string]interface{}{}
    13  	if err := json.Unmarshal(jsonBytes, &document); err != nil {
    14  		return sdkerrors.Wrap(ErrNotAJSONObject, "failed to unmarshal JSON to map")
    15  	}
    16  
    17  	if len(document) == 0 {
    18  		return sdkerrors.Wrap(ErrNoTopLevelKey, "JSON object has no top-level key")
    19  	}
    20  
    21  	if len(document) > 1 {
    22  		return sdkerrors.Wrap(ErrMultipleTopLevelKeys, "JSON object has multiple top-level keys")
    23  	}
    24  
    25  	// Loop is executed exactly once
    26  	for topLevelKey := range document {
    27  		for _, allowedKey := range allowedKeys {
    28  			if allowedKey == topLevelKey {
    29  				return nil
    30  			}
    31  		}
    32  		return sdkerrors.Wrapf(ErrTopKevelKeyNotAllowed, "JSON object has a top-level key which is not allowed: '%s'", topLevelKey)
    33  	}
    34  
    35  	panic("Reached unreachable code. This is a bug.")
    36  }