contract_relationship.go 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
package vm

import (
	"bytes"
	"errors"
	"go-ethereum-advance/common"
	"go-ethereum-advance/core/vm/protoc"
	"go-ethereum-advance/graph"
	"go-ethereum-advance/log"
	"go-ethereum-advance/params"
	"github.com/golang/protobuf/proto"
)

type contractRelationship struct {}

func (c *contractRelationship) RequiredGas(input []byte) uint64 {
	return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
}

func (c *contractRelationship) Run(ctx *PrecompiledContractContext,input []byte) ([]byte, error) {
	info := &protoc.RelationInfo{}
	err := proto.Unmarshal(input,info)
	if err != nil {
		log.Info("contract relationship Run err","err info:",err.Error())
		return nil, err
	}

	contractAddr := common.HexToAddress(info.ContractAddress)
	keyHash := contractAddr.Hash()
	senderAddr := common.HexToAddress(info.OwnerAddress)
	contractOwnerAddr := common.BytesToAddress([]byte("contract_owner_record"))

	value := ctx.Evm.StateDB.GetState(contractOwnerAddr,keyHash)
	if !bytes.Equal(value.Bytes(),senderAddr.Bytes()) {
		//更新关系的发送者与记录不相等
		return nil,errors.New("relationship tx sender not match with record")
	}

	if len(info.Relations) == 0 {
		return nil,errors.New("registration relationship must not be empty")
	}

	graphRela := graph.NewSparseGraphOnce()
	contactsAddrs := make([]common.Address,len(info.Relations))
	for i,addr := range info.Relations{
		contactsAddrs[i] = common.HexToAddress(addr)
	}

	switch info.Type {
	case protoc.RelationType_AddRelation:
		//添加关系
		index,ok := graphRela.Retrieve[contractAddr]
		if ok {
			//有注册关系 需要去重以后添加
			oldContracts := graphRela.Graph[index]
			newContracts := append(oldContracts, contactsAddrs...)
			newContracts = graph.RemoveRepeatedElement(newContracts)
			graphRela.Graph[index] = newContracts
		}else {
			//没有注册关系 将关系放入列表最后
			index = len(graphRela.Graph)
			newConntracts := graph.RemoveRepeatedElement(contactsAddrs)
			graphRela.Graph[index] = newConntracts
			graphRela.Retrieve[contractAddr] = index
		}

	case protoc.RelationType_DelRelation:
		//删除关系
		index,ok := graphRela.Retrieve[contractAddr]
		if ok {
			//找到了关系 进行剔除
			oldContracts := graphRela.Graph[index]
			for _,addr := range contactsAddrs {
				ind,ok := graph.Contains(oldContracts,addr)
				if ok {
					if ind == 0 {
						oldContracts = oldContracts[0:]
					}else {
						oldContracts = append(oldContracts[:ind],oldContracts[ind+1:]...)
					}
				}
			}
		}else {
			//没有找到对应的关系需要报错
			return nil,errors.New(graph.ErrorAddressNotExit)
		}
	}

	return []byte{},nil
}