github.com/nspcc-dev/neo-go@v0.105.2-0.20240517133400-6be757af3eba/pkg/neorpc/result/block.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 "github.com/nspcc-dev/neo-go/pkg/util" 9 ) 10 11 type ( 12 // Block wrapper used for the representation of 13 // block.Block / block.Base on the RPC Server. 14 Block struct { 15 block.Block 16 BlockMetadata 17 } 18 19 // BlockMetadata is an additional metadata added to the standard 20 // block.Block. 21 BlockMetadata struct { 22 Size int `json:"size"` 23 NextBlockHash *util.Uint256 `json:"nextblockhash,omitempty"` 24 Confirmations uint32 `json:"confirmations"` 25 } 26 ) 27 28 // MarshalJSON implements the json.Marshaler interface. 29 func (b Block) MarshalJSON() ([]byte, error) { 30 output, err := json.Marshal(b.BlockMetadata) 31 if err != nil { 32 return nil, err 33 } 34 baseBytes, err := json.Marshal(b.Block) 35 if err != nil { 36 return nil, err 37 } 38 39 // We have to keep both "fields" at the same level in json in order to 40 // match C# API, so there's no way to marshall Block correctly with 41 // the standard json.Marshaller tool. 42 if output[len(output)-1] != '}' || baseBytes[0] != '{' { 43 return nil, errors.New("can't merge internal jsons") 44 } 45 output[len(output)-1] = ',' 46 output = append(output, baseBytes[1:]...) 47 return output, nil 48 } 49 50 // UnmarshalJSON implements the json.Unmarshaler interface. 51 func (b *Block) UnmarshalJSON(data []byte) error { 52 // As block.Block and BlockMetadata are at the same level in json, 53 // do unmarshalling separately for both structs. 54 meta := new(BlockMetadata) 55 err := json.Unmarshal(data, meta) 56 if err != nil { 57 return err 58 } 59 err = json.Unmarshal(data, &b.Block) 60 if err != nil { 61 return err 62 } 63 b.BlockMetadata = *meta 64 return nil 65 }