github.com/amazechain/amc@v0.1.3/accounts/abi/abi.go (about)

     1  // Copyright 2023 The AmazeChain Authors
     2  // This file is part of the AmazeChain library.
     3  //
     4  // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package abi
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"github.com/amazechain/amc/common/crypto"
    25  	"github.com/amazechain/amc/common/types"
    26  	"io"
    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  	Errors      map[string]Error
    37  
    38  	// Additional "special" functions introduced in solidity v0.6.0.
    39  	// It's separated from the original default fallback. Each contract
    40  	// can only define one fallback and receive function.
    41  	Fallback Method // Note it's also used to represent legacy fallback before v0.6.0
    42  	Receive  Method
    43  }
    44  
    45  // JSON returns a parsed ABI interface and error if it failed.
    46  func JSON(reader io.Reader) (ABI, error) {
    47  	dec := json.NewDecoder(reader)
    48  
    49  	var abi ABI
    50  	if err := dec.Decode(&abi); err != nil {
    51  		return ABI{}, err
    52  	}
    53  	return abi, nil
    54  }
    55  
    56  // Pack the given method name to conform the ABI. Method call's data
    57  // will consist of method_id, args0, arg1, ... argN. Method id consists
    58  // of 4 bytes and arguments are all 32 bytes.
    59  // Method ids are created from the first 4 bytes of the hash of the
    60  // methods string signature. (signature = baz(uint32,string32))
    61  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    62  	// Fetch the ABI of the requested method
    63  	if name == "" {
    64  		// constructor
    65  		arguments, err := abi.Constructor.Inputs.Pack(args...)
    66  		if err != nil {
    67  			return nil, err
    68  		}
    69  		return arguments, nil
    70  	}
    71  	method, exist := abi.Methods[name]
    72  	if !exist {
    73  		return nil, fmt.Errorf("method '%s' not found", name)
    74  	}
    75  	arguments, err := method.Inputs.Pack(args...)
    76  	if err != nil {
    77  		return nil, err
    78  	}
    79  	// Pack up the method ID too if not a constructor and return
    80  	return append(method.ID, arguments...), nil
    81  }
    82  
    83  func (abi ABI) getArguments(name string, data []byte) (Arguments, error) {
    84  	// since there can't be naming collisions with contracts and events,
    85  	// we need to decide whether we're calling a method or an event
    86  	var args Arguments
    87  	if method, ok := abi.Methods[name]; ok {
    88  		if len(data)%32 != 0 {
    89  			return nil, fmt.Errorf("abi: improperly formatted output: %q - Bytes: %+v", data, data)
    90  		}
    91  		args = method.Outputs
    92  	}
    93  	if event, ok := abi.Events[name]; ok {
    94  		args = event.Inputs
    95  	}
    96  	if args == nil {
    97  		return nil, fmt.Errorf("abi: could not locate named method or event: %s", name)
    98  	}
    99  	return args, nil
   100  }
   101  
   102  // Unpack unpacks the output according to the abi specification.
   103  func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) {
   104  	args, err := abi.getArguments(name, data)
   105  	if err != nil {
   106  		return nil, err
   107  	}
   108  	return args.Unpack(data)
   109  }
   110  
   111  // UnpackIntoInterface unpacks the output in v according to the abi specification.
   112  // It performs an additional copy. Please only use, if you want to unpack into a
   113  // structure that does not strictly conform to the abi structure (e.g. has additional arguments)
   114  func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error {
   115  	args, err := abi.getArguments(name, data)
   116  	if err != nil {
   117  		return err
   118  	}
   119  	unpacked, err := args.Unpack(data)
   120  	if err != nil {
   121  		return err
   122  	}
   123  	return args.Copy(v, unpacked)
   124  }
   125  
   126  // UnpackIntoMap unpacks a log into the provided map[string]interface{}.
   127  func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
   128  	args, err := abi.getArguments(name, data)
   129  	if err != nil {
   130  		return err
   131  	}
   132  	return args.UnpackIntoMap(v, data)
   133  }
   134  
   135  // UnmarshalJSON implements json.Unmarshaler interface.
   136  func (abi *ABI) UnmarshalJSON(data []byte) error {
   137  	var fields []struct {
   138  		Type    string
   139  		Name    string
   140  		Inputs  []Argument
   141  		Outputs []Argument
   142  
   143  		// Status indicator which can be: "pure", "view",
   144  		// "nonpayable" or "payable".
   145  		StateMutability string
   146  
   147  		// Deprecated Status indicators, but removed in v0.6.0.
   148  		Constant bool // True if function is either pure or view
   149  		Payable  bool // True if function is payable
   150  
   151  		// Event relevant indicator represents the event is
   152  		// declared as anonymous.
   153  		Anonymous bool
   154  	}
   155  	if err := json.Unmarshal(data, &fields); err != nil {
   156  		return err
   157  	}
   158  	abi.Methods = make(map[string]Method)
   159  	abi.Events = make(map[string]Event)
   160  	abi.Errors = make(map[string]Error)
   161  	for _, field := range fields {
   162  		switch field.Type {
   163  		case "constructor":
   164  			abi.Constructor = NewMethod("", "", Constructor, field.StateMutability, field.Constant, field.Payable, field.Inputs, nil)
   165  		case "function":
   166  			name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Methods[s]; return ok })
   167  			abi.Methods[name] = NewMethod(name, field.Name, Function, field.StateMutability, field.Constant, field.Payable, field.Inputs, field.Outputs)
   168  		case "fallback":
   169  			// New introduced function type in v0.6.0, check more detail
   170  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   171  			if abi.HasFallback() {
   172  				return errors.New("only single fallback is allowed")
   173  			}
   174  			abi.Fallback = NewMethod("", "", Fallback, field.StateMutability, field.Constant, field.Payable, nil, nil)
   175  		case "receive":
   176  			// New introduced function type in v0.6.0, check more detail
   177  			// here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function
   178  			if abi.HasReceive() {
   179  				return errors.New("only single receive is allowed")
   180  			}
   181  			if field.StateMutability != "payable" {
   182  				return errors.New("the statemutability of receive can only be payable")
   183  			}
   184  			abi.Receive = NewMethod("", "", Receive, field.StateMutability, field.Constant, field.Payable, nil, nil)
   185  		case "event":
   186  			name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Events[s]; return ok })
   187  			abi.Events[name] = NewEvent(name, field.Name, field.Anonymous, field.Inputs)
   188  		case "error":
   189  			// Errors cannot be overloaded or overridden but are inherited,
   190  			// no need to resolve the name conflict here.
   191  			abi.Errors[field.Name] = NewError(field.Name, field.Inputs)
   192  		default:
   193  			return fmt.Errorf("abi: could not recognize type %v of field %v", field.Type, field.Name)
   194  		}
   195  	}
   196  	return nil
   197  }
   198  
   199  // MethodById looks up a method by the 4-byte id,
   200  // returns nil if none found.
   201  func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
   202  	if len(sigdata) < 4 {
   203  		return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
   204  	}
   205  	for _, method := range abi.Methods {
   206  		if bytes.Equal(method.ID, sigdata[:4]) {
   207  			return &method, nil
   208  		}
   209  	}
   210  	return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
   211  }
   212  
   213  // EventByID looks an event up by its topic hash in the
   214  // ABI and returns nil if none found.
   215  func (abi *ABI) EventByID(topic types.Hash) (*Event, error) {
   216  	for _, event := range abi.Events {
   217  		if bytes.Equal(event.ID.Bytes(), topic.Bytes()) {
   218  			return &event, nil
   219  		}
   220  	}
   221  	return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
   222  }
   223  
   224  // HasFallback returns an indicator whether a fallback function is included.
   225  func (abi *ABI) HasFallback() bool {
   226  	return abi.Fallback.Type == Fallback
   227  }
   228  
   229  // HasReceive returns an indicator whether a receive function is included.
   230  func (abi *ABI) HasReceive() bool {
   231  	return abi.Receive.Type == Receive
   232  }
   233  
   234  // revertSelector is a special function selector for revert reason unpacking.
   235  var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4]
   236  
   237  // UnpackRevert resolves the abi-encoded revert reason. According to the solidity
   238  // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert,
   239  // the provided revert reason is abi-encoded as if it were a call to a function
   240  // `Error(string)`. So it's a special tool for it.
   241  func UnpackRevert(data []byte) (string, error) {
   242  	if len(data) < 4 {
   243  		return "", errors.New("invalid data for unpacking")
   244  	}
   245  	if !bytes.Equal(data[:4], revertSelector) {
   246  		return "", errors.New("invalid data for unpacking")
   247  	}
   248  	typ, _ := NewType("string", "", nil)
   249  	unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:])
   250  	if err != nil {
   251  		return "", err
   252  	}
   253  	return unpacked[0].(string), nil
   254  }