From 8eb9de521b0a18dd0a28a857778317b9b25a93b5 Mon Sep 17 00:00:00 2001 From: wincenteam Date: Thu, 20 Feb 2020 14:22:12 +0800 Subject: [PATCH] Revert "add abigen" This reverts commit e3dcef905f41254b6aeb3e8327b3df9dad663814. --- accounts/abi/abi.go | 50 --- accounts/abi/argument.go | 53 --- accounts/abi/bind/auth.go | 89 ----- accounts/abi/bind/backend.go | 8 +- accounts/abi/bind/base.go | 168 +--------- accounts/abi/bind/bind.go | 133 +++++++- accounts/abi/bind/template.go | 31 +- accounts/abi/bind/topics.go | 48 --- accounts/abi/pack.go | 14 +- accounts/abi/type.go | 37 --- accounts/external/backend.go | 230 ------------- cmd/abigen/main.go | 237 ------------- cmd/utils/flags.go | 41 --- common/compiler/helpers.go | 65 ---- common/compiler/solidity.go | 74 +++-- common/compiler/solidity_test.go | 7 +- consensus/ethash/consensus.go | 2 +- interfaces.go | 12 +- internal/ethapi/api.go | 9 - internal/ethapi/api_abi.go | 6 +- seroclient/seroclient.go | 60 +--- tests/abigen/testAbi.go | 551 ------------------------------- tests/abigen/testAbi.sol | 90 ----- tests/abigen_test.go | 130 -------- tests/state_test.go | 4 +- 25 files changed, 240 insertions(+), 1909 deletions(-) delete mode 100644 accounts/abi/bind/auth.go delete mode 100644 accounts/external/backend.go delete mode 100644 cmd/abigen/main.go delete mode 100644 common/compiler/helpers.go delete mode 100644 tests/abigen/testAbi.go delete mode 100644 tests/abigen/testAbi.sol delete mode 100644 tests/abigen_test.go diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index deadc19c..254b1f7f 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -21,8 +21,6 @@ import ( "encoding/json" "fmt" "io" - - "github.com/sero-cash/go-czero-import/c_type" ) // The ABI holds information about a contract's context and available @@ -51,39 +49,10 @@ func JSON(reader io.Reader) (ABI, error) { // of 4 bytes and arguments are all 32 bytes. // Method ids are created from the first 4 bytes of the hash of the // methods string signature. (signature = baz(uint32,string32)) - -func (abi ABI) PackPrefix(name string, rand c_type.Uint128, args ...interface{}) ([]byte, error) { - var ret []byte - ret = append(ret, rand[:]...) - if name == "" { - // constructor - addressPrefix, err := abi.Constructor.Inputs.PackPrefix(args...) - if err != nil { - return nil, err - } - ret = append(ret, addressPrefix...) - return ret, nil - - } - method, exist := abi.Methods[name] - if !exist { - return nil, fmt.Errorf("method '%s' not found", name) - } - - addressPrefix, err := method.Inputs.PackPrefix(args...) - if err != nil { - return nil, err - } - ret = append(ret, addressPrefix...) - - return ret, nil -} - func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) { // Fetch the ABI of the requested method if name == "" { // constructor - arguments, err := abi.Constructor.Inputs.Pack(args...) if err != nil { return nil, err @@ -122,25 +91,6 @@ func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) { return fmt.Errorf("abi: could not locate named method or event") } -// UnpackIntoMap unpacks a log into the provided map[string]interface{} -func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) { - if len(data) == 0 { - return fmt.Errorf("abi: unmarshalling empty output") - } - // since there can't be naming collisions with contracts and events, - // we need to decide whether we're calling a method or an event - if method, ok := abi.Methods[name]; ok { - if len(data)%32 != 0 { - return fmt.Errorf("abi: improperly formatted output") - } - return method.Outputs.UnpackIntoMap(v, data) - } - if event, ok := abi.Events[name]; ok { - return event.Inputs.UnpackIntoMap(v, data) - } - return fmt.Errorf("abi: could not locate named method or event") -} - // UnmarshalJSON implements json.Unmarshaler interface func (abi *ABI) UnmarshalJSON(data []byte) error { var fields []struct { diff --git a/accounts/abi/argument.go b/accounts/abi/argument.go index eecafc66..93b513c3 100644 --- a/accounts/abi/argument.go +++ b/accounts/abi/argument.go @@ -19,13 +19,8 @@ package abi import ( "encoding/json" "fmt" - "math/big" "reflect" "strings" - - "github.com/sero-cash/go-sero/common/math" - - "github.com/sero-cash/go-czero-import/c_type" ) // Argument holds the name of the argument and the corresponding type. @@ -105,29 +100,6 @@ func (arguments Arguments) Unpack(v interface{}, data []byte) error { return arguments.unpackAtomic(v, marshalledValues) } -// UnpackIntoMap performs the operation hexdata -> mapping of argument name to argument value -func (arguments Arguments) UnpackIntoMap(v map[string]interface{}, data []byte) error { - marshalledValues, err := arguments.UnpackValues(data) - if err != nil { - return err - } - - return arguments.unpackIntoMap(v, marshalledValues) -} - -// unpackIntoMap unpacks marshalledValues into the provided map[string]interface{} -func (arguments Arguments) unpackIntoMap(v map[string]interface{}, marshalledValues []interface{}) error { - // Make sure map is not nil - if v == nil { - return fmt.Errorf("abi: cannot unpack into a nil map") - } - - for i, arg := range arguments.NonIndexed() { - v[arg.Name] = marshalledValues[i] - } - return nil -} - func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interface{}) error { var ( @@ -257,31 +229,6 @@ func (arguments Arguments) PackValues(args []interface{}) ([]byte, error) { return arguments.Pack(args...) } -func (arguments Arguments) PackPrefix(args ...interface{}) ([]byte, error) { - abiArgs := arguments - if len(args) != len(abiArgs) { - return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs)) - } - var result []c_type.PKr - for i, a := range args { - input := abiArgs[i] - // pack the input - pkrs, err := input.Type.getAllAddress(reflect.ValueOf(a)) - if err != nil { - return nil, err - } - result = append(result, pkrs...) - } - var ret []byte - lenBytes := math.PaddedBigBytes(big.NewInt(int64(len(result))), 2) - ret = append(ret, lenBytes...) - for _, pkr := range result { - ret = append(ret, pkr[:]...) - } - return ret, nil - -} - // Pack performs the operation Go format -> Hexdata func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) { // Make sure arguments match up and pack them diff --git a/accounts/abi/bind/auth.go b/accounts/abi/bind/auth.go deleted file mode 100644 index d163fd3c..00000000 --- a/accounts/abi/bind/auth.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2016 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package bind - -import ( - "encoding/binary" - "io" - "io/ioutil" - "math/big" - - "github.com/sero-cash/go-sero/zero/txtool" - "github.com/sero-cash/go-sero/zero/txtool/flight" - - "github.com/sero-cash/go-czero-import/superzk" - - "github.com/sero-cash/go-czero-import/c_type" - - "github.com/sero-cash/go-sero/accounts/keystore" - "github.com/sero-cash/go-sero/crypto" -) - -// NewTransactor is a utility method to easily create a transaction signer from -// an encrypted json key stream and the associated passphrase. -func NewTransactor(keyin io.Reader, passphrase string, value *big.Int) (*TransactOpts, error) { - superzk.ZeroInit_NoCircuit() - json, err := ioutil.ReadAll(keyin) - if err != nil { - return nil, err - } - key, err := keystore.DecryptKey(json, passphrase) - if err != nil { - return nil, err - } - fromPkr := getMainPkr(key) - - return NewKeyedTransactor(key, &fromPkr, value), nil -} - -func encodeNumber(number uint64) []byte { - enc := make([]byte, 8) - binary.BigEndian.PutUint64(enc, number) - return enc -} - -func getMainPkr(key *keystore.Key) c_type.PKr { - - salt := encodeNumber(1) - //log.Info("GenIndexPKr", "salt", hexutil.Encode(salt)) - random := append(key.Tk[:], salt...) - r := crypto.Keccak256Hash(random).HashToUint256() - pk := key.Address.ToUint512() - return superzk.Pk2PKr(&pk, r) -} - -// NewKeyedTransactor is a utility method to easily create a transaction signer -// from a single private key. -func NewKeyedTransactor(key *keystore.Key, refundTo *c_type.PKr, value *big.Int) *TransactOpts { - tk := crypto.PrivkeyToTk(key.PrivateKey, key.Version) - return &TransactOpts{ - From: tk.ToPk(), - Value: value, - RefundTo: refundTo, - Encrypter: func(txParam *txtool.GTxParam) (*txtool.GTx, error) { - priKey := crypto.FromECDSA(key.PrivateKey) - var seed c_type.Uint256 - copy(seed[:], priKey[:]) - sk := superzk.Seed2Sk(&seed, key.Version) - gtx, err := flight.SignTx(&sk, txParam) - if err != nil { - return nil, err - } - return >x, nil - }, - } -} diff --git a/accounts/abi/bind/backend.go b/accounts/abi/bind/backend.go index 2c5849f2..d60eba64 100644 --- a/accounts/abi/bind/backend.go +++ b/accounts/abi/bind/backend.go @@ -21,8 +21,6 @@ import ( "errors" "math/big" - "github.com/sero-cash/go-sero/zero/txtool" - sero "github.com/sero-cash/go-sero" "github.com/sero-cash/go-sero/common" "github.com/sero-cash/go-sero/core/types" @@ -82,10 +80,8 @@ type ContractTransactor interface { // transactions may be added or removed by miners, but it should provide a basis // for setting a reasonable default. EstimateGas(ctx context.Context, call sero.CallMsg) (gas uint64, err error) - - GenContractTx(ctx context.Context, msg sero.CallMsg) (*txtool.GTxParam, error) - - CommitTx(ctx context.Context, arg *txtool.GTx) error + // SendTransaction injects the transaction into the pending pool for execution. + SendTransaction(ctx context.Context, tx *types.Transaction) error } // ContractFilterer defines the methods needed to access log events using one-off diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go index 0e478bae..4857c4d2 100644 --- a/accounts/abi/bind/base.go +++ b/accounts/abi/bind/base.go @@ -18,42 +18,34 @@ package bind import ( "context" - "fmt" "math/big" - "github.com/sero-cash/go-sero/common/hexutil" - - "github.com/sero-cash/go-sero/common/address" - - "github.com/sero-cash/go-sero" - - "github.com/sero-cash/go-czero-import/c_type" + sero "github.com/sero-cash/go-sero" "github.com/sero-cash/go-sero/accounts/abi" "github.com/sero-cash/go-sero/common" "github.com/sero-cash/go-sero/core/types" "github.com/sero-cash/go-sero/event" - "github.com/sero-cash/go-sero/zero/txtool" + "github.com/sero-cash/go-sero/zero/txs/tx" ) -// SignerFn is a signer function callback when a contract requires a method to +// SignerFn is a abi function callback when a contract requires a method to // sign the transaction before submission. -type EncrypterFn func(txParam *txtool.GTxParam) (tx *txtool.GTx, e error) +type EncrypterFn func(common.Address, *types.Transaction, *tx.T) (*types.Transaction, error) // CallOpts is the collection of options to fine tune a contract call request. type CallOpts struct { - Pending bool // Whether to operate on the pending state or the last known one - From *address.PKAddress // Optional the sender address, otherwise the first account is used - RefundTo *c_type.PKr - BlockNumber *big.Int // Optional the block number on which the call should be performed - Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) + Pending bool // Whether to operate on the pending state or the last known one + From common.Address // Optional the sender address, otherwise the first account is used + + Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) } // TransactOpts is the collection of authorization data required to create a -// valid Ethereum transaction. +// valid Sero transaction. type TransactOpts struct { - From address.PKAddress // Ethereum account to send the transaction from - RefundTo *c_type.PKr - Encrypter EncrypterFn // Method to use for signing the transaction (mandatory) + From common.Address // Sero account to send the transaction from + Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state) + Encrypter EncrypterFn // Method to use for signing the transaction (mandatory) Value *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds) GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle) @@ -82,8 +74,8 @@ type WatchOpts struct { // Ethereum network. It contains a collection of methods that are used by the // higher level contract bindings to operate. type BoundContract struct { - address common.Address // Deployment address of the contract on the Ethereum blockchain - abi abi.ABI // Reflect based ABI to access the correct Ethereum methods + address common.Address // Deployment address of the contract on the Sero blockchain + abi abi.ABI // Reflect based ABI to access the correct Sero methods caller ContractCaller // Read interface to interact with the blockchain transactor ContractTransactor // Write interface to interact with the blockchain filterer ContractFilterer // Event filtering to interact with the blockchain @@ -101,33 +93,6 @@ func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller } } -// DeployContract deploys a contract onto the Ethereum blockchain and binds the -// deployment address with a Go wrapper. -func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) { - // Otherwise try to deploy the contract - c := NewBoundContract(common.Address{}, abi, backend, backend, backend) - - prefix, err := c.abi.PackPrefix("", c_type.RandUint128(), params...) - if err != nil { - return common.Address{}, nil, nil, err - } - input, err := c.abi.Pack("", params...) - if err != nil { - return common.Address{}, nil, nil, err - } - data := append(prefix, bytecode...) - input = append(data, input...) - fmt.Println("DeployContract prefix", hexutil.Encode(prefix[:])) - fmt.Println("DeployContract byteCode", hexutil.Encode(bytecode[:])) - fmt.Println("DeployContract data", hexutil.Encode(input)) - - tx, err := c.transact(opts, nil, input) - if err != nil { - return common.Address{}, nil, nil, err - } - return common.Address{}, tx, c, nil -} - // Call invokes the (constant) contract method with params as input values and // sets the output to result. The result type might be a single field for simple // returns, a slice of interfaces for anonymous returns and a struct for named @@ -137,20 +102,13 @@ func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, if opts == nil { opts = new(CallOpts) } - var rand c_type.Uint128 - copy(rand[:], c.address[:16]) - prefix, err := c.abi.PackPrefix(method, rand, params...) - if err != nil { - return err - } // Pack the input, call and unpack the results input, err := c.abi.Pack(method, params...) if err != nil { return err } - input = append(prefix, input...) var ( - msg = sero.CallMsg{From: opts.From, RefundTo: opts.RefundTo, To: &c.address, Data: input} + msg = sero.CallMsg{From: opts.From, To: &c.address, Data: input} ctx = ensureContext(opts.Context) code []byte output []byte @@ -170,10 +128,10 @@ func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, } } } else { - output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber) + output, err = c.caller.CallContract(ctx, msg, nil) if err == nil && len(output) == 0 { // Make sure we have a contract to operate on, and bail out otherwise. - if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil { + if code, err = c.caller.CodeAt(ctx, c.address, nil); err != nil { return err } else if len(code) == 0 { return ErrNoCode @@ -186,82 +144,6 @@ func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, return c.abi.Unpack(result, method, output) } -// Transact invokes the (paid) contract method with params as input values. -func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - // Otherwise pack up the parameters and invoke the contract - var rand c_type.Uint128 - copy(rand[:], c.address[:16]) - prefix, err := c.abi.PackPrefix(method, rand, params...) - if err != nil { - return nil, err - } - input, err := c.abi.Pack(method, params...) - if err != nil { - return nil, err - } - input = append(prefix, input...) - return c.transact(opts, &c.address, input) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) { - return c.transact(opts, &c.address, nil) -} - -// transact executes an actual transaction invocation, first deriving any missing -// authorization fields, and then scheduling the transaction for execution. -func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) { - var err error - - // Ensure a valid value field and resolve the account nonce - value := opts.Value - if value == nil { - value = new(big.Int) - } - - // Figure out the gas allowance and gas price values - gasPrice := opts.GasPrice - if gasPrice == nil { - gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context)) - if err != nil { - return nil, fmt.Errorf("failed to suggest gas price: %v", err) - } - } - gasLimit := opts.GasLimit - if gasLimit == 0 { - // Gas estimation cannot succeed without code for method invocations - if contract != nil { - if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil { - return nil, err - } else if len(code) == 0 { - return nil, ErrNoCode - } - } - // If the contract surely has code (or code is not needed), estimate the transaction - msg := sero.CallMsg{From: &opts.From, To: contract, Value: value, Data: input} - gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg) - if err != nil { - return nil, fmt.Errorf("failed to estimate gas needed: %v", err) - } - } - - msg := sero.CallMsg{From: &opts.From, RefundTo: opts.RefundTo, To: contract, Gas: gasLimit, Value: value, GasPrice: gasPrice, Data: input} - preTx, err := c.transactor.GenContractTx(ensureContext(opts.Context), msg) - if err != nil { - return nil, err - } - gtx, err := opts.Encrypter(preTx) - - err = c.transactor.CommitTx(ensureContext(opts.Context), gtx) - if err != nil { - return nil, err - } - - signedTx := types.NewTxWithGTx(opts.GasLimit, gasPrice, >x.Tx) - return signedTx, nil -} - // FilterLogs filters contract logs for past blocks, returning the necessary // channels to construct a strongly typed bound iterator on top of them. func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { @@ -358,22 +240,6 @@ func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) return parseTopics(out, indexed, log.Topics[1:]) } -// UnpackLogIntoMap unpacks a retrieved log into the provided map. -func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error { - if len(log.Data) > 0 { - if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil { - return err - } - } - var indexed abi.Arguments - for _, arg := range c.abi.Events[event].Inputs { - if arg.Indexed { - indexed = append(indexed, arg) - } - } - return parseTopicsIntoMap(out, indexed, log.Topics[1:]) -} - // ensureContext is a helper method to ensure a context is not nil, even if the // user specified it as such. func ensureContext(ctx context.Context) context.Context { diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index f3859fd4..8c1781fc 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -37,6 +37,8 @@ type Lang int const ( LangGo Lang = iota + LangJava + LangObjC ) // Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant @@ -158,7 +160,8 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string, lang La // bindType is a set of type binders that convert Solidity types to some supported // programming language types. var bindType = map[Lang]func(kind abi.Type) string{ - LangGo: bindTypeGo, + LangGo: bindTypeGo, + LangJava: bindTypeJava, } // Helper function for the binding generators. @@ -209,7 +212,7 @@ func bindUnnestedTypeGo(stringKind string) (int, string) { switch { case strings.HasPrefix(stringKind, "address"): - return len("address"), "common.Address" + return len("address"), "common.Data" case strings.HasPrefix(stringKind, "bytes"): parts := regexp.MustCompile(`bytes([0-9]*)`).FindStringSubmatch(stringKind) @@ -234,10 +237,82 @@ func bindUnnestedTypeGo(stringKind string) (int, string) { } } +// Translates the array sizes to a Java declaration of a (nested) array of the inner type. +// Simply returns the inner type if arraySizes is empty. +func arrayBindingJava(inner string, arraySizes []string) string { + // Java array type declarations do not include the length. + return inner + strings.Repeat("[]", len(arraySizes)) +} + +// bindTypeJava converts a Solidity type to a Java one. Since there is no clear mapping +// from all Solidity types to Java ones (e.g. uint17), those that cannot be exactly +// mapped will use an upscaled type (e.g. BigDecimal). +func bindTypeJava(kind abi.Type) string { + stringKind := kind.String() + innerLen, innerMapping := bindUnnestedTypeJava(stringKind) + return arrayBindingJava(wrapArray(stringKind, innerLen, innerMapping)) +} + +// The inner function of bindTypeJava, this finds the inner type of stringKind. +// (Or just the type itself if it is not an array or slice) +// The length of the matched part is returned, with the the translated type. +func bindUnnestedTypeJava(stringKind string) (int, string) { + + switch { + case strings.HasPrefix(stringKind, "address"): + parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind) + if len(parts) != 2 { + return len(stringKind), stringKind + } + if parts[1] == "" { + return len("address"), "Data" + } + return len(parts[0]), "Addresses" + + case strings.HasPrefix(stringKind, "bytes"): + parts := regexp.MustCompile(`bytes([0-9]*)`).FindStringSubmatch(stringKind) + if len(parts) != 2 { + return len(stringKind), stringKind + } + return len(parts[0]), "byte[]" + + case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): + //Note that uint and int (without digits) are also matched, + // these are size 256, and will translate to BigInt (the default). + parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(stringKind) + if len(parts) != 3 { + return len(stringKind), stringKind + } + + namedSize := map[string]string{ + "8": "byte", + "16": "short", + "32": "int", + "64": "long", + }[parts[2]] + + //default to BigInt + if namedSize == "" { + namedSize = "BigInt" + } + return len(parts[0]), namedSize + + case strings.HasPrefix(stringKind, "bool"): + return len("bool"), "boolean" + + case strings.HasPrefix(stringKind, "string"): + return len("string"), "String" + + default: + return len(stringKind), stringKind + } +} + // bindTopicType is a set of type binders that convert Solidity types to some // supported programming language topic types. var bindTopicType = map[Lang]func(kind abi.Type) string{ - LangGo: bindTopicTypeGo, + LangGo: bindTopicTypeGo, + LangJava: bindTopicTypeJava, } // bindTypeGo converts a Solidity topic type to a Go one. It is almost the same @@ -250,16 +325,64 @@ func bindTopicTypeGo(kind abi.Type) string { return bound } +// bindTypeGo converts a Solidity topic type to a Java one. It is almost the same +// funcionality as for simple types, but dynamic types get converted to hashes. +func bindTopicTypeJava(kind abi.Type) string { + bound := bindTypeJava(kind) + if bound == "String" || bound == "Bytes" { + bound = "Hash" + } + return bound +} + // namedType is a set of functions that transform language specific types to // named versions that my be used inside method names. var namedType = map[Lang]func(string, abi.Type) string{ - LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") }, + LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") }, + LangJava: namedTypeJava, +} + +// namedTypeJava converts some primitive data types to named variants that can +// be used as parts of method names. +func namedTypeJava(javaKind string, solKind abi.Type) string { + switch javaKind { + case "byte[]": + return "Binary" + case "byte[][]": + return "Binaries" + case "string": + return "String" + case "string[]": + return "Strings" + case "boolean": + return "Bool" + case "boolean[]": + return "Bools" + case "BigInt[]": + return "BigInts" + default: + parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(solKind.String()) + if len(parts) != 4 { + return javaKind + } + switch parts[2] { + case "8", "16", "32", "64": + if parts[3] == "" { + return capitalise(fmt.Sprintf("%sint%s", parts[1], parts[2])) + } + return capitalise(fmt.Sprintf("%sint%ss", parts[1], parts[2])) + + default: + return javaKind + } + } } // methodNormalizer is a name transformer that modifies Solidity method names to // conform to target language naming concentions. var methodNormalizer = map[Lang]func(string) string{ - LangGo: capitalise, + LangGo: capitalise, + LangJava: decapitalise, } // capitalise makes a camel-case string which starts with an upper case character. diff --git a/accounts/abi/bind/template.go b/accounts/abi/bind/template.go index 819ea9c4..cf82593c 100644 --- a/accounts/abi/bind/template.go +++ b/accounts/abi/bind/template.go @@ -52,7 +52,8 @@ type tmplEvent struct { // tmplSource is language to template mapping containing all the supported // programming languages the package can generate to. var tmplSource = map[Lang]string{ - LangGo: tmplSourceGo, + LangGo: tmplSourceGo, + LangJava: tmplSourceJava, } // tmplSourceGo is the Go source template use to generate the contract binding @@ -72,14 +73,14 @@ package {{.Package}} const {{.Type}}Bin = ` + "`" + `{{.InputBin}}` + "`" + ` // Deploy{{.Type}} deploys a new Ethereum contract, binding an instance of {{.Type}} to it. - func Deploy{{.Type}}(auth *bind.TransactOpts, backend bind.ContractBackend {{range .Constructor.Inputs}}, {{.Name}} {{bindtype .Type}}{{end}}) (common.Address, *types.Transaction, *{{.Type}}, error) { + func Deploy{{.Type}}(auth *bind.TransactOpts, backend bind.ContractBackend {{range .Constructor.Inputs}}, {{.Name}} {{bindtype .Type}}{{end}}) (common.Data, *types.Transaction, *{{.Type}}, error) { parsed, err := abi.JSON(strings.NewReader({{.Type}}ABI)) if err != nil { - return common.Address{}, nil, nil, err + return common.Data{}, nil, nil, err } address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex({{.Type}}Bin), backend {{range .Constructor.Inputs}}, {{.Name}}{{end}}) if err != nil { - return common.Address{}, nil, nil, err + return common.Data{}, nil, nil, err } return address, tx, &{{.Type}}{ {{.Type}}Caller: {{.Type}}Caller{contract: contract}, {{.Type}}Transactor: {{.Type}}Transactor{contract: contract}, {{.Type}}Filterer: {{.Type}}Filterer{contract: contract} }, nil } @@ -145,7 +146,7 @@ package {{.Package}} } // New{{.Type}} creates a new instance of {{.Type}}, bound to a specific deployed contract. - func New{{.Type}}(address common.Address, backend bind.ContractBackend) (*{{.Type}}, error) { + func New{{.Type}}(address common.Data, backend bind.ContractBackend) (*{{.Type}}, error) { contract, err := bind{{.Type}}(address, backend, backend, backend) if err != nil { return nil, err @@ -154,7 +155,7 @@ package {{.Package}} } // New{{.Type}}Caller creates a new read-only instance of {{.Type}}, bound to a specific deployed contract. - func New{{.Type}}Caller(address common.Address, caller bind.ContractCaller) (*{{.Type}}Caller, error) { + func New{{.Type}}Caller(address common.Data, caller bind.ContractCaller) (*{{.Type}}Caller, error) { contract, err := bind{{.Type}}(address, caller, nil, nil) if err != nil { return nil, err @@ -163,7 +164,7 @@ package {{.Package}} } // New{{.Type}}Transactor creates a new write-only instance of {{.Type}}, bound to a specific deployed contract. - func New{{.Type}}Transactor(address common.Address, transactor bind.ContractTransactor) (*{{.Type}}Transactor, error) { + func New{{.Type}}Transactor(address common.Data, transactor bind.ContractTransactor) (*{{.Type}}Transactor, error) { contract, err := bind{{.Type}}(address, nil, transactor, nil) if err != nil { return nil, err @@ -172,7 +173,7 @@ package {{.Package}} } // New{{.Type}}Filterer creates a new log filterer instance of {{.Type}}, bound to a specific deployed contract. - func New{{.Type}}Filterer(address common.Address, filterer bind.ContractFilterer) (*{{.Type}}Filterer, error) { + func New{{.Type}}Filterer(address common.Data, filterer bind.ContractFilterer) (*{{.Type}}Filterer, error) { contract, err := bind{{.Type}}(address, nil, nil, filterer) if err != nil { return nil, err @@ -181,7 +182,7 @@ package {{.Package}} } // bind{{.Type}} binds a generic wrapper to an already deployed contract. - func bind{{.Type}}(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + func bind{{.Type}}(address common.Data, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader({{.Type}}ABI)) if err != nil { return nil, err @@ -294,7 +295,7 @@ package {{.Package}} event string // Event name to use for unpacking event data logs chan types.Log // Log channel receiving the found contract events - sub sero.Subscription // Subscription for errors, completion and termination + sub ethereum.Subscription // Subscription for errors, completion and termination done bool // Whether the subscription completed delivering logs fail error // Occurred error to stop iteration } @@ -426,8 +427,8 @@ const tmplSourceJava = ` package {{.Package}}; -import org.ethereum.geth.*; -import org.ethereum.geth.internal.*; +import org.ethereum.gero.*; +import org.ethereum.gero.internal.*; {{range $contract := .Contracts}} public class {{.Type}} { @@ -449,14 +450,14 @@ import org.ethereum.geth.internal.*; // Internal constructor used by contract deployment. private {{.Type}}(BoundContract deployment) { - this.Address = deployment.getAddress(); + this.Data = deployment.getAddress(); this.Deployer = deployment.getDeployer(); this.Contract = deployment; } {{end}} // Ethereum address where this contract is located at. - public final Address Address; + public final Data Data; // Ethereum transaction in which this contract was deployed (if known!). public final Transaction Deployer; @@ -465,7 +466,7 @@ import org.ethereum.geth.internal.*; private final BoundContract Contract; // Creates a new instance of {{.Type}}, bound to a specific deployed contract. - public {{.Type}}(Address address, EthereumClient client) throws Exception { + public {{.Type}}(Data address, EthereumClient client) throws Exception { this(Geth.bindContract(address, ABI, client)); } diff --git a/accounts/abi/bind/topics.go b/accounts/abi/bind/topics.go index bdd49cd1..d9ecff04 100644 --- a/accounts/abi/bind/topics.go +++ b/accounts/abi/bind/topics.go @@ -17,7 +17,6 @@ package bind import ( - "encoding/binary" "errors" "fmt" "math/big" @@ -187,50 +186,3 @@ func parseTopics(out interface{}, fields abi.Arguments, topics []common.Hash) er } return nil } - -// parseTopicsIntoMap converts the indexed topic field-value pairs into map key-value pairs -func parseTopicsIntoMap(out map[string]interface{}, fields abi.Arguments, topics []common.Hash) error { - // Sanity check that the fields and topics match up - if len(fields) != len(topics) { - return errors.New("topic/field count mismatch") - } - // Iterate over all the fields and reconstruct them from topics - for _, arg := range fields { - if !arg.Indexed { - return errors.New("non-indexed field in topic reconstruction") - } - - switch arg.Type.T { - case abi.BoolTy: - out[arg.Name] = topics[0][common.HashLength-1] == 1 - case abi.IntTy, abi.UintTy: - num := new(big.Int).SetBytes(topics[0][:]) - out[arg.Name] = num - case abi.AddressTy: - var addr common.Address - copy(addr[:], topics[0][12:]) - out[arg.Name] = addr - case abi.HashTy: - out[arg.Name] = topics[0] - case abi.FixedBytesTy: - out[arg.Name] = topics[0][:] - case abi.StringTy, abi.BytesTy, abi.SliceTy, abi.ArrayTy: - // Array types (including strings and bytes) have their keccak256 hashes stored in the topic- not a hash - // whose bytes can be decoded to the actual value- so the best we can do is retrieve that hash - out[arg.Name] = topics[0] - case abi.FunctionTy: - if garbage := binary.BigEndian.Uint64(topics[0][0:8]); garbage != 0 { - return fmt.Errorf("bind: got improperly encoded function type, got %v", topics[0].Bytes()) - } - var tmp [24]byte - copy(tmp[:], topics[0][8:32]) - out[arg.Name] = tmp - default: // Not handling tuples - return fmt.Errorf("unsupported indexed type: %v", arg.Type) - } - - topics = topics[1:] - } - - return nil -} diff --git a/accounts/abi/pack.go b/accounts/abi/pack.go index 372edebf..767a9e52 100644 --- a/accounts/abi/pack.go +++ b/accounts/abi/pack.go @@ -20,9 +20,6 @@ import ( "math/big" "reflect" - "github.com/sero-cash/go-czero-import/c_type" - - "github.com/sero-cash/go-czero-import/c_superzk" "github.com/sero-cash/go-sero/common" "github.com/sero-cash/go-sero/common/math" ) @@ -34,14 +31,6 @@ func packBytesSlice(bytes []byte, l int) []byte { return append(len, common.RightPadBytes(bytes, (l+31)/32*32)...) } -func convertToPkr(addr []byte) []byte { - var pkr c_type.PKr - copy(pkr[:], addr) - shortAddr := c_superzk.HashPKr(pkr.NewRef()) - return common.LeftPadBytes(shortAddr[:], 32) - -} - // packElement packs the given reflect value according to the abi specification in // t. func packElement(t Type, reflectValue reflect.Value) []byte { @@ -54,7 +43,8 @@ func packElement(t Type, reflectValue reflect.Value) []byte { if reflectValue.Kind() == reflect.Array { reflectValue = mustArrayToByteSlice(reflectValue) } - return convertToPkr(reflectValue.Bytes()) + + return common.LeftPadBytes(reflectValue.Bytes(), 32) case BoolTy: if reflectValue.Bool() { return math.PaddedBigBytes(common.Big1, 32) diff --git a/accounts/abi/type.go b/accounts/abi/type.go index 78968849..9de36daf 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -22,10 +22,6 @@ import ( "regexp" "strconv" "strings" - - "github.com/pkg/errors" - - "github.com/sero-cash/go-czero-import/c_type" ) // Type enumerator @@ -201,39 +197,6 @@ func (t Type) pack(v reflect.Value) ([]byte, error) { return packElement(t, v), nil } -func (t Type) getAllAddress(v reflect.Value) (pkrs []c_type.PKr, err error) { - // dereference pointer first if it's a pointer - v = indirect(v) - - if err := typeCheck(t, v); err != nil { - return nil, err - } - if t.T == SliceTy || t.T == ArrayTy { - for i := 0; i < v.Len(); i++ { - val, err := t.Elem.getAllAddress(v.Index(i)) - if err != nil { - return nil, err - } - pkrs = append(pkrs, val...) - } - return - } - if t.T == AddressTy { - if v.Kind() == reflect.Array { - v = mustArrayToByteSlice(v) - } - if len(v.Bytes()) != 96 { - return nil, errors.New("address params only support pkr") - } - var pkr c_type.PKr - copy(pkr[:], v.Bytes()) - pkrs = append(pkrs, pkr) - return - } - return - -} - // requireLengthPrefix returns whether the type requires any sort of length // prefixing. func (t Type) requiresLengthPrefix() bool { diff --git a/accounts/external/backend.go b/accounts/external/backend.go deleted file mode 100644 index 1e2ecc73..00000000 --- a/accounts/external/backend.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2019 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package external - -import ( - "fmt" - "math/big" - "sync" - - "github.com/sero-cash/go-sero/accounts" - "github.com/sero-cash/go-sero/common" - "github.com/sero-cash/go-sero/common/hexutil" - "github.com/sero-cash/go-sero/core/types" - "github.com/sero-cash/go-sero/event" - "github.com/sero-cash/go-sero/internal/ethapi" - "github.com/sero-cash/go-sero/log" - "github.com/sero-cash/go-sero/rpc" - "github.com/sero-cash/go-sero/signer/core" -) - -type ExternalBackend struct { - signers []accounts.Wallet -} - -func (eb *ExternalBackend) Wallets() []accounts.Wallet { - return eb.signers -} - -func NewExternalBackend(endpoint string) (*ExternalBackend, error) { - signer, err := NewExternalSigner(endpoint) - if err != nil { - return nil, err - } - return &ExternalBackend{ - signers: []accounts.Wallet{signer}, - }, nil -} - -func (eb *ExternalBackend) Subscribe(sink chan<- accounts.WalletEvent) event.Subscription { - return event.NewSubscription(func(quit <-chan struct{}) error { - <-quit - return nil - }) -} - -// ExternalSigner provides an API to interact with an external signer (clef) -// It proxies request to the external signer while forwarding relevant -// request headers -type ExternalSigner struct { - client *rpc.Client - endpoint string - status string - cacheMu sync.RWMutex - cache []accounts.Account -} - -func NewExternalSigner(endpoint string) (*ExternalSigner, error) { - client, err := rpc.Dial(endpoint) - if err != nil { - return nil, err - } - extsigner := &ExternalSigner{ - client: client, - endpoint: endpoint, - } - // Check if reachable - version, err := extsigner.pingVersion() - if err != nil { - return nil, err - } - extsigner.status = fmt.Sprintf("ok [version=%v]", version) - return extsigner, nil -} - -func (api *ExternalSigner) URL() accounts.URL { - return accounts.URL{ - Scheme: "extapi", - Path: api.endpoint, - } -} - -func (api *ExternalSigner) Status() (string, error) { - return api.status, nil -} - -func (api *ExternalSigner) Open(passphrase string) error { - return fmt.Errorf("operation not supported on external signers") -} - -func (api *ExternalSigner) Close() error { - return fmt.Errorf("operation not supported on external signers") -} - -func (api *ExternalSigner) Accounts() []accounts.Account { - var accnts []accounts.Account - res, err := api.listAccounts() - if err != nil { - log.Error("account listing failed", "error", err) - return accnts - } - for _, addr := range res { - accnts = append(accnts, accounts.Account{ - URL: accounts.URL{ - Scheme: "extapi", - Path: api.endpoint, - }, - Address: addr, - }) - } - api.cacheMu.Lock() - api.cache = accnts - api.cacheMu.Unlock() - return accnts -} - -func (api *ExternalSigner) Contains(account accounts.Account) bool { - api.cacheMu.RLock() - defer api.cacheMu.RUnlock() - for _, a := range api.cache { - if a.Address == account.Address && (account.URL == (accounts.URL{}) || account.URL == api.URL()) { - return true - } - } - return false -} - -func (api *ExternalSigner) Derive(path accounts.DerivationPath, pin bool) (accounts.Account, error) { - return accounts.Account{}, fmt.Errorf("operation not supported on external signers") -} - -func (api *ExternalSigner) SelfDerive(bases []accounts.DerivationPath, chain ethereum.ChainStateReader) { - log.Error("operation SelfDerive not supported on external signers") -} - -func (api *ExternalSigner) signHash(account accounts.Account, hash []byte) ([]byte, error) { - return []byte{}, fmt.Errorf("operation not supported on external signers") -} - -// SignData signs keccak256(data). The mimetype parameter describes the type of data being signed -func (api *ExternalSigner) SignData(account accounts.Account, mimeType string, data []byte) ([]byte, error) { - var res hexutil.Bytes - var signAddress = common.NewMixedcaseAddress(account.Address) - if err := api.client.Call(&res, "account_signData", - mimeType, - &signAddress, // Need to use the pointer here, because of how MarshalJSON is defined - hexutil.Encode(data)); err != nil { - return nil, err - } - // If V is on 27/28-form, convert to to 0/1 for Clique - if mimeType == accounts.MimetypeClique && (res[64] == 27 || res[64] == 28) { - res[64] -= 27 // Transform V from 27/28 to 0/1 for Clique use - } - return res, nil -} - -func (api *ExternalSigner) SignText(account accounts.Account, text []byte) ([]byte, error) { - var res hexutil.Bytes - var signAddress = common.NewMixedcaseAddress(account.Address) - if err := api.client.Call(&res, "account_signData", - accounts.MimetypeTextPlain, - &signAddress, // Need to use the pointer here, because of how MarshalJSON is defined - hexutil.Encode(text)); err != nil { - return nil, err - } - return res, nil -} - -func (api *ExternalSigner) SignTx(account accounts.Account, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { - res := ethapi.SignTransactionResult{} - data := hexutil.Bytes(tx.Data()) - var to *common.MixedcaseAddress - if tx.To() != nil { - t := common.NewMixedcaseAddress(*tx.To()) - to = &t - } - args := &core.SendTxArgs{ - Data: &data, - Nonce: hexutil.Uint64(tx.Nonce()), - Value: hexutil.Big(*tx.Value()), - Gas: hexutil.Uint64(tx.Gas()), - GasPrice: hexutil.Big(*tx.GasPrice()), - To: to, - From: common.NewMixedcaseAddress(account.Address), - } - if err := api.client.Call(&res, "account_signTransaction", args); err != nil { - return nil, err - } - return res.Tx, nil -} - -func (api *ExternalSigner) SignTextWithPassphrase(account accounts.Account, passphrase string, text []byte) ([]byte, error) { - return []byte{}, fmt.Errorf("passphrase-operations not supported on external signers") -} - -func (api *ExternalSigner) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { - return nil, fmt.Errorf("passphrase-operations not supported on external signers") -} -func (api *ExternalSigner) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) { - return nil, fmt.Errorf("passphrase-operations not supported on external signers") -} - -func (api *ExternalSigner) listAccounts() ([]common.Address, error) { - var res []common.Address - if err := api.client.Call(&res, "account_list"); err != nil { - return nil, err - } - return res, nil -} - -func (api *ExternalSigner) pingVersion() (string, error) { - var v string - if err := api.client.Call(&v, "account_version"); err != nil { - return "", err - } - return v, nil -} diff --git a/cmd/abigen/main.go b/cmd/abigen/main.go deleted file mode 100644 index 070787bd..00000000 --- a/cmd/abigen/main.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2016 The go-ethereum Authors -// This file is part of go-ethereum. -// -// go-ethereum is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// go-ethereum is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with go-ethereum. If not, see . - -package main - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "strings" - - "github.com/sero-cash/go-sero/accounts/abi/bind" - "github.com/sero-cash/go-sero/cmd/utils" - "github.com/sero-cash/go-sero/common/compiler" - "github.com/sero-cash/go-sero/crypto" - "github.com/sero-cash/go-sero/log" - "gopkg.in/urfave/cli.v1" -) - -const ( - commandHelperTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...] -{{if .Description}}{{.Description}} -{{end}}{{if .Subcommands}} -SUBCOMMANDS: - {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}} - {{end}}{{end}}{{if .Flags}} -OPTIONS: -{{range $.Flags}}{{"\t"}}{{.}} -{{end}} -{{end}}` -) - -var ( - // Git SHA1 commit hash of the release (set via linker flags) - gitCommit = "" - gitDate = "" - - app *cli.App - - // Flags needed by abigen - abiFlag = cli.StringFlag{ - Name: "abi", - Usage: "Path to the Sero contract ABI json to bind, - for STDIN", - } - binFlag = cli.StringFlag{ - Name: "bin", - Usage: "Path to the Sero contract bytecode (generate deploy method)", - } - typeFlag = cli.StringFlag{ - Name: "type", - Usage: "Struct name for the binding (default = package name)", - } - jsonFlag = cli.StringFlag{ - Name: "combined-json", - Usage: "Path to the combined-json file generated by compiler", - } - solFlag = cli.StringFlag{ - Name: "sol", - Usage: "Path to the Sero contract Solidity source to build and bind", - } - solcFlag = cli.StringFlag{ - Name: "solc", - Usage: "Solidity compiler to use if source builds are requested", - Value: "solc", - } - excFlag = cli.StringFlag{ - Name: "exc", - Usage: "Comma separated types to exclude from binding", - } - pkgFlag = cli.StringFlag{ - Name: "pkg", - Usage: "Package name to generate the binding into", - } - outFlag = cli.StringFlag{ - Name: "out", - Usage: "Output file for the generated binding (default = stdout)", - } - langFlag = cli.StringFlag{ - Name: "lang", - Usage: "Destination language for the bindings (go, java, objc)", - Value: "go", - } -) - -func init() { - app = utils.NewApp(gitCommit, "ethereum checkpoint helper tool") - app.Flags = []cli.Flag{ - abiFlag, - binFlag, - typeFlag, - jsonFlag, - solFlag, - solcFlag, - excFlag, - pkgFlag, - outFlag, - langFlag, - } - app.Action = utils.MigrateFlags(abigen) - cli.CommandHelpTemplate = commandHelperTemplate -} - -func abigen(c *cli.Context) error { - utils.CheckExclusive(c, abiFlag, jsonFlag, solFlag) // Only one source can be selected. - if c.GlobalString(pkgFlag.Name) == "" { - utils.Fatalf("No destination package specified (--pkg)") - } - var lang bind.Lang - switch c.GlobalString(langFlag.Name) { - case "go": - lang = bind.LangGo - default: - utils.Fatalf("Unsupported destination language \"%s\" (--lang)", c.GlobalString(langFlag.Name)) - } - // If the entire solidity code was specified, build and bind based on that - var ( - abis []string - bins []string - types []string - sigs []map[string]string - libs = make(map[string]string) - ) - if c.GlobalString(abiFlag.Name) != "" { - // Load up the ABI, optional bytecode and type name from the parameters - var ( - abi []byte - err error - ) - input := c.GlobalString(abiFlag.Name) - if input == "-" { - abi, err = ioutil.ReadAll(os.Stdin) - } else { - abi, err = ioutil.ReadFile(input) - } - if err != nil { - utils.Fatalf("Failed to read input ABI: %v", err) - } - abis = append(abis, string(abi)) - - var bin []byte - if binFile := c.GlobalString(binFlag.Name); binFile != "" { - if bin, err = ioutil.ReadFile(binFile); err != nil { - utils.Fatalf("Failed to read input bytecode: %v", err) - } - if strings.Contains(string(bin), "//") { - utils.Fatalf("Contract has additional library references, please use other mode(e.g. --combined-json) to catch library infos") - } - } - bins = append(bins, string(bin)) - - kind := c.GlobalString(typeFlag.Name) - if kind == "" { - kind = c.GlobalString(pkgFlag.Name) - } - types = append(types, kind) - } else { - // Generate the list of types to exclude from binding - exclude := make(map[string]bool) - for _, kind := range strings.Split(c.GlobalString(excFlag.Name), ",") { - exclude[strings.ToLower(kind)] = true - } - var err error - var contracts map[string]*compiler.Contract - - switch { - case c.GlobalIsSet(solFlag.Name): - contracts, err = compiler.CompileSolidity(c.GlobalString(solcFlag.Name), c.GlobalString(solFlag.Name)) - if err != nil { - utils.Fatalf("Failed to build Solidity contract: %v", err) - } - case c.GlobalIsSet(jsonFlag.Name): - jsonOutput, err := ioutil.ReadFile(c.GlobalString(jsonFlag.Name)) - if err != nil { - utils.Fatalf("Failed to read combined-json from compiler: %v", err) - } - contracts, err = compiler.ParseCombinedJSON(jsonOutput, "", "", "", "") - if err != nil { - utils.Fatalf("Failed to read contract information from json output: %v", err) - } - } - // Gather all non-excluded contract for binding - for name, contract := range contracts { - if exclude[strings.ToLower(name)] { - continue - } - abi, err := json.Marshal(contract.Info.AbiDefinition) // Flatten the compiler parse - if err != nil { - utils.Fatalf("Failed to parse ABIs from compiler output: %v", err) - } - abis = append(abis, string(abi)) - bins = append(bins, contract.Code) - sigs = append(sigs, contract.Hashes) - nameParts := strings.Split(name, ":") - types = append(types, nameParts[len(nameParts)-1]) - - libPattern := crypto.Keccak256Hash([]byte(name)).String()[2:36] - libs[libPattern] = nameParts[len(nameParts)-1] - } - } - // Generate the contract binding - code, err := bind.Bind(types, abis, bins, c.GlobalString(pkgFlag.Name), lang) - if err != nil { - utils.Fatalf("Failed to generate ABI binding: %v", err) - } - // Either flush it out to a file or display on the standard output - if !c.GlobalIsSet(outFlag.Name) { - fmt.Printf("%s\n", code) - return nil - } - if err := ioutil.WriteFile(c.GlobalString(outFlag.Name), []byte(code), 0600); err != nil { - utils.Fatalf("Failed to write ABI binding: %v", err) - } - return nil -} - -func main() { - log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) - - if err := app.Run(os.Args); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index afe16d51..d935f35c 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1267,47 +1267,6 @@ func SetSeroConfig(ctx *cli.Context, stack *node.Node, cfg *sero.Config) { } } -// CheckExclusive verifies that only a single instance of the provided flags was -// set by the user. Each flag might optionally be followed by a string type to -// specialize it further. -func CheckExclusive(ctx *cli.Context, args ...interface{}) { - set := make([]string, 0, 1) - for i := 0; i < len(args); i++ { - // Make sure the next argument is a flag and skip if not set - flag, ok := args[i].(cli.Flag) - if !ok { - panic(fmt.Sprintf("invalid argument, not cli.Flag type: %T", args[i])) - } - // Check if next arg extends current and expand its name if so - name := flag.GetName() - - if i+1 < len(args) { - switch option := args[i+1].(type) { - case string: - // Extended flag check, make sure value set doesn't conflict with passed in option - if ctx.GlobalString(flag.GetName()) == option { - name += "=" + option - set = append(set, "--"+name) - } - // shift arguments and continue - i++ - continue - - case cli.Flag: - default: - panic(fmt.Sprintf("invalid argument, not cli.Flag or string extension: %T", args[i+1])) - } - } - // Mark the flag if it's set - if ctx.GlobalIsSet(flag.GetName()) { - set = append(set, "--"+name) - } - } - if len(set) > 1 { - Fatalf("Flags %v can't be used at the same time", strings.Join(set, ", ")) - } -} - // SetDashboardConfig applies dashboard related command line flags to the config. func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) { cfg.Host = ctx.GlobalString(DashboardAddrFlag.Name) diff --git a/common/compiler/helpers.go b/common/compiler/helpers.go deleted file mode 100644 index 5ed640de..00000000 --- a/common/compiler/helpers.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2019 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -// Package compiler wraps the Solidity and Vyper compiler executables (solc; vyper). -package compiler - -import ( - "bytes" - "io/ioutil" - "regexp" -) - -var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`) - -// Contract contains information about a compiled contract, alongside its code and runtime code. -type Contract struct { - Code string `json:"code"` - RuntimeCode string `json:"runtime-code"` - Info ContractInfo `json:"info"` - Hashes map[string]string `json:"hashes"` -} - -// ContractInfo contains information about a compiled contract, including access -// to the ABI definition, source mapping, user and developer docs, and metadata. -// -// Depending on the source, language version, compiler version, and compiler -// options will provide information about how the contract was compiled. -type ContractInfo struct { - Source string `json:"source"` - Language string `json:"language"` - LanguageVersion string `json:"languageVersion"` - CompilerVersion string `json:"compilerVersion"` - CompilerOptions string `json:"compilerOptions"` - SrcMap interface{} `json:"srcMap"` - SrcMapRuntime string `json:"srcMapRuntime"` - AbiDefinition interface{} `json:"abiDefinition"` - UserDoc interface{} `json:"userDoc"` - DeveloperDoc interface{} `json:"developerDoc"` - Metadata string `json:"metadata"` -} - -func slurpFiles(files []string) (string, error) { - var concat bytes.Buffer - for _, file := range files { - content, err := ioutil.ReadFile(file) - if err != nil { - return "", err - } - concat.Write(content) - } - return concat.String(), nil -} diff --git a/common/compiler/solidity.go b/common/compiler/solidity.go index b689f258..f6e8d2e4 100644 --- a/common/compiler/solidity.go +++ b/common/compiler/solidity.go @@ -14,7 +14,7 @@ // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see . -// Package compiler wraps the Solidity and Vyper compiler executables (solc; vyper). +// Package compiler wraps the Solidity compiler executable (solc). package compiler import ( @@ -22,11 +22,38 @@ import ( "encoding/json" "errors" "fmt" + "io/ioutil" "os/exec" + "regexp" "strconv" "strings" ) +var versionRegexp = regexp.MustCompile(`([0-9]+)\.([0-9]+)\.([0-9]+)`) + +// Contract contains information about a compiled contract, alongside its code. +type Contract struct { + Code string `json:"code"` + Info ContractInfo `json:"info"` +} + +// ContractInfo contains information about a compiled contract, including access +// to the ABI definition, user and developer docs, and metadata. +// +// Depending on the source, language version, compiler version, and compiler +// options will provide information about how the contract was compiled. +type ContractInfo struct { + Source string `json:"source"` + Language string `json:"language"` + LanguageVersion string `json:"languageVersion"` + CompilerVersion string `json:"compilerVersion"` + CompilerOptions string `json:"compilerOptions"` + AbiDefinition interface{} `json:"abiDefinition"` + UserDoc interface{} `json:"userDoc"` + DeveloperDoc interface{} `json:"developerDoc"` + Metadata string `json:"metadata"` +} + // Solidity contains information about the solidity compiler. type Solidity struct { Path, Version, FullVersion string @@ -36,22 +63,18 @@ type Solidity struct { // --combined-output format type solcOutput struct { Contracts map[string]struct { - BinRuntime string `json:"bin-runtime"` - SrcMapRuntime string `json:"srcmap-runtime"` - Bin, SrcMap, Abi, Devdoc, Userdoc, Metadata string - Hashes map[string]string + Bin, Abi, Devdoc, Userdoc, Metadata string } Version string } func (s *Solidity) makeArgs() []string { p := []string{ - "--combined-json", "bin,bin-runtime,srcmap,srcmap-runtime,abi,userdoc,devdoc", - "--optimize", // code optimizer switched on - "--allow-paths", "., ./, ../", // default to support relative paths + "--combined-json", "bin,abi,userdoc,devdoc", + "--optimize", // code optimizer switched on } if s.Major > 0 || s.Minor > 4 || s.Patch > 6 { - p[1] += ",metadata,hashes" + p[1] += ",metadata" } return p } @@ -134,7 +157,7 @@ func (s *Solidity) run(cmd *exec.Cmd, source string) (map[string]*Contract, erro // provided source, language and compiler version, and compiler options are all // passed through into the Contract structs. // -// The solc output is expected to contain ABI, source mapping, user docs, and dev docs. +// The solc output is expected to contain ABI, user docs, and dev docs. // // Returns an error if the JSON is malformed or missing data, or if the JSON // embedded within the JSON is malformed. @@ -143,6 +166,7 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin if err := json.Unmarshal(combinedJSON, &output); err != nil { return nil, err } + // Compilation succeeded, assemble and return the contracts. contracts := make(map[string]*Contract) for name, info := range output.Contracts { @@ -151,22 +175,22 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin if err := json.Unmarshal([]byte(info.Abi), &abi); err != nil { return nil, fmt.Errorf("solc: error reading abi definition (%v)", err) } - var userdoc, devdoc interface{} - json.Unmarshal([]byte(info.Userdoc), &userdoc) - json.Unmarshal([]byte(info.Devdoc), &devdoc) - + var userdoc interface{} + if err := json.Unmarshal([]byte(info.Userdoc), &userdoc); err != nil { + return nil, fmt.Errorf("solc: error reading user doc: %v", err) + } + var devdoc interface{} + if err := json.Unmarshal([]byte(info.Devdoc), &devdoc); err != nil { + return nil, fmt.Errorf("solc: error reading dev doc: %v", err) + } contracts[name] = &Contract{ - Code: "0x" + info.Bin, - RuntimeCode: "0x" + info.BinRuntime, - Hashes: info.Hashes, + Code: "0x" + info.Bin, Info: ContractInfo{ Source: source, Language: "Solidity", LanguageVersion: languageVersion, CompilerVersion: compilerVersion, CompilerOptions: compilerOptions, - SrcMap: info.SrcMap, - SrcMapRuntime: info.SrcMapRuntime, AbiDefinition: abi, UserDoc: userdoc, DeveloperDoc: devdoc, @@ -176,3 +200,15 @@ func ParseCombinedJSON(combinedJSON []byte, source string, languageVersion strin } return contracts, nil } + +func slurpFiles(files []string) (string, error) { + var concat bytes.Buffer + for _, file := range files { + content, err := ioutil.ReadFile(file) + if err != nil { + return "", err + } + concat.Write(content) + } + return concat.String(), nil +} diff --git a/common/compiler/solidity_test.go b/common/compiler/solidity_test.go index 491e3665..0da3bb33 100644 --- a/common/compiler/solidity_test.go +++ b/common/compiler/solidity_test.go @@ -23,10 +23,9 @@ import ( const ( testSource = ` -pragma solidity >0.0.0; contract test { /// @notice Will multiply ` + "`a`" + ` by 7. - function multiply(uint a) public returns(uint d) { + function multiply(uint a) returns(uint d) { return a * 7; } } @@ -39,7 +38,7 @@ func skipWithoutSolc(t *testing.T) { } } -func TestSolidityCompiler(t *testing.T) { +func TestCompiler(t *testing.T) { skipWithoutSolc(t) contracts, err := CompileSolidityString("", testSource) @@ -67,7 +66,7 @@ func TestSolidityCompiler(t *testing.T) { } } -func TestSolidityCompileError(t *testing.T) { +func TestCompileError(t *testing.T) { skipWithoutSolc(t) contracts, err := CompileSolidityString("", testSource[4:]) diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go index 94649e8f..abee6c43 100644 --- a/consensus/ethash/consensus.go +++ b/consensus/ethash/consensus.go @@ -460,7 +460,7 @@ func accumulateRewards(config *params.ChainConfig, statedb *state.StateDB, heade } if seroparam.Is_Dev() { - reward = new(big.Int).Mul(oneSero, big.NewInt(1000000)) + reward = new(big.Int).Set(oneSero) } //log.Info(fmt.Sprintf("BlockNumber = %v, gasLimie = %v, gasUsed = %v, reward = %v", header.Number.Uint64(), header.GasLimit, header.GasUsed, reward)) reward.Add(reward, new(big.Int).SetUint64(gasReward)) diff --git a/interfaces.go b/interfaces.go index e141635f..f307ccfc 100644 --- a/interfaces.go +++ b/interfaces.go @@ -22,12 +22,6 @@ import ( "errors" "math/big" - "github.com/sero-cash/go-sero/zero/txtool" - - "github.com/sero-cash/go-czero-import/c_type" - - "github.com/sero-cash/go-sero/common/address" - "github.com/sero-cash/go-sero/common" "github.com/sero-cash/go-sero/core/types" ) @@ -119,14 +113,12 @@ type ChainSyncReader interface { // CallMsg contains parameters for contract calls. type CallMsg struct { - From *address.PKAddress // the sender of the 'transaction' - RefundTo *c_type.PKr + From common.Address // the sender of the 'transaction' To *common.Address // the destination contract (nil for contract creation) Gas uint64 // if 0, the call executes with near-infinite gas GasPrice *big.Int // wei <-> gas exchange ratio Value *big.Int // amount of wei sent along with the call Data []byte // input data, usually an ABI-encoded contract method invocation - Currency string } // A ContractCaller provides contract calls, essentially transactions that are executed by @@ -177,7 +169,7 @@ type LogFilterer interface { // API can use package accounts to maintain local private keys and need can retrieve the // next available nonce using PendingNonceAt. type TransactionSender interface { - CommitTx(ctx context.Context, arg *txtool.GTx) error + SendTransaction(ctx context.Context, tx *types.Transaction) error } // GasPricer wraps the gas price oracle, which monitors the blockchain to determine the diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 206904f9..394ee49c 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -2028,15 +2028,6 @@ func (s *PublicTransactionPoolAPI) CommitTx(ctx context.Context, args *txtool.GT return s.b.CommitTx(args) } -func (s *PublicTransactionPoolAPI) CommitContractTx(ctx context.Context, args *txtool.GTx) (hash common.Hash, err error) { - err = s.b.CommitTx(args) - if err != nil { - return - } - hash = common.BytesToHash(args.Hash[:]) - return -} - func (s *PublicTransactionPoolAPI) ReSendTransaction(ctx context.Context, txhash common.Hash) (common.Hash, error) { pending, err := s.b.GetPoolTransactions() diff --git a/internal/ethapi/api_abi.go b/internal/ethapi/api_abi.go index 9b0e04f0..7cd8c419 100644 --- a/internal/ethapi/api_abi.go +++ b/internal/ethapi/api_abi.go @@ -94,8 +94,8 @@ func encodeStringParams(abiArgs abi.Arguments, args []string) ([]interface{}, [] if err != nil { return nil, nil, err } - //caddr := (c_superzk.HashPKr(addr.ToPKr().NewRef())) - packArgs[index] = address + caddr := (c_superzk.HashPKr(addr.ToPKr().NewRef())) + packArgs[index] = common.BytesToContractAddress(caddr[:]) address = append(address, addr.ToPKrAddress()) case "address[]": var addrs []AllMixedAddress @@ -103,7 +103,7 @@ func encodeStringParams(abiArgs abi.Arguments, args []string) ([]interface{}, [] if err != nil { return nil, nil, err } - packArgs[index] = addrs + packArgs[index] = convertToContractAddr(addrs) pkrs := convertToAddr(addrs) address = append(address, pkrs...) diff --git a/seroclient/seroclient.go b/seroclient/seroclient.go index 7ecb1c99..71554d99 100644 --- a/seroclient/seroclient.go +++ b/seroclient/seroclient.go @@ -24,12 +24,11 @@ import ( "fmt" "math/big" - "github.com/sero-cash/go-sero/zero/txtool" - sero "github.com/sero-cash/go-sero" "github.com/sero-cash/go-sero/common" "github.com/sero-cash/go-sero/common/hexutil" "github.com/sero-cash/go-sero/core/types" + "github.com/sero-cash/go-sero/rlp" "github.com/sero-cash/go-sero/rpc" ) @@ -449,54 +448,16 @@ func (ec *Client) EstimateGas(ctx context.Context, msg sero.CallMsg) (uint64, er return uint64(hex), nil } -func (ec *Client) GenContractTx(ctx context.Context, msg sero.CallMsg) (*txtool.GTxParam, error) { - var param txtool.GTxParam - if err := ec.c.CallContext(ctx, ¶m, "exchange_genTx", toContractTxArgs(msg)); err != nil { - return nil, err - } - return ¶m, nil -} - -func (ec *Client) CommitTx(ctx context.Context, arg *txtool.GTx) error { - var hash common.Hash - if err := ec.c.CallContext(ctx, &hash, "sero_commitContractTx", arg); err != nil { +// SendTransaction injects a signed transaction into the pending pool for execution. +// +// If the transaction was a contract creation use the TransactionReceipt method to get the +// contract address after the transaction has been mined. +func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error { + data, err := rlp.EncodeToBytes(tx) + if err != nil { return err } - return nil -} - -func toContractTxArgs(msg sero.CallMsg) interface{} { - arg := map[string]interface{}{ - "From": msg.From, - "RefundTo": msg.RefundTo, - } - - if msg.Gas != 0 { - arg["Gas"] = msg.Gas - } - if msg.GasPrice != nil { - arg["GasPrice"] = msg.GasPrice - } - - contractArgs := map[string]interface{}{} - - if msg.Currency != "" { - contractArgs["Currency"] = msg.Currency - } else { - contractArgs["Currency"] = "SERO" - } - contractArgs["Value"] = msg.Value - if msg.To != nil { - contractArgs["To"] = hexutil.Bytes(msg.To[:]) - } - if len(msg.Data) > 0 { - contractArgs["Data"] = hexutil.Bytes(msg.Data) - } - cmdArgs := map[string]interface{}{} - cmdArgs["Contract"] = contractArgs - - arg["Cmds"] = cmdArgs - return arg + return ec.c.CallContext(ctx, nil, "sero_sendRawTransaction", common.ToHex(data)) } func toCallArg(msg sero.CallMsg) interface{} { @@ -504,9 +465,6 @@ func toCallArg(msg sero.CallMsg) interface{} { "from": msg.From, "to": msg.To, } - if msg.RefundTo != nil { - arg["from"] = msg.RefundTo - } if len(msg.Data) > 0 { arg["data"] = hexutil.Bytes(msg.Data) } diff --git a/tests/abigen/testAbi.go b/tests/abigen/testAbi.go deleted file mode 100644 index 6b5b3212..00000000 --- a/tests/abigen/testAbi.go +++ /dev/null @@ -1,551 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package abigen - -import ( - "math/big" - "strings" - - sero "github.com/sero-cash/go-sero" - "github.com/sero-cash/go-sero/accounts/abi" - "github.com/sero-cash/go-sero/accounts/abi/bind" - "github.com/sero-cash/go-sero/common" - "github.com/sero-cash/go-sero/core/types" - "github.com/sero-cash/go-sero/event" -) - -// TestabiABI is the input ABI used to generate the binding from. -const TestabiABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"count\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"registerscode\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"infon\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address[]\"},{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"number\",\"outputs\":[{\"name\":\"a\",\"type\":\"uint32\"},{\"name\":\"b\",\"type\":\"uint64\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"own\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"registers\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"blockN\",\"outputs\":[{\"name\":\"\",\"type\":\"uint64\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addrs\",\"type\":\"address[]\"}],\"name\":\"registers\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"registers\",\"type\":\"address[]\"},{\"name\":\"registerscode\",\"type\":\"string\"},{\"name\":\"decimals\",\"type\":\"uint8\"},{\"name\":\"count\",\"type\":\"uint16\"},{\"name\":\"number\",\"type\":\"uint32\"},{\"name\":\"blockN\",\"type\":\"uint64\"},{\"name\":\"totalSupply\",\"type\":\"uint256\"},{\"name\":\"own\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"registers\",\"type\":\"address[]\"},{\"indexed\":false,\"name\":\"registerscode\",\"type\":\"string\"},{\"indexed\":false,\"name\":\"decimals\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"count\",\"type\":\"uint16\"},{\"indexed\":false,\"name\":\"number\",\"type\":\"uint32\"},{\"indexed\":false,\"name\":\"blockN\",\"type\":\"uint64\"},{\"indexed\":false,\"name\":\"totalSupply\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"own\",\"type\":\"address\"}],\"name\":\"constructorEvent\",\"type\":\"event\"}]" - -// TestabiBin is the compiled bytecode used for deploying new contracts. -const TestabiBin = `0x608060405234801561001057600080fd5b50604051610a3e380380610a3e8339810160409081528151602080840151928401516060850151608086015160a087015160c088015160e089015196890180519099989098019794969395929491939092909161007391600091908b0190610290565b5086516100879060019060208a01906102f5565b5085600260006101000a81548160ff021916908360ff16021790555084600260016101000a81548161ffff021916908361ffff16021790555083600260036101000a81548163ffffffff021916908363ffffffff16021790555082600260076101000a8154816001604060020a0302191690836001604060020a031602179055508160038190555080600460006101000a815481600160a060020a030219169083600160a060020a031602179055507f5d4c6f231ce175a28c0d89b77cb4a74c6a5f61efcc537d422a66c2220c8f8c0388888888888888886040518080602001806020018960ff1660ff1681526020018861ffff1661ffff1681526020018763ffffffff1663ffffffff168152602001866001604060020a03166001604060020a0316815260200185815260200184600160a060020a0316600160a060020a0316815260200183810383528b818151815260200191508051906020019060200280838360005b838110156102055781810151838201526020016101ed565b5050505090500183810382528a818151815260200191508051906020019080838360005b83811015610241578181015183820152602001610229565b50505050905090810190601f16801561026e5780820380516001836020036101000a031916815260200191505b509a505050505050505050505060405180910390a150505050505050506103b0565b8280548282559060005260206000209081019282156102e5579160200282015b828111156102e55782518254600160a060020a031916600160a060020a039091161782556020909201916001909101906102b0565b506102f192915061036f565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061033657805160ff1916838001178555610363565b82800160010185558215610363579182015b82811115610363578251825591602001919060010190610348565b506102f1929150610396565b61039391905b808211156102f1578054600160a060020a0319168155600101610375565b90565b61039391905b808211156102f1576000815560010161039c565b61067f806103bf6000396000f3006080604052600436106100a35763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306661abd81146100a857806318160ddd146100d45780631d44b1c2146100fb578063313ce5671461018557806359593c70146101b05780638381f58a1461023357806399cdee0e14610271578063a0d3d084146102a2578063a52dc2e714610307578063a818131a14610339575b600080fd5b3480156100b457600080fd5b506100bd6103a2565b6040805161ffff9092168252519081900360200190f35b3480156100e057600080fd5b506100e96103b2565b60408051918252519081900360200190f35b34801561010757600080fd5b506101106103b8565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561014a578181015183820152602001610132565b50505050905090810190601f1680156101775780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561019157600080fd5b5061019a61044d565b6040805160ff9092168252519081900360200190f35b3480156101bc57600080fd5b506101c5610456565b60408051600160a060020a038516815260ff8316918101919091526060602080830182815285519284019290925284516080840191868101910280838360005b8381101561021d578181015183820152602001610205565b5050505090500194505050505060405180910390f35b34801561023f57600080fd5b506102486104dd565b6040805163ffffffff909316835267ffffffffffffffff90911660208301528051918290030190f35b34801561027d57600080fd5b50610286610507565b60408051600160a060020a039092168252519081900360200190f35b3480156102ae57600080fd5b506102b7610516565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156102f35781810151838201526020016102db565b505050509050019250505060405180910390f35b34801561031357600080fd5b5061031c610577565b6040805167ffffffffffffffff9092168252519081900360200190f35b34801561034557600080fd5b506040805160206004803580820135838102808601850190965280855261038e953695939460249493850192918291850190849080828437509497506105929650505050505050565b604080519115158252519081900360200190f35b600254610100900461ffff165b90565b60035490565b60018054604080516020601f600260001961010087891615020190951694909404938401819004810282018101909252828152606093909290918301828280156104435780601f1061041857610100808354040283529160200191610443565b820191906000526020600020905b81548152906001019060200180831161042657829003601f168201915b5050505050905090565b60025460ff1690565b600454600254600080546040805160208084028201810190925282815292946060948694600160a060020a0390921693859360ff90921692918491908301828280156104cb57602002820191906000526020600020905b8154600160a060020a031681526001909101906020018083116104ad575b50505050509150925092509250909192565b6002546301000000810463ffffffff169167010000000000000090910467ffffffffffffffff1690565b600454600160a060020a031690565b6060600080548060200260200160405190810160405280929190818152602001828054801561044357602002820191906000526020600020905b8154600160a060020a03168152600190910190602001808311610550575050505050905090565b600254670100000000000000900467ffffffffffffffff1690565b80516000906105a790829060208501906105b0565b50600192915050565b828054828255906000526020600020908101928215610612579160200282015b82811115610612578251825473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a039091161782556020909201916001909101906105d0565b5061061e929150610622565b5090565b6103af91905b8082111561061e57805473ffffffffffffffffffffffffffffffffffffffff191681556001016106285600a165627a7a72305820ca5b03515993c293931836dd754566ba471e6435977179567ef9c5e54c721d320029` - -// DeployTestabi deploys a new Ethereum contract, binding an instance of Testabi to it. -func DeployTestabi(auth *bind.TransactOpts, backend bind.ContractBackend, registers []common.Address, registerscode string, decimals uint8, count uint16, number uint32, blockN uint64, totalSupply *big.Int, own common.Address) (common.Address, *types.Transaction, *Testabi, error) { - parsed, err := abi.JSON(strings.NewReader(TestabiABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(TestabiBin), backend, registers, registerscode, decimals, count, number, blockN, totalSupply, own) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &Testabi{TestabiCaller: TestabiCaller{contract: contract}, TestabiTransactor: TestabiTransactor{contract: contract}, TestabiFilterer: TestabiFilterer{contract: contract}}, nil -} - -// Testabi is an auto generated Go binding around an Ethereum contract. -type Testabi struct { - TestabiCaller // Read-only binding to the contract - TestabiTransactor // Write-only binding to the contract - TestabiFilterer // Log filterer for contract events -} - -// TestabiCaller is an auto generated read-only Go binding around an Ethereum contract. -type TestabiCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestabiTransactor is an auto generated write-only Go binding around an Ethereum contract. -type TestabiTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestabiFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type TestabiFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestabiSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type TestabiSession struct { - Contract *Testabi // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TestabiCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type TestabiCallerSession struct { - Contract *TestabiCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// TestabiTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type TestabiTransactorSession struct { - Contract *TestabiTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TestabiRaw is an auto generated low-level Go binding around an Ethereum contract. -type TestabiRaw struct { - Contract *Testabi // Generic contract binding to access the raw methods on -} - -// TestabiCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type TestabiCallerRaw struct { - Contract *TestabiCaller // Generic read-only contract binding to access the raw methods on -} - -// TestabiTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type TestabiTransactorRaw struct { - Contract *TestabiTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewTestabi creates a new instance of Testabi, bound to a specific deployed contract. -func NewTestabi(address common.Address, backend bind.ContractBackend) (*Testabi, error) { - contract, err := bindTestabi(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Testabi{TestabiCaller: TestabiCaller{contract: contract}, TestabiTransactor: TestabiTransactor{contract: contract}, TestabiFilterer: TestabiFilterer{contract: contract}}, nil -} - -// NewTestabiCaller creates a new read-only instance of Testabi, bound to a specific deployed contract. -func NewTestabiCaller(address common.Address, caller bind.ContractCaller) (*TestabiCaller, error) { - contract, err := bindTestabi(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &TestabiCaller{contract: contract}, nil -} - -// NewTestabiTransactor creates a new write-only instance of Testabi, bound to a specific deployed contract. -func NewTestabiTransactor(address common.Address, transactor bind.ContractTransactor) (*TestabiTransactor, error) { - contract, err := bindTestabi(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &TestabiTransactor{contract: contract}, nil -} - -// NewTestabiFilterer creates a new log filterer instance of Testabi, bound to a specific deployed contract. -func NewTestabiFilterer(address common.Address, filterer bind.ContractFilterer) (*TestabiFilterer, error) { - contract, err := bindTestabi(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &TestabiFilterer{contract: contract}, nil -} - -// bindTestabi binds a generic wrapper to an already deployed contract. -func bindTestabi(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(TestabiABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Testabi *TestabiRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { - return _Testabi.Contract.TestabiCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Testabi *TestabiRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Testabi.Contract.TestabiTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Testabi *TestabiRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Testabi.Contract.TestabiTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Testabi *TestabiCallerRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { - return _Testabi.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Testabi *TestabiTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { - return _Testabi.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Testabi *TestabiTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { - return _Testabi.Contract.contract.Transact(opts, method, params...) -} - -// BlockN is a free data retrieval call binding the contract method 0xa52dc2e7. -// -// Solidity: function blockN() constant returns(uint64) -func (_Testabi *TestabiCaller) BlockN(opts *bind.CallOpts) (uint64, error) { - var ( - ret0 = new(uint64) - ) - out := ret0 - err := _Testabi.contract.Call(opts, out, "blockN") - return *ret0, err -} - -// BlockN is a free data retrieval call binding the contract method 0xa52dc2e7. -// -// Solidity: function blockN() constant returns(uint64) -func (_Testabi *TestabiSession) BlockN() (uint64, error) { - return _Testabi.Contract.BlockN(&_Testabi.CallOpts) -} - -// BlockN is a free data retrieval call binding the contract method 0xa52dc2e7. -// -// Solidity: function blockN() constant returns(uint64) -func (_Testabi *TestabiCallerSession) BlockN() (uint64, error) { - return _Testabi.Contract.BlockN(&_Testabi.CallOpts) -} - -// Count is a free data retrieval call binding the contract method 0x06661abd. -// -// Solidity: function count() constant returns(uint16) -func (_Testabi *TestabiCaller) Count(opts *bind.CallOpts) (uint16, error) { - var ( - ret0 = new(uint16) - ) - out := ret0 - err := _Testabi.contract.Call(opts, out, "count") - return *ret0, err -} - -// Count is a free data retrieval call binding the contract method 0x06661abd. -// -// Solidity: function count() constant returns(uint16) -func (_Testabi *TestabiSession) Count() (uint16, error) { - return _Testabi.Contract.Count(&_Testabi.CallOpts) -} - -// Count is a free data retrieval call binding the contract method 0x06661abd. -// -// Solidity: function count() constant returns(uint16) -func (_Testabi *TestabiCallerSession) Count() (uint16, error) { - return _Testabi.Contract.Count(&_Testabi.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() constant returns(uint8) -func (_Testabi *TestabiCaller) Decimals(opts *bind.CallOpts) (uint8, error) { - var ( - ret0 = new(uint8) - ) - out := ret0 - err := _Testabi.contract.Call(opts, out, "decimals") - return *ret0, err -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() constant returns(uint8) -func (_Testabi *TestabiSession) Decimals() (uint8, error) { - return _Testabi.Contract.Decimals(&_Testabi.CallOpts) -} - -// Decimals is a free data retrieval call binding the contract method 0x313ce567. -// -// Solidity: function decimals() constant returns(uint8) -func (_Testabi *TestabiCallerSession) Decimals() (uint8, error) { - return _Testabi.Contract.Decimals(&_Testabi.CallOpts) -} - -// Infon is a free data retrieval call binding the contract method 0x59593c70. -// -// Solidity: function infon() constant returns(address, address[], uint8) -func (_Testabi *TestabiCaller) Infon(opts *bind.CallOpts) (common.Address, []common.Address, uint8, error) { - var ( - ret0 = new(common.Address) - ret1 = new([]common.Address) - ret2 = new(uint8) - ) - out := &[]interface{}{ - ret0, - ret1, - ret2, - } - err := _Testabi.contract.Call(opts, out, "infon") - return *ret0, *ret1, *ret2, err -} - -// Infon is a free data retrieval call binding the contract method 0x59593c70. -// -// Solidity: function infon() constant returns(address, address[], uint8) -func (_Testabi *TestabiSession) Infon() (common.Address, []common.Address, uint8, error) { - return _Testabi.Contract.Infon(&_Testabi.CallOpts) -} - -// Infon is a free data retrieval call binding the contract method 0x59593c70. -// -// Solidity: function infon() constant returns(address, address[], uint8) -func (_Testabi *TestabiCallerSession) Infon() (common.Address, []common.Address, uint8, error) { - return _Testabi.Contract.Infon(&_Testabi.CallOpts) -} - -// Number is a free data retrieval call binding the contract method 0x8381f58a. -// -// Solidity: function number() constant returns(a uint32, b uint64) -func (_Testabi *TestabiCaller) Number(opts *bind.CallOpts) (struct { - A uint32 - B uint64 -}, error) { - ret := new(struct { - A uint32 - B uint64 - }) - out := ret - err := _Testabi.contract.Call(opts, out, "number") - return *ret, err -} - -// Number is a free data retrieval call binding the contract method 0x8381f58a. -// -// Solidity: function number() constant returns(a uint32, b uint64) -func (_Testabi *TestabiSession) Number() (struct { - A uint32 - B uint64 -}, error) { - return _Testabi.Contract.Number(&_Testabi.CallOpts) -} - -// Number is a free data retrieval call binding the contract method 0x8381f58a. -// -// Solidity: function number() constant returns(a uint32, b uint64) -func (_Testabi *TestabiCallerSession) Number() (struct { - A uint32 - B uint64 -}, error) { - return _Testabi.Contract.Number(&_Testabi.CallOpts) -} - -// Own is a free data retrieval call binding the contract method 0x99cdee0e. -// -// Solidity: function own() constant returns(address) -func (_Testabi *TestabiCaller) Own(opts *bind.CallOpts) (common.Address, error) { - var ( - ret0 = new(common.Address) - ) - out := ret0 - err := _Testabi.contract.Call(opts, out, "own") - return *ret0, err -} - -// Own is a free data retrieval call binding the contract method 0x99cdee0e. -// -// Solidity: function own() constant returns(address) -func (_Testabi *TestabiSession) Own() (common.Address, error) { - return _Testabi.Contract.Own(&_Testabi.CallOpts) -} - -// Own is a free data retrieval call binding the contract method 0x99cdee0e. -// -// Solidity: function own() constant returns(address) -func (_Testabi *TestabiCallerSession) Own() (common.Address, error) { - return _Testabi.Contract.Own(&_Testabi.CallOpts) -} - -// Registerscode is a free data retrieval call binding the contract method 0x1d44b1c2. -// -// Solidity: function registerscode() constant returns(string) -func (_Testabi *TestabiCaller) Registerscode(opts *bind.CallOpts) (string, error) { - var ( - ret0 = new(string) - ) - out := ret0 - err := _Testabi.contract.Call(opts, out, "registerscode") - return *ret0, err -} - -// Registerscode is a free data retrieval call binding the contract method 0x1d44b1c2. -// -// Solidity: function registerscode() constant returns(string) -func (_Testabi *TestabiSession) Registerscode() (string, error) { - return _Testabi.Contract.Registerscode(&_Testabi.CallOpts) -} - -// Registerscode is a free data retrieval call binding the contract method 0x1d44b1c2. -// -// Solidity: function registerscode() constant returns(string) -func (_Testabi *TestabiCallerSession) Registerscode() (string, error) { - return _Testabi.Contract.Registerscode(&_Testabi.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() constant returns(uint256) -func (_Testabi *TestabiCaller) TotalSupply(opts *bind.CallOpts) (*big.Int, error) { - var ( - ret0 = new(*big.Int) - ) - out := ret0 - err := _Testabi.contract.Call(opts, out, "totalSupply") - return *ret0, err -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() constant returns(uint256) -func (_Testabi *TestabiSession) TotalSupply() (*big.Int, error) { - return _Testabi.Contract.TotalSupply(&_Testabi.CallOpts) -} - -// TotalSupply is a free data retrieval call binding the contract method 0x18160ddd. -// -// Solidity: function totalSupply() constant returns(uint256) -func (_Testabi *TestabiCallerSession) TotalSupply() (*big.Int, error) { - return _Testabi.Contract.TotalSupply(&_Testabi.CallOpts) -} - -// Registers is a paid mutator transaction binding the contract method 0xa818131a. -// -// Solidity: function registers(addrs address[]) returns(bool) -func (_Testabi *TestabiTransactor) Registers(opts *bind.TransactOpts, addrs []common.Address) (*types.Transaction, error) { - return _Testabi.contract.Transact(opts, "registers", addrs) -} - -// Registers is a paid mutator transaction binding the contract method 0xa818131a. -// -// Solidity: function registers(addrs address[]) returns(bool) -func (_Testabi *TestabiSession) Registers(addrs []common.Address) (*types.Transaction, error) { - return _Testabi.Contract.Registers(&_Testabi.TransactOpts, addrs) -} - -// Registers is a paid mutator transaction binding the contract method 0xa818131a. -// -// Solidity: function registers(addrs address[]) returns(bool) -func (_Testabi *TestabiTransactorSession) Registers(addrs []common.Address) (*types.Transaction, error) { - return _Testabi.Contract.Registers(&_Testabi.TransactOpts, addrs) -} - -// TestabiConstructorEventIterator is returned from FilterConstructorEvent and is used to iterate over the raw logs and unpacked data for ConstructorEvent events raised by the Testabi contract. -type TestabiConstructorEventIterator struct { - Event *TestabiConstructorEvent // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub sero.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TestabiConstructorEventIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TestabiConstructorEvent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TestabiConstructorEvent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TestabiConstructorEventIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TestabiConstructorEventIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TestabiConstructorEvent represents a ConstructorEvent event raised by the Testabi contract. -type TestabiConstructorEvent struct { - Registers []common.Address - Registerscode string - Decimals uint8 - Count uint16 - Number uint32 - BlockN uint64 - TotalSupply *big.Int - Own common.Address - Raw types.Log // Blockchain specific contextual infos -} - -// FilterConstructorEvent is a free log retrieval operation binding the contract event 0x5d4c6f231ce175a28c0d89b77cb4a74c6a5f61efcc537d422a66c2220c8f8c03. -// -// Solidity: e constructorEvent(registers address[], registerscode string, decimals uint8, count uint16, number uint32, blockN uint64, totalSupply uint256, own address) -func (_Testabi *TestabiFilterer) FilterConstructorEvent(opts *bind.FilterOpts) (*TestabiConstructorEventIterator, error) { - - logs, sub, err := _Testabi.contract.FilterLogs(opts, "constructorEvent") - if err != nil { - return nil, err - } - return &TestabiConstructorEventIterator{contract: _Testabi.contract, event: "constructorEvent", logs: logs, sub: sub}, nil -} - -// WatchConstructorEvent is a free log subscription operation binding the contract event 0x5d4c6f231ce175a28c0d89b77cb4a74c6a5f61efcc537d422a66c2220c8f8c03. -// -// Solidity: e constructorEvent(registers address[], registerscode string, decimals uint8, count uint16, number uint32, blockN uint64, totalSupply uint256, own address) -func (_Testabi *TestabiFilterer) WatchConstructorEvent(opts *bind.WatchOpts, sink chan<- *TestabiConstructorEvent) (event.Subscription, error) { - - logs, sub, err := _Testabi.contract.WatchLogs(opts, "constructorEvent") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TestabiConstructorEvent) - if err := _Testabi.contract.UnpackLog(event, "constructorEvent", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} diff --git a/tests/abigen/testAbi.sol b/tests/abigen/testAbi.sol deleted file mode 100644 index 07553fc7..00000000 --- a/tests/abigen/testAbi.sol +++ /dev/null @@ -1,90 +0,0 @@ -pragma solidity ^0.4.16; - - -contract testabi { - - - address[] private _registers; - string private _registerscode; - uint8 private _decimals; - uint16 private _count; - uint32 private _number; - uint64 private _block; - uint256 _totalSupply; - address private _own; - - event constructorEvent( address[] registers, - string registerscode, - uint8 decimals, - uint16 count, - uint32 number, - uint64 blockN, - uint256 totalSupply, - address own); - - constructor( - address[] registers, - string registerscode, - uint8 decimals, - uint16 count, - uint32 number, - uint64 blockN, - uint256 totalSupply, - address own) public{ - _registers = registers; - _registerscode=registerscode; - _decimals=decimals; - _count=count; - _number=number; - _block=blockN; - _totalSupply=totalSupply; - _own=own; - emit constructorEvent(registers,registerscode,decimals,count,number,blockN,totalSupply,own); - } - - function registers( address[] addrs) public returns(bool){ - _registers=addrs; - return true; - } - - function infon() public view returns(address,address[],uint8){ - return (_own,_registers,_decimals); - } - - /** - * @return the number of decimals of the token. - */ - function decimals() public view returns (uint8) { - return _decimals; - } - - function totalSupply() public view returns (uint256) { - return _totalSupply; - } - - function registerscode() public view returns (string) { - return _registerscode; - } - - function number() public view returns ( uint32 a, uint64 b) { - a=_number; - b=_block; - return; - } - - function blockN() public view returns (uint64) { - return _block; - } - - function registers() public view returns (address[]) { - return _registers; - } - function count() public view returns (uint16) { - return _count; - } - - function own() public view returns (address) { - return _own; - } - -} \ No newline at end of file diff --git a/tests/abigen_test.go b/tests/abigen_test.go deleted file mode 100644 index d4e85b46..00000000 --- a/tests/abigen_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package tests - -import ( - "context" - "fmt" - "log" - "math/big" - "strings" - "testing" - "time" - - "github.com/sero-cash/go-sero/common" - "github.com/sero-cash/go-sero/tests/abigen" - - "github.com/sero-cash/go-sero/accounts/abi/bind" - "github.com/sero-cash/go-sero/seroclient" -) - -const keyStr = ` -{ - "address": "3bG34svmC3pwCazHtsV7t1p5ihvaSBu2pA27CsnrsdJY5yCkf1ZqAKGArV6gHpeDHieiXScL5FKdgJTgHBiwe1uU", - "tk": "3bG34svmC3pwCazHtsV7t1p5ihvaSBu2pA27CsnrsdJY1ENvjxfeC4vGQfigJ54nX4od4BM5tsT48WbnDpFFGAJn", - "crypto": { - "cipher": "aes-128-ctr", - "ciphertext": "3138a97b25721f0829106aa652d3ea76483078be253bacb30449c0e6f970a097", - "cipherparams": { - "iv": "b29008189567795220a84bf7d8dfaf01" - }, - "kdf": "scrypt", - "kdfparams": { - "dklen": 32, - "n": 262144, - "p": 1, - "r": 8, - "salt": "1a238ac93b466659368dbd89cb5558fbc09a8fde256c7e3daef5b778857e456c" - }, - "mac": "a23300101025fd7ed170f69a283655688e0d05e073177f252fb9326fc626127b" - }, - "id": "e5b057ac-2119-4cf5-9584-047828207eb3", - "version": 1, - "at": 0 -} -` - -func TestDeploy(t *testing.T) { - conn, err := seroclient.Dial("http://127.0.0.1:8545") - if err != nil { - log.Fatalf("Failed to connect to the Ethereum client: %v", err) - } - //value := big.NewInt(0).Mul(big.NewInt(1000000000), big.NewInt(1000000000)) - auth, err := bind.NewTransactor(strings.NewReader(keyStr), "123456", nil) - if err != nil { - log.Fatalf("Failed to create authorized transactor: %v", err) - } - // Deploy a new awesome contract for the binding demo - - registers := []common.Address{common.Base58ToAddress("iQe7iX45yGZeQnxjdxgo7SZJfyWpWPaKmQJyR5UuPM2Aq1BJDUuFvh5bLtquiwuzdWCxmYXMW1LbhHZC4vDBgAhuRxZGtQr7zoTjkHH6Z1vMzUQNGjBAXE5nkufjjAzfWBZ")} - - registerscode := "registerscode" - decimals := uint8(8) - count := uint16(16) - number := uint32(32) - blockN := uint64(64) - totalSupply := big.NewInt(1000000) - own := common.Base58ToAddress("wg5cNrx3qeh6xea8nNQqrWEu5etbCauo7Ek75XhmWQnmQAyesBjVMbDwWLZdeUYfXj4eB7YAPBmqAyUcBgYuCFBRdHjuE8PQsaEPp5MTXpE7zBt6wcsEyzuguGd4NMw3i7H") - - _, tx, testAbi, err := abigen.DeployTestabi(auth, conn, registers, registerscode, decimals, count, number, blockN, totalSupply, own) - if err != nil { - log.Fatalf("Failed to deploy new token contract: %v", err) - } - fmt.Printf("Transaction waiting to be mined: 0x%x\n\n", tx.Hash()) - startTime := time.Now() - fmt.Printf("TX start @:%s", time.Now()) - ctx := context.Background() - addressAfterMined, err := bind.WaitDeployed(ctx, conn, tx) - if err != nil { - log.Fatalf("failed to deploy contact when mining :%v", err) - } - fmt.Printf("tx mining take time:%s\n", time.Now().Sub(startTime)) - log.Printf("mined address :%s", addressAfterMined.String()) - - name, err := testAbi.Own(&bind.CallOpts{Pending: true}) - if err != nil { - log.Fatalf("Failed to retrieve pending name: %v", err) - } - fmt.Println("Pending name:", name) -} - -func TestCall(t *testing.T) { - conn, err := seroclient.Dial("http://127.0.0.1:8545") - if err != nil { - log.Fatalf("Failed to connect to the Ethereum client: %v", err) - } - contractAddress := common.Base58ToAddress("25rwV92apLVTVcTyjhAKx2izEmEvpVv5kwoDBi1anWC2HtChJNVg3o4uHTaMxAPmYTUTRM1kLvNDdZLiFXgCJVsg") - testAbi, err := abigen.NewTestabi(contractAddress, conn) - if err != nil { - log.Fatalf("Failed to NewTestabi : %v", err) - } - e, err := testAbi.Number(&bind.CallOpts{}) - if err != nil { - log.Fatalf("Failed to retrieve pending name: %v", err) - } - fmt.Println(e.A, e.B) -} - -func TestExcute(t *testing.T) { - conn, err := seroclient.Dial("http://127.0.0.1:8545") - if err != nil { - log.Fatalf("Failed to connect to the Ethereum client: %v", err) - } - //value := big.NewInt(0).Mul(big.NewInt(1000000000), big.NewInt(1000000000)) - auth, err := bind.NewTransactor(strings.NewReader(keyStr), "123456", nil) - if err != nil { - log.Fatalf("Failed to create authorized transactor: %v", err) - } - // Deploy a new awesome contract for the binding demo - - registers := []common.Address{common.Base58ToAddress("2WmLwyPZ7e8E1pSrQavxXGtXbHyqQGuWAWnZdPGG5UQ7y1epSFJWNMdtmrfbYoHKviQ42AB872Ccp3EP3uzpWxCSxx9ZBn6a6E3fbGQEMT6xETV4xKEc8Nf5VMYRZYYXszHh")} - - contractAddress := common.Base58ToAddress("25rwV92apLVTVcTyjhAKx2izEmEvpVv5kwoDBi1anWC2HtChJNVg3o4uHTaMxAPmYTUTRM1kLvNDdZLiFXgCJVsg") - testAbi, err := abigen.NewTestabi(contractAddress, conn) - if err != nil { - log.Fatalf("Failed to NewTestabi : %v", err) - } - e, err := testAbi.Registers(auth, registers) - if err != nil { - log.Fatalf("Failed to retrieve pending name: %v", err) - } - fmt.Println(e) -} diff --git a/tests/state_test.go b/tests/state_test.go index c976a4f2..cb32f5d2 100644 --- a/tests/state_test.go +++ b/tests/state_test.go @@ -47,8 +47,8 @@ func TestState(t *testing.T) { t.Skip("constantinople not supported yet") } withTrace(t, test.gasLimit(subtest), func(vmconfig vm.Config) error { - //_, err := test.Run(subtest, vmconfig) - return st.checkFailure(t, name, nil) + _, err := test.Run(subtest, vmconfig) + return st.checkFailure(t, name, err) }) }) }