neo-go/pkg/core/state/contract.go

81 lines
1.9 KiB
Go
Raw Normal View History

package state
import (
2020-06-09 09:12:56 +00:00
"encoding/json"
"errors"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/io"
2020-06-09 09:12:56 +00:00
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
"github.com/nspcc-dev/neo-go/pkg/util"
)
// Contract holds information about a smart contract in the NEO blockchain.
type Contract struct {
2020-06-09 09:12:56 +00:00
ID int32
Script []byte
Manifest manifest.Manifest
scriptHash util.Uint160
}
// DecodeBinary implements Serializable interface.
func (cs *Contract) DecodeBinary(br *io.BinReader) {
2020-06-09 09:12:56 +00:00
cs.ID = int32(br.ReadU32LE())
cs.Script = br.ReadVarBytes()
2020-06-09 09:12:56 +00:00
cs.Manifest.DecodeBinary(br)
cs.createHash()
}
// EncodeBinary implements Serializable interface.
func (cs *Contract) EncodeBinary(bw *io.BinWriter) {
2020-06-09 09:12:56 +00:00
bw.WriteU32LE(uint32(cs.ID))
bw.WriteVarBytes(cs.Script)
2020-06-09 09:12:56 +00:00
cs.Manifest.EncodeBinary(bw)
}
// ScriptHash returns a contract script hash.
func (cs *Contract) ScriptHash() util.Uint160 {
if cs.scriptHash.Equals(util.Uint160{}) {
cs.createHash()
}
return cs.scriptHash
}
// createHash creates contract script hash.
func (cs *Contract) createHash() {
cs.scriptHash = hash.Hash160(cs.Script)
}
2020-06-09 09:12:56 +00:00
type contractJSON struct {
ID int32 `json:"id"`
Script []byte `json:"script"`
Manifest *manifest.Manifest `json:"manifest"`
ScriptHash util.Uint160 `json:"hash"`
}
// MarshalJSON implements json.Marshaler.
func (cs *Contract) MarshalJSON() ([]byte, error) {
return json.Marshal(&contractJSON{
ID: cs.ID,
Script: cs.Script,
Manifest: &cs.Manifest,
ScriptHash: cs.ScriptHash(),
})
}
// UnmarshalJSON implements json.Unmarshaler.
func (cs *Contract) UnmarshalJSON(data []byte) error {
var cj contractJSON
if err := json.Unmarshal(data, &cj); err != nil {
return err
} else if cj.Manifest == nil {
return errors.New("empty manifest")
}
cs.ID = cj.ID
cs.Script = cj.Script
cs.Manifest = *cj.Manifest
cs.createHash()
return nil
}