github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+incompatible/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  	"encoding/json"
    21  	"fmt"
    22  	"io"
    23  	"reflect"
    24  	"strings"
    25  
    26  	"github.com/ethereum/go-ethereum/common"
    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  	var method Method
    58  
    59  	if name == "" {
    60  		method = abi.Constructor
    61  	} else {
    62  		m, exist := abi.Methods[name]
    63  		if !exist {
    64  			return nil, fmt.Errorf("method '%s' not found", name)
    65  		}
    66  		method = m
    67  	}
    68  	arguments, err := method.pack(args...)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	// Pack up the method ID too if not a constructor and return
    73  	if name == "" {
    74  		return arguments, nil
    75  	}
    76  	return append(method.Id(), arguments...), nil
    77  }
    78  
    79  // these variable are used to determine certain types during type assertion for
    80  // assignment.
    81  var (
    82  	r_interSlice = reflect.TypeOf([]interface{}{})
    83  	r_hash       = reflect.TypeOf(common.Hash{})
    84  	r_bytes      = reflect.TypeOf([]byte{})
    85  	r_byte       = reflect.TypeOf(byte(0))
    86  )
    87  
    88  // Unpack output in v according to the abi specification
    89  func (abi ABI) Unpack(v interface{}, name string, output []byte) error {
    90  	var method = abi.Methods[name]
    91  
    92  	if len(output) == 0 {
    93  		return fmt.Errorf("abi: unmarshalling empty output")
    94  	}
    95  
    96  	// make sure the passed value is a pointer
    97  	valueOf := reflect.ValueOf(v)
    98  	if reflect.Ptr != valueOf.Kind() {
    99  		return fmt.Errorf("abi: Unpack(non-pointer %T)", v)
   100  	}
   101  
   102  	var (
   103  		value = valueOf.Elem()
   104  		typ   = value.Type()
   105  	)
   106  
   107  	if len(method.Outputs) > 1 {
   108  		switch value.Kind() {
   109  		// struct will match named return values to the struct's field
   110  		// names
   111  		case reflect.Struct:
   112  			for i := 0; i < len(method.Outputs); i++ {
   113  				marshalledValue, err := toGoType(i, method.Outputs[i], output)
   114  				if err != nil {
   115  					return err
   116  				}
   117  				reflectValue := reflect.ValueOf(marshalledValue)
   118  
   119  				for j := 0; j < typ.NumField(); j++ {
   120  					field := typ.Field(j)
   121  					// TODO read tags: `abi:"fieldName"`
   122  					if field.Name == strings.ToUpper(method.Outputs[i].Name[:1])+method.Outputs[i].Name[1:] {
   123  						if err := set(value.Field(j), reflectValue, method.Outputs[i]); err != nil {
   124  							return err
   125  						}
   126  					}
   127  				}
   128  			}
   129  		case reflect.Slice:
   130  			if !value.Type().AssignableTo(r_interSlice) {
   131  				return fmt.Errorf("abi: cannot marshal tuple in to slice %T (only []interface{} is supported)", v)
   132  			}
   133  
   134  			// if the slice already contains values, set those instead of the interface slice itself.
   135  			if value.Len() > 0 {
   136  				if len(method.Outputs) > value.Len() {
   137  					return fmt.Errorf("abi: cannot marshal in to slices of unequal size (require: %v, got: %v)", len(method.Outputs), value.Len())
   138  				}
   139  
   140  				for i := 0; i < len(method.Outputs); i++ {
   141  					marshalledValue, err := toGoType(i, method.Outputs[i], output)
   142  					if err != nil {
   143  						return err
   144  					}
   145  					reflectValue := reflect.ValueOf(marshalledValue)
   146  					if err := set(value.Index(i).Elem(), reflectValue, method.Outputs[i]); err != nil {
   147  						return err
   148  					}
   149  				}
   150  				return nil
   151  			}
   152  
   153  			// create a new slice and start appending the unmarshalled
   154  			// values to the new interface slice.
   155  			z := reflect.MakeSlice(typ, 0, len(method.Outputs))
   156  			for i := 0; i < len(method.Outputs); i++ {
   157  				marshalledValue, err := toGoType(i, method.Outputs[i], output)
   158  				if err != nil {
   159  					return err
   160  				}
   161  				z = reflect.Append(z, reflect.ValueOf(marshalledValue))
   162  			}
   163  			value.Set(z)
   164  		default:
   165  			return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ)
   166  		}
   167  
   168  	} else {
   169  		marshalledValue, err := toGoType(0, method.Outputs[0], output)
   170  		if err != nil {
   171  			return err
   172  		}
   173  		if err := set(value, reflect.ValueOf(marshalledValue), method.Outputs[0]); err != nil {
   174  			return err
   175  		}
   176  	}
   177  
   178  	return nil
   179  }
   180  
   181  func (abi *ABI) UnmarshalJSON(data []byte) error {
   182  	var fields []struct {
   183  		Type      string
   184  		Name      string
   185  		Constant  bool
   186  		Indexed   bool
   187  		Anonymous bool
   188  		Inputs    []Argument
   189  		Outputs   []Argument
   190  	}
   191  
   192  	if err := json.Unmarshal(data, &fields); err != nil {
   193  		return err
   194  	}
   195  
   196  	abi.Methods = make(map[string]Method)
   197  	abi.Events = make(map[string]Event)
   198  	for _, field := range fields {
   199  		switch field.Type {
   200  		case "constructor":
   201  			abi.Constructor = Method{
   202  				Inputs: field.Inputs,
   203  			}
   204  		// empty defaults to function according to the abi spec
   205  		case "function", "":
   206  			abi.Methods[field.Name] = Method{
   207  				Name:    field.Name,
   208  				Const:   field.Constant,
   209  				Inputs:  field.Inputs,
   210  				Outputs: field.Outputs,
   211  			}
   212  		case "event":
   213  			abi.Events[field.Name] = Event{
   214  				Name:      field.Name,
   215  				Anonymous: field.Anonymous,
   216  				Inputs:    field.Inputs,
   217  			}
   218  		}
   219  	}
   220  
   221  	return nil
   222  }