package utils import ( "bytes" "fmt" "reflect" "sort" "strconv" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/log" "github.com/XinFinOrg/XDPoSChain/rlp" ) func Position(list []common.Address, x common.Address) int { for i, item := range list { if item == x { return i } } return -1 } func Hop(len, pre, cur int) int { switch { case pre < cur: return cur - (pre + 1) case pre > cur: return (len - pre) + (cur - 1) default: return len - 1 } } // Extract validators from byte array. func ExtractValidatorsFromBytes(byteValidators []byte) []int64 { lenValidator := len(byteValidators) / M2ByteLength var validators []int64 for i := 0; i < lenValidator; i++ { trimByte := bytes.Trim(byteValidators[i*M2ByteLength:(i+1)*M2ByteLength], "\x00") intNumber, err := strconv.Atoi(string(trimByte)) if err != nil { log.Error("Can not convert string to integer", "error", err) return []int64{} } validators = append(validators, int64(intNumber)) } return validators } // compare 2 signers lists // return true if they are same elements, otherwise return false func CompareSignersLists(list1 []common.Address, list2 []common.Address) bool { if len(list1) == 0 && len(list2) == 0 { return true } sort.Slice(list1, func(i, j int) bool { return list1[i].String() <= list1[j].String() }) sort.Slice(list2, func(i, j int) bool { return list2[i].String() <= list2[j].String() }) return reflect.DeepEqual(list1, list2) } // Decode extra fields for consensus version >= 2 (XDPoS 2.0 and future versions) func DecodeBytesExtraFields(b []byte, val interface{}) error { if len(b) == 0 { return fmt.Errorf("extra field is 0 length") } switch b[0] { case 1: return fmt.Errorf("consensus version 1 is not applicable for decoding extra fields") case 2: return rlp.DecodeBytes(b[1:], val) default: return fmt.Errorf("consensus version %d is not defined", b[0]) } }