mobile: fix mobile interface

This commit is contained in:
rjl493456442 2019-02-27 19:39:34 +08:00
parent 30c2b1b06d
commit acf308b25e
6 changed files with 240 additions and 42 deletions

View file

@ -452,7 +452,6 @@ const tmplSourceJava = `
package {{.Package}};
import org.ethereum.geth.*;
import org.ethereum.geth.internal.*;
{{range $contract := .Contracts}}
public class {{.Type}} {
@ -461,7 +460,7 @@ import org.ethereum.geth.internal.*;
{{if .InputBin}}
// BYTECODE is the compiled bytecode used for deploying new contracts.
public final static byte[] BYTECODE = "{{.InputBin}}".getBytes();
public final static String BYTECODE = "{{.InputBin}}";
// deploy deploys a new Ethereum contract, binding an instance of {{.Type}} to it.
public static {{.Type}} deploy(TransactOpts auth, EthereumClient client{{range .Constructor.Inputs}}, {{bindtype .Type}} {{.Name}}{{end}}) throws Exception {
@ -469,7 +468,7 @@ import org.ethereum.geth.internal.*;
{{range $index, $element := .Constructor.Inputs}}
args.set({{$index}}, Geth.newInterface()); args.get({{$index}}).set{{namedtype (bindtype .Type) .Type}}({{.Name}});
{{end}}
return new {{.Type}}(Geth.deployContract(auth, ABI, BYTECODE, client, args));
return new {{.Type}}(Geth.deployContract(auth, ABI, Geth.fromHex(BYTECODE), client, args));
}
// Internal constructor used by contract deployment.

View file

@ -21,25 +21,28 @@ package geth
import (
"math/big"
"strings"
"errors"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/accounts/keystore"
)
// Signer is an interaface defining the callback when a contract requires a
// Signer is an interface defining the callback when a contract requires a
// method to sign the transaction before submission.
type Signer interface {
Sign(*Address, *Transaction) (tx *Transaction, _ error)
}
type signer struct {
type MobileSigner struct {
sign bind.SignerFn
}
func (s *signer) Sign(addr *Address, unsignedTx *Transaction) (signedTx *Transaction, _ error) {
sig, err := s.sign(types.HomesteadSigner{}, addr.address, unsignedTx.tx)
func (s *MobileSigner) Sign(addr *Address, unsignedTx *Transaction) (signedTx *Transaction, _ error) {
sig, err := s.sign(types.EIP155Signer{}, addr.address, unsignedTx.tx)
if err != nil {
return nil, err
}
@ -73,6 +76,35 @@ type TransactOpts struct {
opts bind.TransactOpts
}
// NewTransactOpts creates a new option set for contract transaction.
func NewTransactOpts() *TransactOpts {
return new(TransactOpts)
}
// NewKeyedTransactor is a utility method to easily create a transaction signer
// from a single private key.
func NewKeyedTransactOpts(keyJson []byte, passphrase string) (*TransactOpts, error) {
key, err := keystore.DecryptKey(keyJson, passphrase)
if err != nil {
return nil, err
}
keyAddr := crypto.PubkeyToAddress(key.PrivateKey.PublicKey)
opts := bind.TransactOpts{
From: keyAddr,
Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) {
if address != keyAddr {
return nil, errors.New("not authorized to sign this account")
}
signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key.PrivateKey)
if err != nil {
return nil, err
}
return tx.WithSignature(signer, signature)
},
}
return &TransactOpts{opts}, nil
}
func (opts *TransactOpts) GetFrom() *Address { return &Address{opts.opts.From} }
func (opts *TransactOpts) GetNonce() int64 { return opts.opts.Nonce.Int64() }
func (opts *TransactOpts) GetValue() *BigInt { return &BigInt{opts.opts.Value} }
@ -119,7 +151,7 @@ func DeployContract(opts *TransactOpts, abiJSON string, bytecode []byte, client
if err != nil {
return nil, err
}
addr, tx, bound, err := bind.DeployContract(&opts.opts, parsed, common.CopyBytes(bytecode), client.client, args.objects...)
addr, tx, bound, err := bind.DeployContract(&opts.opts, parsed, common.CopyBytes(bytecode), client.client, args.value()...)
if err != nil {
return nil, err
}
@ -155,25 +187,27 @@ func (c *BoundContract) GetDeployer() *Transaction {
// sets the output to result.
func (c *BoundContract) Call(opts *CallOpts, out *Interfaces, method string, args *Interfaces) error {
if len(out.objects) == 1 {
result := out.objects[0]
if err := c.contract.Call(&opts.opts, result, method, args.objects...); err != nil {
result := out.objects[0].object
if err := c.contract.Call(&opts.opts, &result, method, args.value()...); err != nil {
return err
}
out.objects[0] = result
out.objects[0].object = result
} else {
results := make([]interface{}, len(out.objects))
copy(results, out.objects)
if err := c.contract.Call(&opts.opts, &results, method, args.objects...); err != nil {
copy(results, out.value())
if err := c.contract.Call(&opts.opts, &results, method, args.value()...); err != nil {
return err
}
copy(out.objects, results)
for index, result := range results {
out.objects[index].object = result
}
}
return nil
}
// Transact invokes the (paid) contract method with params as input values.
func (c *BoundContract) Transact(opts *TransactOpts, method string, args *Interfaces) (tx *Transaction, _ error) {
rawTx, err := c.contract.Transact(&opts.opts, method, args.objects...)
rawTx, err := c.contract.Transact(&opts.opts, method, args.value()...)
if err != nil {
return nil, err
}

View file

@ -228,3 +228,17 @@ func (a *Addresses) Set(index int, address *Address) error {
func (a *Addresses) Append(address *Address) {
a.addresses = append(a.addresses, address.address)
}
// ToHex returns the hex representation of b, prefixed with '0x'.
// For empty slices, the return value is "0x0".
//
// Deprecated: use hexutil.Encode instead.
func ToHex(b []byte) string {
return common.ToHex(b)
}
// FromHex returns the bytes represented by the hexadecimal string s.
// s may be prefixed with "0x".
func FromHex(s string) []byte {
return common.FromHex(s)
}

View file

@ -42,26 +42,26 @@ func NewInterface() *Interface {
return new(Interface)
}
func (i *Interface) SetBool(b bool) { i.object = &b }
func (i *Interface) SetBools(bs []bool) { i.object = &bs }
func (i *Interface) SetString(str string) { i.object = &str }
func (i *Interface) SetStrings(strs *Strings) { i.object = &strs.strs }
func (i *Interface) SetBinary(binary []byte) { b := common.CopyBytes(binary); i.object = &b }
func (i *Interface) SetBinaries(binaries [][]byte) { i.object = &binaries }
func (i *Interface) SetAddress(address *Address) { i.object = &address.address }
func (i *Interface) SetAddresses(addrs *Addresses) { i.object = &addrs.addresses }
func (i *Interface) SetHash(hash *Hash) { i.object = &hash.hash }
func (i *Interface) SetHashes(hashes *Hashes) { i.object = &hashes.hashes }
func (i *Interface) SetInt8(n int8) { i.object = &n }
func (i *Interface) SetInt16(n int16) { i.object = &n }
func (i *Interface) SetInt32(n int32) { i.object = &n }
func (i *Interface) SetInt64(n int64) { i.object = &n }
func (i *Interface) SetUint8(bigint *BigInt) { n := uint8(bigint.bigint.Uint64()); i.object = &n }
func (i *Interface) SetUint16(bigint *BigInt) { n := uint16(bigint.bigint.Uint64()); i.object = &n }
func (i *Interface) SetUint32(bigint *BigInt) { n := uint32(bigint.bigint.Uint64()); i.object = &n }
func (i *Interface) SetUint64(bigint *BigInt) { n := bigint.bigint.Uint64(); i.object = &n }
func (i *Interface) SetBigInt(bigint *BigInt) { i.object = &bigint.bigint }
func (i *Interface) SetBigInts(bigints *BigInts) { i.object = &bigints.bigints }
func (i *Interface) SetBool(b bool) { i.object = &b }
func (i *Interface) SetBools(bs *Bools) { i.object = &bs.bools }
func (i *Interface) SetString(str string) { i.object = &str }
func (i *Interface) SetStrings(strs *Strings) { i.object = &strs.strs }
func (i *Interface) SetBinary(binary []byte) { b := common.CopyBytes(binary); i.object = &b }
func (i *Interface) SetBinaries(binaries *Binaries) { i.object = &binaries.binaries }
func (i *Interface) SetAddress(address *Address) { i.object = &address.address }
func (i *Interface) SetAddresses(addrs *Addresses) { i.object = &addrs.addresses }
func (i *Interface) SetHash(hash *Hash) { i.object = &hash.hash }
func (i *Interface) SetHashes(hashes *Hashes) { i.object = &hashes.hashes }
func (i *Interface) SetInt8(n int8) { i.object = &n }
func (i *Interface) SetInt16(n int16) { i.object = &n }
func (i *Interface) SetInt32(n int32) { i.object = &n }
func (i *Interface) SetInt64(n int64) { i.object = &n }
func (i *Interface) SetUint8(bigint *BigInt) { n := uint8(bigint.bigint.Uint64()); i.object = &n }
func (i *Interface) SetUint16(bigint *BigInt) { n := uint16(bigint.bigint.Uint64()); i.object = &n }
func (i *Interface) SetUint32(bigint *BigInt) { n := uint32(bigint.bigint.Uint64()); i.object = &n }
func (i *Interface) SetUint64(bigint *BigInt) { n := bigint.bigint.Uint64(); i.object = &n }
func (i *Interface) SetBigInt(bigint *BigInt) { i.object = &bigint.bigint }
func (i *Interface) SetBigInts(bigints *BigInts) { i.object = &bigints.bigints }
func (i *Interface) SetDefaultBool() { i.object = new(bool) }
func (i *Interface) SetDefaultBools() { i.object = new([]bool) }
@ -85,11 +85,11 @@ func (i *Interface) SetDefaultBigInt() { i.object = new(*big.Int) }
func (i *Interface) SetDefaultBigInts() { i.object = new([]*big.Int) }
func (i *Interface) GetBool() bool { return *i.object.(*bool) }
func (i *Interface) GetBools() []bool { return *i.object.(*[]bool) }
func (i *Interface) GetBools() *Bools { return &Bools{*i.object.(*[]bool)} }
func (i *Interface) GetString() string { return *i.object.(*string) }
func (i *Interface) GetStrings() *Strings { return &Strings{*i.object.(*[]string)} }
func (i *Interface) GetBinary() []byte { return *i.object.(*[]byte) }
func (i *Interface) GetBinaries() [][]byte { return *i.object.(*[][]byte) }
func (i *Interface) GetBinaries() *Binaries { return &Binaries{*i.object.(*[][]byte)} }
func (i *Interface) GetAddress() *Address { return &Address{*i.object.(*common.Address)} }
func (i *Interface) GetAddresses() *Addresses { return &Addresses{*i.object.(*[]common.Address)} }
func (i *Interface) GetHash() *Hash { return &Hash{*i.object.(*common.Hash)} }
@ -115,14 +115,16 @@ func (i *Interface) GetBigInts() *BigInts { return &BigInts{*i.object.(*[]*big.I
// Interfaces is a slices of wrapped generic objects.
type Interfaces struct {
objects []interface{}
objects []*Interface // Notably, each element in the objects is not nil
}
// NewInterfaces creates a slice of uninitialized interfaces.
func NewInterfaces(size int) *Interfaces {
return &Interfaces{
objects: make([]interface{}, size),
ifaces := &Interfaces{objects: make([]*Interface, size)}
for i := 0; i < ifaces.Size(); i++ {
ifaces.objects[i] = NewInterface()
}
return ifaces
}
// Size returns the number of interfaces in the slice.
@ -135,7 +137,7 @@ func (i *Interfaces) Get(index int) (iface *Interface, _ error) {
if index < 0 || index >= len(i.objects) {
return nil, errors.New("index out of bounds")
}
return &Interface{i.objects[index]}, nil
return i.objects[index], nil
}
// Set sets the big int at the given index in the slice.
@ -143,6 +145,17 @@ func (i *Interfaces) Set(index int, object *Interface) error {
if index < 0 || index >= len(i.objects) {
return errors.New("index out of bounds")
}
i.objects[index] = object.object
i.objects[index].object = object.object
return nil
}
// value returns a batch of embedded values.
//
// Notably, this function won't be exposed.
func (i *Interfaces) value() []interface{} {
values := make([]interface{}, 0, i.Size())
for index := 0; index < i.Size(); index += 1 {
values = append(values, i.objects[index].object)
}
return values
}

76
mobile/interface_test.go Normal file
View file

@ -0,0 +1,76 @@
// 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 <http://www.gnu.org/licenses/>.
package geth
import (
"fmt"
"math/big"
"reflect"
"testing"
"github.com/ethereum/go-ethereum/common"
)
func TestInterfaceGetSet(t *testing.T) {
var tests = []struct {
method string
input interface{}
expect interface{}
}{
{"Bool", true, true},
{"Bool", false, false},
{"Bools", &Bools{[]bool{false, true}}, &Bools{[]bool{false, true}}},
{"String", "go-ethereum", "go-ethereum"},
{"Strings", &Strings{strs: []string{"hello", "world"}}, &Strings{strs: []string{"hello", "world"}}},
{"Binary", []byte{0x01, 0x02}, []byte{0x01, 0x02}},
{"Binaries", &Binaries{[][]byte{{0x01, 0x02}, {0x03, 0x04}}}, &Binaries{[][]byte{{0x01, 0x02}, {0x03, 0x04}}}},
{"Address", &Address{common.HexToAddress("deadbeef")}, &Address{common.HexToAddress("deadbeef")}},
{"Addresses", &Addresses{[]common.Address{common.HexToAddress("deadbeef"), common.HexToAddress("cafebabe")}}, &Addresses{[]common.Address{common.HexToAddress("deadbeef"), common.HexToAddress("cafebabe")}}},
{"Hash", &Hash{common.HexToHash("deadbeef")}, &Hash{common.HexToHash("deadbeef")}},
{"Hashes", &Hashes{[]common.Hash{common.HexToHash("deadbeef"), common.HexToHash("cafebabe")}}, &Hashes{[]common.Hash{common.HexToHash("deadbeef"), common.HexToHash("cafebabe")}}},
{"Int8", int8(1), int8(1)},
{"Int16", int16(1), int16(1)},
{"Int32", int32(1), int32(1)},
{"Int64", int64(1), int64(1)},
{"Uint8", NewBigInt(1), NewBigInt(1)},
{"Uint16", NewBigInt(1), NewBigInt(1)},
{"Uint32", NewBigInt(1), NewBigInt(1)},
{"Uint64", NewBigInt(1), NewBigInt(1)},
{"BigInt", NewBigInt(1), NewBigInt(1)},
{"BigInts", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}},
}
args := NewInterfaces(len(tests))
callFn := func(receiver interface{}, method string, arg interface{}) interface{} {
rval := reflect.ValueOf(receiver)
rval.MethodByName(fmt.Sprintf("Set%s", method)).Call([]reflect.Value{reflect.ValueOf(arg)})
res := rval.MethodByName(fmt.Sprintf("Get%s", method)).Call(nil)
if len(res) > 0 {
return res[0].Interface()
}
return nil
}
for index, c := range tests {
iface, _ := args.Get(index)
result := callFn(iface, c.method, c.input)
if !reflect.DeepEqual(result, c.expect) {
t.Errorf("Interface get/set mismatch, want %v, got %v", c.expect, result)
}
}
}

View file

@ -21,6 +21,8 @@ package geth
import (
"errors"
"fmt"
"github.com/ethereum/go-ethereum/common"
)
// Strings represents s slice of strs.
@ -52,3 +54,63 @@ func (s *Strings) Set(index int, str string) error {
func (s *Strings) String() string {
return fmt.Sprintf("%v", s.strs)
}
// Bools represents a slice of bool.
type Bools struct{ bools []bool }
// Size returns the number of bool in the slice.
func (bs *Bools) Size() int {
return len(bs.bools)
}
// Get returns the bool at the given index from the slice.
func (bs *Bools) Get(index int) (b bool, _ error) {
if index < 0 || index >= len(bs.bools) {
return false, errors.New("index out of bounds")
}
return bs.bools[index], nil
}
// Set sets the bool at the given index in the slice.
func (bs *Bools) Set(index int, b bool) error {
if index < 0 || index >= len(bs.bools) {
return errors.New("index out of bounds")
}
bs.bools[index] = b
return nil
}
// String implements the Stringer interface.
func (bs *Bools) String() string {
return fmt.Sprintf("%v", bs.bools)
}
// Binaries represents a slice of byte slice
type Binaries struct{ binaries [][]byte }
// Size returns the number of byte slice in the slice.
func (bs *Binaries) Size() int {
return len(bs.binaries)
}
// Get returns the byte slice at the given index from the slice.
func (bs *Binaries) Get(index int) (binary []byte, _ error) {
if index < 0 || index >= len(bs.binaries) {
return nil, errors.New("index out of bounds")
}
return common.CopyBytes(bs.binaries[index]), nil
}
// Set sets the byte slice at the given index in the slice.
func (bs *Binaries) Set(index int, binary []byte) error {
if index < 0 || index >= len(bs.binaries) {
return errors.New("index out of bounds")
}
bs.binaries[index] = common.CopyBytes(binary)
return nil
}
// String implements the Stringer interface.
func (bs *Binaries) String() string {
return fmt.Sprintf("%v", bs.binaries)
}