github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/accounts/abi/abi.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package abi
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"fmt"
    23  	"github.com/intfoundation/intchain/common"
    24  	"github.com/intfoundation/intchain/crypto"
    25  	"io"
    26  	"reflect"
    27  )
    28  
    29  // The ABI holds information about a contract's context and available
    30  // invokable methods. It will allow you to type check function calls and
    31  // packs data accordingly.
    32  type ABI struct {
    33  	Constructor Method
    34  	Methods     map[string]Method
    35  	Events      map[string]Event
    36  }
    37  
    38  // JSON returns a parsed ABI interface and error if it failed.
    39  func JSON(reader io.Reader) (ABI, error) {
    40  	dec := json.NewDecoder(reader)
    41  
    42  	var abi ABI
    43  	if err := dec.Decode(&abi); err != nil {
    44  		return ABI{}, err
    45  	}
    46  
    47  	return abi, nil
    48  }
    49  
    50  // Pack the given method name to conform the ABI. Method call's data
    51  // will consist of method_id, args0, arg1, ... argN. Method id consists
    52  // of 4 bytes and arguments are all 32 bytes.
    53  // Method ids are created from the first 4 bytes of the hash of the
    54  // methods string signature. (signature = baz(uint32,string32))
    55  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    56  	// Fetch the ABI of the requested method
    57  	if name == "" {
    58  		// constructor
    59  		arguments, err := abi.Constructor.Inputs.Pack(args...)
    60  		if err != nil {
    61  			return nil, err
    62  		}
    63  		return arguments, nil
    64  
    65  	}
    66  	method, exist := abi.Methods[name]
    67  	if !exist {
    68  		return nil, fmt.Errorf("method '%s' not found", name)
    69  	}
    70  
    71  	arguments, err := method.Inputs.Pack(args...)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  	// Pack up the method ID too if not a constructor and return
    76  	return append(method.ID(), arguments...), nil
    77  }
    78  
    79  // Unpack output in v according to the abi specification
    80  func (abi ABI) Unpack(v interface{}, name string, data []byte) (err error) {
    81  	// since there can't be naming collisions with contracts and events,
    82  	// we need to decide whether we're calling a method or an event
    83  	if method, ok := abi.Methods[name]; ok {
    84  		if len(data)%32 != 0 {
    85  			return fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
    86  		}
    87  		return method.Outputs.Unpack(v, data)
    88  	}
    89  	if event, ok := abi.Events[name]; ok {
    90  		return event.Inputs.Unpack(v, data)
    91  	}
    92  	return fmt.Errorf("abi: could not locate named method or event")
    93  }
    94  
    95  // UnpackIntoMap unpacks a log into the provided map[string]interface{}
    96  func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
    97  	// since there can't be naming collisions with contracts and events,
    98  	// we need to decide whether we're calling a method or an event
    99  	if method, ok := abi.Methods[name]; ok {
   100  		if len(data)%32 != 0 {
   101  			return fmt.Errorf("abi: improperly formatted output")
   102  		}
   103  		return method.Outputs.UnpackIntoMap(v, data)
   104  	}
   105  	if event, ok := abi.Events[name]; ok {
   106  		return event.Inputs.UnpackIntoMap(v, data)
   107  	}
   108  	return fmt.Errorf("abi: could not locate named method or event")
   109  }
   110  
   111  // UnpackMethodInputs output in v according to the abi specification
   112  func (abi ABI) UnpackMethodInputs(v interface{}, name string, input []byte) (err error) {
   113  	if len(input) == 0 {
   114  		return fmt.Errorf("abi: unmarshalling empty output")
   115  	}
   116  	if method, ok := abi.Methods[name]; ok {
   117  		return method.Inputs.Unpack(v, input)
   118  	}
   119  	return fmt.Errorf("abi: could not locate named method or event")
   120  }
   121  
   122  // UnmarshalJSON implements json.Unmarshaler interface
   123  func (abi *ABI) UnmarshalJSON(data []byte) error {
   124  	var fields []struct {
   125  		Type            string
   126  		Name            string
   127  		Constant        bool
   128  		StateMutability string
   129  		Anonymous       bool
   130  		Inputs          []Argument
   131  		Outputs         []Argument
   132  	}
   133  
   134  	if err := json.Unmarshal(data, &fields); err != nil {
   135  		return err
   136  	}
   137  
   138  	abi.Methods = make(map[string]Method)
   139  	abi.Events = make(map[string]Event)
   140  	for _, field := range fields {
   141  		switch field.Type {
   142  		case "constructor":
   143  			abi.Constructor = Method{
   144  				Inputs: field.Inputs,
   145  			}
   146  		// empty defaults to function according to the abi spec
   147  		case "function", "":
   148  			name := field.Name
   149  			_, ok := abi.Methods[name]
   150  			for idx := 0; ok; idx++ {
   151  				name = fmt.Sprintf("%s%d", field.Name, idx)
   152  				_, ok = abi.Methods[name]
   153  			}
   154  			isConst := field.Constant || field.StateMutability == "pure" || field.StateMutability == "view"
   155  			abi.Methods[name] = Method{
   156  				Name:    name,
   157  				RawName: field.Name,
   158  				Const:   isConst,
   159  				Inputs:  field.Inputs,
   160  				Outputs: field.Outputs,
   161  			}
   162  		case "event":
   163  			name := field.Name
   164  			_, ok := abi.Events[name]
   165  			for idx := 0; ok; idx++ {
   166  				name = fmt.Sprintf("%s%d", field.Name, idx)
   167  				_, ok = abi.Events[name]
   168  			}
   169  			abi.Events[name] = Event{
   170  				Name:      name,
   171  				RawName:   field.Name,
   172  				Anonymous: field.Anonymous,
   173  				Inputs:    field.Inputs,
   174  			}
   175  		}
   176  	}
   177  
   178  	return nil
   179  }
   180  
   181  // MethodById looks up a method by the 4-byte id
   182  // returns nil if none found
   183  func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
   184  	if len(sigdata) < 4 {
   185  		return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
   186  	}
   187  	for _, method := range abi.Methods {
   188  		if bytes.Equal(method.ID(), sigdata[:4]) {
   189  			return &method, nil
   190  		}
   191  	}
   192  	return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
   193  }
   194  
   195  // EventByID looks an event up by its topic hash in the
   196  // ABI and returns nil if none found.
   197  func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
   198  	for _, event := range abi.Events {
   199  		if bytes.Equal(event.ID().Bytes(), topic.Bytes()) {
   200  			return &event, nil
   201  		}
   202  	}
   203  	return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
   204  }
   205  
   206  // revertSelector is a special function selector for revert reason unpacking.
   207  var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
   208  
   209  // UnpackRevert resolves the abi-encoded revert reason. According to the solidity
   210  // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
   211  // the provided revert reason is abi-encoded as if it were a call to a function
   212  // `Error(string)`. So it's a special tool for it.
   213  func UnpackRevert(data []byte) (string, error) {
   214  	if len(data) < 4 {
   215  		return "", fmt.Errorf("invalid data for unpacking")
   216  	}
   217  	if !bytes.Equal(data[:4], revertSelector) {
   218  		return "", fmt.Errorf("invalid data for unpacking")
   219  	}
   220  	typ, _ := NewType("string", "", nil)
   221  	unpacked, err := (Arguments{{Type: typ}}).UnpackForRevert(reflect.New(reflect.TypeOf(typ)).Interface(), data[4:])
   222  	if err != nil {
   223  		return "", err
   224  	}
   225  	return unpacked[0].(string), nil
   226  }