github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/neorpc/result/block_header.go (about)

     1  package result
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  
     7  	"github.com/nspcc-dev/neo-go/pkg/core/block"
     8  )
     9  
    10  type (
    11  	// Header wrapper used for a representation of
    12  	// the block header on the RPC Server.
    13  	Header struct {
    14  		block.Header
    15  		BlockMetadata
    16  	}
    17  )
    18  
    19  // MarshalJSON implements the json.Marshaler interface.
    20  func (h Header) MarshalJSON() ([]byte, error) {
    21  	output, err := json.Marshal(h.BlockMetadata)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	baseBytes, err := json.Marshal(h.Header)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	// We have to keep both "fields" at the same level in json in order to
    31  	// match C# API, so there's no way to marshall Block correctly with
    32  	// standard json.Marshaller tool.
    33  	if output[len(output)-1] != '}' || baseBytes[0] != '{' {
    34  		return nil, errors.New("can't merge internal jsons")
    35  	}
    36  	output[len(output)-1] = ','
    37  	output = append(output, baseBytes[1:]...)
    38  	return output, nil
    39  }
    40  
    41  // UnmarshalJSON implements the json.Unmarshaler interface.
    42  func (h *Header) UnmarshalJSON(data []byte) error {
    43  	// As block.Block and BlockMetadata are at the same level in json,
    44  	// do unmarshalling separately for both structs.
    45  	meta := new(BlockMetadata)
    46  	err := json.Unmarshal(data, meta)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	err = json.Unmarshal(data, &h.Header)
    51  	if err != nil {
    52  		return err
    53  	}
    54  	h.BlockMetadata = *meta
    55  	return nil
    56  }