accounts, build, mobile: remove Android and iOS support (#26599)

This commit is contained in:
JukLee0ira 2024-11-14 15:17:12 +08:00
parent 77b0c0b88f
commit cba5782884
26 changed files with 10 additions and 2982 deletions

1
.github/CODEOWNERS vendored
View file

@ -7,5 +7,4 @@ core/ @karalabe @holiman
eth/ @karalabe
les/ @zsfelfoldi
light/ @zsfelfoldi
mobile/ @karalabe
p2p/ @fjl @zsfelfoldi

View file

@ -37,8 +37,6 @@ type Lang int
const (
LangGo Lang = iota
LangJava
LangObjC
)
// Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant
@ -160,15 +158,15 @@ 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,
LangJava: bindTypeJava,
LangGo: bindTypeGo,
}
// Helper function for the binding generators.
// It reads the unmatched characters after the inner type-match,
// (since the inner type is a prefix of the total type declaration),
// looks for valid arrays (possibly a dynamic one) wrapping the inner type,
// and returns the sizes of these arrays.
//
// (since the inner type is a prefix of the total type declaration),
// looks for valid arrays (possibly a dynamic one) wrapping the inner type,
// and returns the sizes of these arrays.
//
// Returned array sizes are in the same order as solidity signatures; inner array size first.
// Array sizes may also be "", indicating a dynamic array.
@ -244,15 +242,6 @@ func arrayBindingJava(inner string, arraySizes []string) string {
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.
@ -311,8 +300,7 @@ func bindUnnestedTypeJava(stringKind string) (int, string) {
// 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,
LangJava: bindTopicTypeJava,
LangGo: bindTopicTypeGo,
}
// bindTypeGo converts a Solidity topic type to a Go one. It is almost the same
@ -325,64 +313,16 @@ 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") },
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
}
}
LangGo: func(string, abi.Type) string { panic("this shouldn't be needed") },
}
// 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,
LangJava: decapitalise,
LangGo: capitalise,
}
// capitalise makes a camel-case string which starts with an upper case character.

View file

@ -52,8 +52,7 @@ 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,
LangJava: tmplSourceJava,
LangGo: tmplSourceGo,
}
// tmplSourceGo is the Go source template use to generate the contract binding
@ -418,105 +417,3 @@ package {{.Package}}
{{end}}
{{end}}
`
// tmplSourceJava is the Java source template use to generate the contract binding
// based on.
const tmplSourceJava = `
// This file is an automatically generated Java binding. Do not modify as any
// change will likely be lost upon the next re-generation!
package {{.Package}};
import org.ethereum.geth.*;
import org.ethereum.geth.internal.*;
{{range $contract := .Contracts}}
public class {{.Type}} {
// ABI is the input ABI used to generate the binding from.
public final static String ABI = "{{.InputABI}}";
{{if .InputBin}}
// BYTECODE is the compiled bytecode used for deploying new contracts.
public final static byte[] BYTECODE = "{{.InputBin}}".getBytes();
// 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 {
Interfaces args = Geth.newInterfaces({{(len .Constructor.Inputs)}});
{{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));
}
// Internal constructor used by contract deployment.
private {{.Type}}(BoundContract deployment) {
this.Address = deployment.getAddress();
this.Deployer = deployment.getDeployer();
this.Contract = deployment;
}
{{end}}
// Ethereum address where this contract is located at.
public final Address Address;
// Ethereum transaction in which this contract was deployed (if known!).
public final Transaction Deployer;
// Contract instance bound to a blockchain address.
private final BoundContract Contract;
// Creates a new instance of {{.Type}}, bound to a specific deployed contract.
public {{.Type}}(Address address, EthereumClient client) throws Exception {
this(Geth.bindContract(address, ABI, client));
}
{{range .Calls}}
{{if gt (len .Normalized.Outputs) 1}}
// {{capitalise .Normalized.Name}}Results is the output of a call to {{.Normalized.Name}}.
public class {{capitalise .Normalized.Name}}Results {
{{range $index, $item := .Normalized.Outputs}}public {{bindtype .Type}} {{if ne .Name ""}}{{.Name}}{{else}}Return{{$index}}{{end}};
{{end}}
}
{{end}}
// {{.Normalized.Name}} is a free data retrieval call binding the contract method 0x{{printf "%x" .Original.Id}}.
//
// Solidity: {{.Original.String}}
public {{if gt (len .Normalized.Outputs) 1}}{{capitalise .Normalized.Name}}Results{{else}}{{range .Normalized.Outputs}}{{bindtype .Type}}{{end}}{{end}} {{.Normalized.Name}}(CallOpts opts{{range .Normalized.Inputs}}, {{bindtype .Type}} {{.Name}}{{end}}) throws Exception {
Interfaces args = Geth.newInterfaces({{(len .Normalized.Inputs)}});
{{range $index, $item := .Normalized.Inputs}}args.set({{$index}}, Geth.newInterface()); args.get({{$index}}).set{{namedtype (bindtype .Type) .Type}}({{.Name}});
{{end}}
Interfaces results = Geth.newInterfaces({{(len .Normalized.Outputs)}});
{{range $index, $item := .Normalized.Outputs}}Interface result{{$index}} = Geth.newInterface(); result{{$index}}.setDefault{{namedtype (bindtype .Type) .Type}}(); results.set({{$index}}, result{{$index}});
{{end}}
if (opts == null) {
opts = Geth.newCallOpts();
}
this.Contract.call(opts, results, "{{.Original.Name}}", args);
{{if gt (len .Normalized.Outputs) 1}}
{{capitalise .Normalized.Name}}Results result = new {{capitalise .Normalized.Name}}Results();
{{range $index, $item := .Normalized.Outputs}}result.{{if ne .Name ""}}{{.Name}}{{else}}Return{{$index}}{{end}} = results.get({{$index}}).get{{namedtype (bindtype .Type) .Type}}();
{{end}}
return result;
{{else}}{{range .Normalized.Outputs}}return results.get(0).get{{namedtype (bindtype .Type) .Type}}();{{end}}
{{end}}
}
{{end}}
{{range .Transacts}}
// {{.Normalized.Name}} is a paid mutator transaction binding the contract method 0x{{printf "%x" .Original.Id}}.
//
// Solidity: {{.Original.String}}
public Transaction {{.Normalized.Name}}(TransactOpts opts{{range .Normalized.Inputs}}, {{bindtype .Type}} {{.Name}}{{end}}) throws Exception {
Interfaces args = Geth.newInterfaces({{(len .Normalized.Inputs)}});
{{range $index, $item := .Normalized.Inputs}}args.set({{$index}}, Geth.newInterface()); args.get({{$index}}).set{{namedtype (bindtype .Type) .Type}}({{.Name}});
{{end}}
return this.Contract.transact(opts, "{{.Original.Name}}" , args);
}
{{end}}
}
{{end}}
`

View file

@ -38,7 +38,7 @@ var (
pkgFlag = flag.String("pkg", "", "Package name to generate the binding into")
outFlag = flag.String("out", "", "Output file for the generated binding (default = stdout)")
langFlag = flag.String("lang", "go", "Destination language for the bindings (go, java, objc)")
langFlag = flag.String("lang", "go", "Destination language for the bindings (go)")
)
func main() {
@ -60,10 +60,6 @@ func main() {
switch *langFlag {
case "go":
lang = bind.LangGo
case "java":
lang = bind.LangJava
case "objc":
lang = bind.LangObjC
default:
fmt.Printf("Unsupported destination language \"%s\" (--lang)\n", *langFlag)
os.Exit(-1)

View file

@ -1,221 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the accounts package to support client side key
// management on mobile platforms.
package geth
import (
"errors"
"time"
"github.com/XinFinOrg/XDPoSChain/accounts"
"github.com/XinFinOrg/XDPoSChain/accounts/keystore"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/crypto"
)
const (
// StandardScryptN is the N parameter of Scrypt encryption algorithm, using 256MB
// memory and taking approximately 1s CPU time on a modern processor.
StandardScryptN = int(keystore.StandardScryptN)
// StandardScryptP is the P parameter of Scrypt encryption algorithm, using 256MB
// memory and taking approximately 1s CPU time on a modern processor.
StandardScryptP = int(keystore.StandardScryptP)
// LightScryptN is the N parameter of Scrypt encryption algorithm, using 4MB
// memory and taking approximately 100ms CPU time on a modern processor.
LightScryptN = int(keystore.LightScryptN)
// LightScryptP is the P parameter of Scrypt encryption algorithm, using 4MB
// memory and taking approximately 100ms CPU time on a modern processor.
LightScryptP = int(keystore.LightScryptP)
)
// Account represents a stored key.
type Account struct{ account accounts.Account }
// Accounts represents a slice of accounts.
type Accounts struct{ accounts []accounts.Account }
// Size returns the number of accounts in the slice.
func (a *Accounts) Size() int {
return len(a.accounts)
}
// Get returns the account at the given index from the slice.
func (a *Accounts) Get(index int) (account *Account, _ error) {
if index < 0 || index >= len(a.accounts) {
return nil, errors.New("index out of bounds")
}
return &Account{a.accounts[index]}, nil
}
// Set sets the account at the given index in the slice.
func (a *Accounts) Set(index int, account *Account) error {
if index < 0 || index >= len(a.accounts) {
return errors.New("index out of bounds")
}
a.accounts[index] = account.account
return nil
}
// GetAddress retrieves the address associated with the account.
func (a *Account) GetAddress() *Address {
return &Address{a.account.Address}
}
// GetURL retrieves the canonical URL of the account.
func (a *Account) GetURL() string {
return a.account.URL.String()
}
// KeyStore manages a key storage directory on disk.
type KeyStore struct{ keystore *keystore.KeyStore }
// NewKeyStore creates a keystore for the given directory.
func NewKeyStore(keydir string, scryptN, scryptP int) *KeyStore {
return &KeyStore{keystore: keystore.NewKeyStore(keydir, scryptN, scryptP)}
}
// HasAddress reports whether a key with the given address is present.
func (ks *KeyStore) HasAddress(address *Address) bool {
return ks.keystore.HasAddress(address.address)
}
// GetAccounts returns all key files present in the directory.
func (ks *KeyStore) GetAccounts() *Accounts {
return &Accounts{ks.keystore.Accounts()}
}
// DeleteAccount deletes the key matched by account if the passphrase is correct.
// If a contains no filename, the address must match a unique key.
func (ks *KeyStore) DeleteAccount(account *Account, passphrase string) error {
return ks.keystore.Delete(account.account, passphrase)
}
// SignHash calculates a ECDSA signature for the given hash. The produced signature
// is in the [R || S || V] format where V is 0 or 1.
func (ks *KeyStore) SignHash(address *Address, hash []byte) (signature []byte, _ error) {
return ks.keystore.SignHash(accounts.Account{Address: address.address}, common.CopyBytes(hash))
}
// SignTx signs the given transaction with the requested account.
func (ks *KeyStore) SignTx(account *Account, tx *Transaction, chainID *BigInt) (*Transaction, error) {
if chainID == nil { // Null passed from mobile app
chainID = new(BigInt)
}
signed, err := ks.keystore.SignTx(account.account, tx.tx, chainID.bigint)
if err != nil {
return nil, err
}
return &Transaction{signed}, nil
}
// SignHashPassphrase signs hash if the private key matching the given address can
// be decrypted with the given passphrase. The produced signature is in the
// [R || S || V] format where V is 0 or 1.
func (ks *KeyStore) SignHashPassphrase(account *Account, passphrase string, hash []byte) (signature []byte, _ error) {
return ks.keystore.SignHashWithPassphrase(account.account, passphrase, common.CopyBytes(hash))
}
// SignTxPassphrase signs the transaction if the private key matching the
// given address can be decrypted with the given passphrase.
func (ks *KeyStore) SignTxPassphrase(account *Account, passphrase string, tx *Transaction, chainID *BigInt) (*Transaction, error) {
if chainID == nil { // Null passed from mobile app
chainID = new(BigInt)
}
signed, err := ks.keystore.SignTxWithPassphrase(account.account, passphrase, tx.tx, chainID.bigint)
if err != nil {
return nil, err
}
return &Transaction{signed}, nil
}
// Unlock unlocks the given account indefinitely.
func (ks *KeyStore) Unlock(account *Account, passphrase string) error {
return ks.keystore.TimedUnlock(account.account, passphrase, 0)
}
// Lock removes the private key with the given address from memory.
func (ks *KeyStore) Lock(address *Address) error {
return ks.keystore.Lock(address.address)
}
// TimedUnlock unlocks the given account with the passphrase. The account stays
// unlocked for the duration of timeout (nanoseconds). A timeout of 0 unlocks the
// account until the program exits. The account must match a unique key file.
//
// If the account address is already unlocked for a duration, TimedUnlock extends or
// shortens the active unlock timeout. If the address was previously unlocked
// indefinitely the timeout is not altered.
func (ks *KeyStore) TimedUnlock(account *Account, passphrase string, timeout int64) error {
return ks.keystore.TimedUnlock(account.account, passphrase, time.Duration(timeout))
}
// NewAccount generates a new key and stores it into the key directory,
// encrypting it with the passphrase.
func (ks *KeyStore) NewAccount(passphrase string) (*Account, error) {
account, err := ks.keystore.NewAccount(passphrase)
if err != nil {
return nil, err
}
return &Account{account}, nil
}
// UpdateAccount changes the passphrase of an existing account.
func (ks *KeyStore) UpdateAccount(account *Account, passphrase, newPassphrase string) error {
return ks.keystore.Update(account.account, passphrase, newPassphrase)
}
// ExportKey exports as a JSON key, encrypted with newPassphrase.
func (ks *KeyStore) ExportKey(account *Account, passphrase, newPassphrase string) (key []byte, _ error) {
return ks.keystore.Export(account.account, passphrase, newPassphrase)
}
// ImportKey stores the given encrypted JSON key into the key directory.
func (ks *KeyStore) ImportKey(keyJSON []byte, passphrase, newPassphrase string) (account *Account, _ error) {
acc, err := ks.keystore.Import(common.CopyBytes(keyJSON), passphrase, newPassphrase)
if err != nil {
return nil, err
}
return &Account{acc}, nil
}
// ImportECDSAKey stores the given encrypted JSON key into the key directory.
func (ks *KeyStore) ImportECDSAKey(key []byte, passphrase string) (account *Account, _ error) {
privkey, err := crypto.ToECDSA(common.CopyBytes(key))
if err != nil {
return nil, err
}
acc, err := ks.keystore.ImportECDSA(privkey, passphrase)
if err != nil {
return nil, err
}
return &Account{acc}, nil
}
// ImportPreSaleKey decrypts the given Ethereum presale wallet and stores
// a key file in the key directory. The key file is encrypted with the same passphrase.
func (ks *KeyStore) ImportPreSaleKey(keyJSON []byte, passphrase string) (ccount *Account, _ error) {
account, err := ks.keystore.ImportPreSaleKey(common.CopyBytes(keyJSON), passphrase)
if err != nil {
return nil, err
}
return &Account{account}, nil
}

View file

@ -1,266 +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 <http://www.gnu.org/licenses/>.
package geth
import (
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/XinFinOrg/XDPoSChain/internal/build"
)
// androidTestClass is a Java class to do some lightweight tests against the Android
// bindings. The goal is not to test each individual functionality, rather just to
// catch breaking API and/or implementation changes.
const androidTestClass = `
package go;
import android.test.InstrumentationTestCase;
import android.test.MoreAsserts;
import java.math.BigInteger;
import java.util.Arrays;
import org.ethereum.geth.*;
public class AndroidTest extends InstrumentationTestCase {
public AndroidTest() {}
public void testAccountManagement() {
// Create an encrypted keystore with light crypto parameters.
KeyStore ks = new KeyStore(getInstrumentation().getContext().getFilesDir() + "/keystore", Geth.LightScryptN, Geth.LightScryptP);
try {
// Create a new account with the specified encryption passphrase.
Account newAcc = ks.newAccount("Creation password");
// Export the newly created account with a different passphrase. The returned
// data from this method invocation is a JSON encoded, encrypted key-file.
byte[] jsonAcc = ks.exportKey(newAcc, "Creation password", "Export password");
// Update the passphrase on the account created above inside the local keystore.
ks.updateAccount(newAcc, "Creation password", "Update password");
// Delete the account updated above from the local keystore.
ks.deleteAccount(newAcc, "Update password");
// Import back the account we've exported (and then deleted) above with yet
// again a fresh passphrase.
Account impAcc = ks.importKey(jsonAcc, "Export password", "Import password");
// Create a new account to sign transactions with
Account signer = ks.newAccount("Signer password");
Transaction tx = new Transaction(
1, new Address("0x0000000000000000000000000000000000000000"),
new BigInt(0), 0, new BigInt(1), null); // Random empty transaction
BigInt chain = new BigInt(1); // Chain identifier of the main net
// Sign a transaction with a single authorization
Transaction signed = ks.signTxPassphrase(signer, "Signer password", tx, chain);
// Sign a transaction with multiple manually cancelled authorizations
ks.unlock(signer, "Signer password");
signed = ks.signTx(signer, tx, chain);
ks.lock(signer.getAddress());
// Sign a transaction with multiple automatically cancelled authorizations
ks.timedUnlock(signer, "Signer password", 1000000000);
signed = ks.signTx(signer, tx, chain);
} catch (Exception e) {
fail(e.toString());
}
}
public void testInprocNode() {
Context ctx = new Context();
try {
// Start up a new inprocess node
Node node = new Node(getInstrumentation().getContext().getFilesDir() + "/.ethereum", new NodeConfig());
node.start();
// Retrieve some data via function calls (we don't really care about the results)
NodeInfo info = node.getNodeInfo();
info.getName();
info.getListenerAddress();
info.getProtocols();
// Retrieve some data via the APIs (we don't really care about the results)
EthereumClient ec = node.getEthereumClient();
ec.getBlockByNumber(ctx, -1).getNumber();
NewHeadHandler handler = new NewHeadHandler() {
@Override public void onError(String error) {}
@Override public void onNewHead(final Header header) {}
};
ec.subscribeNewHead(ctx, handler, 16);
} catch (Exception e) {
fail(e.toString());
}
}
// Tests that recovering transaction signers works for both Homestead and EIP155
// signatures too. Regression test for go-ethereum issue #14599.
public void testIssue14599() {
try {
byte[] preEIP155RLP = new BigInteger("f901fc8032830138808080b901ae60056013565b6101918061001d6000396000f35b3360008190555056006001600060e060020a6000350480630a874df61461003a57806341c0e1b514610058578063a02b161e14610066578063dbbdf0831461007757005b610045600435610149565b80600160a060020a031660005260206000f35b610060610161565b60006000f35b6100716004356100d4565b60006000f35b61008560043560243561008b565b60006000f35b600054600160a060020a031632600160a060020a031614156100ac576100b1565b6100d0565b8060018360005260205260406000208190555081600060005260206000a15b5050565b600054600160a060020a031633600160a060020a031614158015610118575033600160a060020a0316600182600052602052604060002054600160a060020a031614155b61012157610126565b610146565b600060018260005260205260406000208190555080600060005260206000a15b50565b60006001826000526020526040600020549050919050565b600054600160a060020a031633600160a060020a0316146101815761018f565b600054600160a060020a0316ff5b561ca0c5689ed1ad124753d54576dfb4b571465a41900a1dff4058d8adf16f752013d0a01221cbd70ec28c94a3b55ec771bcbc70778d6ee0b51ca7ea9514594c861b1884", 16).toByteArray();
preEIP155RLP = Arrays.copyOfRange(preEIP155RLP, 1, preEIP155RLP.length);
byte[] postEIP155RLP = new BigInteger("f86b80847735940082520894ef5bbb9bba2e1ca69ef81b23a8727d889f3ef0a1880de0b6b3a7640000802ba06fef16c44726a102e6d55a651740636ef8aec6df3ebf009e7b0c1f29e4ac114aa057e7fbc69760b522a78bb568cfc37a58bfdcf6ea86cb8f9b550263f58074b9cc", 16).toByteArray();
postEIP155RLP = Arrays.copyOfRange(postEIP155RLP, 1, postEIP155RLP.length);
Transaction preEIP155 = new Transaction(preEIP155RLP);
Transaction postEIP155 = new Transaction(postEIP155RLP);
preEIP155.getFrom(null); // Homestead should accept homestead
preEIP155.getFrom(new BigInt(4)); // EIP155 should accept homestead (missing chain ID)
postEIP155.getFrom(new BigInt(4)); // EIP155 should accept EIP 155
try {
postEIP155.getFrom(null);
fail("EIP155 transaction accepted by Homestead");
} catch (Exception e) {}
} catch (Exception e) {
fail(e.toString());
}
}
}
`
// TestAndroid runs the Android java test class specified above.
//
// This requires the gradle command in PATH and the Android SDK whose path is available
// through ANDROID_HOME environment variable. To successfully run the tests, an Android
// device must also be available with debugging enabled.
//
// This method has been adapted from golang.org/x/mobile/bind/java/seq_test.go/runTest
func TestAndroid(t *testing.T) {
t.Skip("skip this test since it's not being used")
// Skip tests on Windows altogether
if runtime.GOOS == "windows" {
t.Skip("cannot test Android bindings on Windows, skipping")
}
// Make sure all the Android tools are installed
if _, err := exec.Command("which", "gradle").CombinedOutput(); err != nil {
t.Skip("command gradle not found, skipping")
}
if sdk := os.Getenv("ANDROID_HOME"); sdk == "" {
// Android SDK not explicitly given, try to auto-resolve
autopath := filepath.Join(os.Getenv("HOME"), "Android", "Sdk")
if _, err := os.Stat(autopath); err != nil {
t.Skip("ANDROID_HOME environment var not set, skipping")
}
os.Setenv("ANDROID_HOME", autopath)
}
if _, err := exec.Command("which", "gomobile").CombinedOutput(); err != nil {
t.Log("gomobile missing, installing it...")
if out, err := exec.Command("go", "get", "golang.org/x/mobile/cmd/gomobile").CombinedOutput(); err != nil {
t.Fatalf("install failed: %v\n%s", err, string(out))
}
t.Log("initializing gomobile...")
start := time.Now()
if _, err := exec.Command("gomobile", "init").CombinedOutput(); err != nil {
t.Fatalf("initialization failed: %v", err)
}
t.Logf("initialization took %v", time.Since(start))
}
// Create and switch to a temporary workspace
workspace, err := os.MkdirTemp("", "geth-android-")
if err != nil {
t.Fatalf("failed to create temporary workspace: %v", err)
}
defer os.RemoveAll(workspace)
pwd, err := os.Getwd()
if err != nil {
t.Fatalf("failed to get current working directory: %v", err)
}
if err := os.Chdir(workspace); err != nil {
t.Fatalf("failed to switch to temporary workspace: %v", err)
}
defer os.Chdir(pwd)
// Create the skeleton of the Android project
for _, dir := range []string{"src/main", "src/androidTest/java/org/ethereum/gethtest", "libs"} {
err = os.MkdirAll(dir, os.ModePerm)
if err != nil {
t.Fatal(err)
}
}
// Generate the mobile bindings for Geth and add the tester class
gobind := exec.Command("gomobile", "bind", "-javapkg", "org.ethereum", "github.com/XinFinOrg/XDPoSChain/mobile")
if output, err := gobind.CombinedOutput(); err != nil {
t.Logf("%s", output)
t.Fatalf("failed to run gomobile bind: %v", err)
}
build.CopyFile(filepath.Join("libs", "geth.aar"), "geth.aar", os.ModePerm)
if err = os.WriteFile(filepath.Join("src", "androidTest", "java", "org", "ethereum", "gethtest", "AndroidTest.java"), []byte(androidTestClass), os.ModePerm); err != nil {
t.Fatalf("failed to write Android test class: %v", err)
}
// Finish creating the project and run the tests via gradle
if err = os.WriteFile(filepath.Join("src", "main", "AndroidManifest.xml"), []byte(androidManifest), os.ModePerm); err != nil {
t.Fatalf("failed to write Android manifest: %v", err)
}
if err = os.WriteFile("build.gradle", []byte(gradleConfig), os.ModePerm); err != nil {
t.Fatalf("failed to write gradle build file: %v", err)
}
if output, err := exec.Command("gradle", "connectedAndroidTest").CombinedOutput(); err != nil {
t.Logf("%s", output)
t.Errorf("failed to run gradle test: %v", err)
}
}
const androidManifest = `<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.ethereum.gethtest"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
</manifest>`
const gradleConfig = `buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
}
}
allprojects {
repositories { jcenter() }
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 'android-19'
buildToolsVersion '21.1.2'
defaultConfig { minSdkVersion 15 }
}
repositories {
flatDir { dirs 'libs' }
}
dependencies {
compile 'com.android.support:appcompat-v7:19.0.0'
compile(name: "geth", ext: "aar")
}
`

View file

@ -1,112 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the math/big package.
package geth
import (
"errors"
"math/big"
"github.com/XinFinOrg/XDPoSChain/common"
)
// A BigInt represents a signed multi-precision integer.
type BigInt struct {
bigint *big.Int
}
// NewBigInt allocates and returns a new BigInt set to x.
func NewBigInt(x int64) *BigInt {
return &BigInt{big.NewInt(x)}
}
// GetBytes returns the absolute value of x as a big-endian byte slice.
func (bi *BigInt) GetBytes() []byte {
return bi.bigint.Bytes()
}
// String returns the value of x as a formatted decimal string.
func (bi *BigInt) String() string {
return bi.bigint.String()
}
// GetInt64 returns the int64 representation of x. If x cannot be represented in
// an int64, the result is undefined.
func (bi *BigInt) GetInt64() int64 {
return bi.bigint.Int64()
}
// SetBytes interprets buf as the bytes of a big-endian unsigned integer and sets
// the big int to that value.
func (bi *BigInt) SetBytes(buf []byte) {
bi.bigint.SetBytes(common.CopyBytes(buf))
}
// SetInt64 sets the big int to x.
func (bi *BigInt) SetInt64(x int64) {
bi.bigint.SetInt64(x)
}
// Sign returns:
//
// -1 if x < 0
// 0 if x == 0
// +1 if x > 0
//
func (bi *BigInt) Sign() int {
return bi.bigint.Sign()
}
// SetString sets the big int to x.
//
// The string prefix determines the actual conversion base. A prefix of "0x" or
// "0X" selects base 16; the "0" prefix selects base 8, and a "0b" or "0B" prefix
// selects base 2. Otherwise the selected base is 10.
func (bi *BigInt) SetString(x string, base int) {
bi.bigint.SetString(x, base)
}
// BigInts represents a slice of big ints.
type BigInts struct{ bigints []*big.Int }
// Size returns the number of big ints in the slice.
func (bi *BigInts) Size() int {
return len(bi.bigints)
}
// Get returns the bigint at the given index from the slice.
func (bi *BigInts) Get(index int) (bigint *BigInt, _ error) {
if index < 0 || index >= len(bi.bigints) {
return nil, errors.New("index out of bounds")
}
return &BigInt{bi.bigints[index]}, nil
}
// Set sets the big int at the given index in the slice.
func (bi *BigInts) Set(index int, bigint *BigInt) error {
if index < 0 || index >= len(bi.bigints) {
return errors.New("index out of bounds")
}
bi.bigints[index] = bigint.bigint
return nil
}
// GetString returns the value of x as a formatted string in some number base.
func (bi *BigInt) GetString(base int) string {
return bi.bigint.Text(base)
}

View file

@ -1,191 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the bind package.
package geth
import (
"math/big"
"strings"
"github.com/XinFinOrg/XDPoSChain/accounts/abi"
"github.com/XinFinOrg/XDPoSChain/accounts/abi/bind"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/types"
)
// Signer is an interaface 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 {
sign bind.SignerFn
}
func (s *signer) Sign(addr *Address, unsignedTx *Transaction) (signedTx *Transaction, _ error) {
sig, err := s.sign(addr.address, unsignedTx.tx)
if err != nil {
return nil, err
}
return &Transaction{sig}, nil
}
// CallOpts is the collection of options to fine tune a contract call request.
type CallOpts struct {
opts bind.CallOpts
}
// NewCallOpts creates a new option set for contract calls.
func NewCallOpts() *CallOpts {
return new(CallOpts)
}
func (opts *CallOpts) IsPending() bool { return opts.opts.Pending }
func (opts *CallOpts) GetGasLimit() int64 { return 0 /* TODO(karalabe) */ }
// GetContext cannot be reliably implemented without identity preservation (https://github.com/golang/go/issues/16876)
// Even then it's awkward to unpack the subtleties of a Go context out to Java.
// func (opts *CallOpts) GetContext() *Context { return &Context{opts.opts.Context} }
func (opts *CallOpts) SetPending(pending bool) { opts.opts.Pending = pending }
func (opts *CallOpts) SetGasLimit(limit int64) { /* TODO(karalabe) */ }
func (opts *CallOpts) SetContext(context *Context) { opts.opts.Context = context.context }
// TransactOpts is the collection of authorization data required to create a
// valid Ethereum transaction.
type TransactOpts struct {
opts bind.TransactOpts
}
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} }
func (opts *TransactOpts) GetGasPrice() *BigInt { return &BigInt{opts.opts.GasPrice} }
func (opts *TransactOpts) GetGasLimit() int64 { return int64(opts.opts.GasLimit) }
// GetSigner cannot be reliably implemented without identity preservation (https://github.com/golang/go/issues/16876)
// func (opts *TransactOpts) GetSigner() Signer { return &signer{opts.opts.Signer} }
// GetContext cannot be reliably implemented without identity preservation (https://github.com/golang/go/issues/16876)
// Even then it's awkward to unpack the subtleties of a Go context out to Java.
//func (opts *TransactOpts) GetContext() *Context { return &Context{opts.opts.Context} }
func (opts *TransactOpts) SetFrom(from *Address) { opts.opts.From = from.address }
func (opts *TransactOpts) SetNonce(nonce int64) { opts.opts.Nonce = big.NewInt(nonce) }
func (opts *TransactOpts) SetSigner(s Signer) {
opts.opts.Signer = func(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
sig, err := s.Sign(&Address{addr}, &Transaction{tx})
if err != nil {
return nil, err
}
return sig.tx, nil
}
}
func (opts *TransactOpts) SetValue(value *BigInt) { opts.opts.Value = value.bigint }
func (opts *TransactOpts) SetGasPrice(price *BigInt) { opts.opts.GasPrice = price.bigint }
func (opts *TransactOpts) SetGasLimit(limit int64) { opts.opts.GasLimit = uint64(limit) }
func (opts *TransactOpts) SetContext(context *Context) { opts.opts.Context = context.context }
// BoundContract is the base wrapper object that reflects a contract on the
// Ethereum network. It contains a collection of methods that are used by the
// higher level contract bindings to operate.
type BoundContract struct {
contract *bind.BoundContract
address common.Address
deployer *types.Transaction
}
// DeployContract deploys a contract onto the Ethereum blockchain and binds the
// deployment address with a wrapper.
func DeployContract(opts *TransactOpts, abiJSON string, bytecode []byte, client *EthereumClient, args *Interfaces) (contract *BoundContract, _ error) {
// Deploy the contract to the network
parsed, err := abi.JSON(strings.NewReader(abiJSON))
if err != nil {
return nil, err
}
addr, tx, bound, err := bind.DeployContract(&opts.opts, parsed, common.CopyBytes(bytecode), client.client, args.objects...)
if err != nil {
return nil, err
}
return &BoundContract{
contract: bound,
address: addr,
deployer: tx,
}, nil
}
// BindContract creates a low level contract interface through which calls and
// transactions may be made through.
func BindContract(address *Address, abiJSON string, client *EthereumClient) (contract *BoundContract, _ error) {
parsed, err := abi.JSON(strings.NewReader(abiJSON))
if err != nil {
return nil, err
}
return &BoundContract{
contract: bind.NewBoundContract(address.address, parsed, client.client, client.client, client.client),
address: address.address,
}, nil
}
func (c *BoundContract) GetAddress() *Address { return &Address{c.address} }
func (c *BoundContract) GetDeployer() *Transaction {
if c.deployer == nil {
return nil
}
return &Transaction{c.deployer}
}
// Call invokes the (constant) contract method with params as input values and
// 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 {
return err
}
out.objects[0] = 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 {
return err
}
copy(out.objects, results)
}
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...)
if err != nil {
return nil, err
}
return &Transaction{rawTx}, nil
}
// 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) (tx *Transaction, _ error) {
rawTx, err := c.contract.Transfer(&opts.opts)
if err != nil {
return nil, err
}
return &Transaction{rawTx}, nil
}

View file

@ -1,230 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the common package.
package geth
import (
"encoding/hex"
"errors"
"fmt"
"strings"
"github.com/XinFinOrg/XDPoSChain/common"
)
// Hash represents the 32 byte Keccak256 hash of arbitrary data.
type Hash struct {
hash common.Hash
}
// NewHashFromBytes converts a slice of bytes to a hash value.
func NewHashFromBytes(binary []byte) (hash *Hash, _ error) {
h := new(Hash)
if err := h.SetBytes(common.CopyBytes(binary)); err != nil {
return nil, err
}
return h, nil
}
// NewHashFromHex converts a hex string to a hash value.
func NewHashFromHex(hex string) (hash *Hash, _ error) {
h := new(Hash)
if err := h.SetHex(hex); err != nil {
return nil, err
}
return h, nil
}
// SetBytes sets the specified slice of bytes as the hash value.
func (h *Hash) SetBytes(hash []byte) error {
if length := len(hash); length != common.HashLength {
return fmt.Errorf("invalid hash length: %v != %v", length, common.HashLength)
}
copy(h.hash[:], hash)
return nil
}
// GetBytes retrieves the byte representation of the hash.
func (h *Hash) GetBytes() []byte {
return h.hash[:]
}
// SetHex sets the specified hex string as the hash value.
func (h *Hash) SetHex(hash string) error {
hash = strings.ToLower(hash)
if len(hash) >= 2 && hash[:2] == "0x" {
hash = hash[2:]
}
if length := len(hash); length != 2*common.HashLength {
return fmt.Errorf("invalid hash hex length: %v != %v", length, 2*common.HashLength)
}
bin, err := hex.DecodeString(hash)
if err != nil {
return err
}
copy(h.hash[:], bin)
return nil
}
// GetHex retrieves the hex string representation of the hash.
func (h *Hash) GetHex() string {
return h.hash.Hex()
}
// Hashes represents a slice of hashes.
type Hashes struct{ hashes []common.Hash }
// NewHashes creates a slice of uninitialized Hashes.
func NewHashes(size int) *Hashes {
return &Hashes{
hashes: make([]common.Hash, size),
}
}
// NewHashesEmpty creates an empty slice of Hashes values.
func NewHashesEmpty() *Hashes {
return NewHashes(0)
}
// Size returns the number of hashes in the slice.
func (h *Hashes) Size() int {
return len(h.hashes)
}
// Get returns the hash at the given index from the slice.
func (h *Hashes) Get(index int) (hash *Hash, _ error) {
if index < 0 || index >= len(h.hashes) {
return nil, errors.New("index out of bounds")
}
return &Hash{h.hashes[index]}, nil
}
// Set sets the Hash at the given index in the slice.
func (h *Hashes) Set(index int, hash *Hash) error {
if index < 0 || index >= len(h.hashes) {
return errors.New("index out of bounds")
}
h.hashes[index] = hash.hash
return nil
}
// Append adds a new Hash element to the end of the slice.
func (h *Hashes) Append(hash *Hash) {
h.hashes = append(h.hashes, hash.hash)
}
// Address represents the 20 byte address of an Ethereum account.
type Address struct {
address common.Address
}
// NewAddressFromBytes converts a slice of bytes to a hash value.
func NewAddressFromBytes(binary []byte) (address *Address, _ error) {
a := new(Address)
if err := a.SetBytes(common.CopyBytes(binary)); err != nil {
return nil, err
}
return a, nil
}
// NewAddressFromHex converts a hex string to a address value.
func NewAddressFromHex(hex string) (address *Address, _ error) {
a := new(Address)
if err := a.SetHex(hex); err != nil {
return nil, err
}
return a, nil
}
// SetBytes sets the specified slice of bytes as the address value.
func (a *Address) SetBytes(address []byte) error {
if length := len(address); length != common.AddressLength {
return fmt.Errorf("invalid address length: %v != %v", length, common.AddressLength)
}
copy(a.address[:], address)
return nil
}
// GetBytes retrieves the byte representation of the address.
func (a *Address) GetBytes() []byte {
return a.address[:]
}
// SetHex sets the specified hex string as the address value.
func (a *Address) SetHex(address string) error {
address = strings.ToLower(address)
if len(address) >= 2 && address[:2] == "0x" {
address = address[2:]
}
if length := len(address); length != 2*common.AddressLength {
return fmt.Errorf("invalid address hex length: %v != %v", length, 2*common.AddressLength)
}
bin, err := hex.DecodeString(address)
if err != nil {
return err
}
copy(a.address[:], bin)
return nil
}
// GetHex retrieves the hex string representation of the address.
func (a *Address) GetHex() string {
return a.address.Hex()
}
// Addresses represents a slice of addresses.
type Addresses struct{ addresses []common.Address }
// NewAddresses creates a slice of uninitialized addresses.
func NewAddresses(size int) *Addresses {
return &Addresses{
addresses: make([]common.Address, size),
}
}
// NewAddressesEmpty creates an empty slice of Addresses values.
func NewAddressesEmpty() *Addresses {
return NewAddresses(0)
}
// Size returns the number of addresses in the slice.
func (a *Addresses) Size() int {
return len(a.addresses)
}
// Get returns the address at the given index from the slice.
func (a *Addresses) Get(index int) (address *Address, _ error) {
if index < 0 || index >= len(a.addresses) {
return nil, errors.New("index out of bounds")
}
return &Address{a.addresses[index]}, nil
}
// Set sets the address at the given index in the slice.
func (a *Addresses) Set(index int, address *Address) error {
if index < 0 || index >= len(a.addresses) {
return errors.New("index out of bounds")
}
a.addresses[index] = address.address
return nil
}
// Append adds a new address element to the end of the slice.
func (a *Addresses) Append(address *Address) {
a.addresses = append(a.addresses, address.address)
}

View file

@ -1,80 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the golang.org/x/net/context package to support
// client side context management on mobile platforms.
package geth
import (
"context"
"time"
)
// Context carries a deadline, a cancelation signal, and other values across API
// boundaries.
type Context struct {
context context.Context
cancel context.CancelFunc
}
// NewContext returns a non-nil, empty Context. It is never canceled, has no
// values, and has no deadline. It is typically used by the main function,
// initialization, and tests, and as the top-level Context for incoming requests.
func NewContext() *Context {
return &Context{
context: context.Background(),
}
}
// WithCancel returns a copy of the original context with cancellation mechanism
// included.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
func (c *Context) WithCancel() *Context {
child, cancel := context.WithCancel(c.context)
return &Context{
context: child,
cancel: cancel,
}
}
// WithDeadline returns a copy of the original context with the deadline adjusted
// to be no later than the specified time.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
func (c *Context) WithDeadline(sec int64, nsec int64) *Context {
child, cancel := context.WithDeadline(c.context, time.Unix(sec, nsec))
return &Context{
context: child,
cancel: cancel,
}
}
// WithTimeout returns a copy of the original context with the deadline adjusted
// to be no later than now + the duration specified.
//
// Canceling this context releases resources associated with it, so code should
// call cancel as soon as the operations running in this Context complete.
func (c *Context) WithTimeout(nsec int64) *Context {
child, cancel := context.WithTimeout(c.context, time.Duration(nsec))
return &Context{
context: child,
cancel: cancel,
}
}

View file

@ -1,104 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the accounts package to support client side enode
// management on mobile platforms.
package geth
import (
"errors"
"github.com/XinFinOrg/XDPoSChain/p2p/discv5"
)
// Enode represents a host on the network.
type Enode struct {
node *discv5.Node
}
// NewEnode parses a node designator.
//
// There are two basic forms of node designators
// - incomplete nodes, which only have the public key (node ID)
// - complete nodes, which contain the public key and IP/Port information
//
// For incomplete nodes, the designator must look like one of these
//
// enode://<hex node id>
// <hex node id>
//
// For complete nodes, the node ID is encoded in the username portion
// of the URL, separated from the host by an @ sign. The hostname can
// only be given as an IP address, DNS domain names are not allowed.
// The port in the host name section is the TCP listening port. If the
// TCP and UDP (discovery) ports differ, the UDP port is specified as
// query parameter "discport".
//
// In the following example, the node URL describes
// a node with IP address 10.3.58.6, TCP listening port 30303
// and UDP discovery port 30301.
//
// enode://<hex node id>@10.3.58.6:30303?discport=30301
func NewEnode(rawurl string) (enode *Enode, _ error) {
node, err := discv5.ParseNode(rawurl)
if err != nil {
return nil, err
}
return &Enode{node}, nil
}
// Enodes represents a slice of accounts.
type Enodes struct{ nodes []*discv5.Node }
// NewEnodes creates a slice of uninitialized enodes.
func NewEnodes(size int) *Enodes {
return &Enodes{
nodes: make([]*discv5.Node, size),
}
}
// NewEnodesEmpty creates an empty slice of Enode values.
func NewEnodesEmpty() *Enodes {
return NewEnodes(0)
}
// Size returns the number of enodes in the slice.
func (e *Enodes) Size() int {
return len(e.nodes)
}
// Get returns the enode at the given index from the slice.
func (e *Enodes) Get(index int) (enode *Enode, _ error) {
if index < 0 || index >= len(e.nodes) {
return nil, errors.New("index out of bounds")
}
return &Enode{e.nodes[index]}, nil
}
// Set sets the enode at the given index in the slice.
func (e *Enodes) Set(index int, enode *Enode) error {
if index < 0 || index >= len(e.nodes) {
return errors.New("index out of bounds")
}
e.nodes[index] = enode.node
return nil
}
// Append adds a new enode element to the end of the slice.
func (e *Enodes) Append(enode *Enode) {
e.nodes = append(e.nodes, enode.node)
}

View file

@ -1,61 +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 <http://www.gnu.org/licenses/>.
// Package geth contains the simplified mobile APIs to go-ethereum.
//
// The scope of this package is *not* to allow writing a custom Ethereum client
// with pieces plucked from go-ethereum, rather to allow writing native dapps on
// mobile platforms. Keep this in mind when using or extending this package!
//
// API limitations
//
// Since gomobile cannot bridge arbitrary types between Go and Android/iOS, the
// exposed APIs need to be manually wrapped into simplified types, with custom
// constructors and getters/setters to ensure that they can be meaninfully used
// from Java/ObjC too.
//
// With this in mind, please try to limit the scope of this package and only add
// essentials without which mobile support cannot work, especially since manually
// syncing the code will be unwieldy otherwise. In the long term we might consider
// writing custom library generators, but those are out of scope now.
//
// Content wise each file in this package corresponds to an entire Go package
// from the go-ethereum repository. Please adhere to this scoping to prevent this
// package getting unmaintainable.
//
// Wrapping guidelines:
//
// Every type that is to be exposed should be wrapped into its own plain struct,
// which internally contains a single field: the original go-ethereum version.
// This is needed because gomobile cannot expose named types for now.
//
// Whenever a method argument or a return type is a custom struct, the pointer
// variant should always be used as value types crossing over between language
// boundaries might have strange behaviors.
//
// Slices of types should be converted into a single multiplicative type wrapping
// a go slice with the methods `Size`, `Get` and `Set`. Further slice operations
// should not be provided to limit the remote code complexity. Arrays should be
// avoided as much as possible since they complicate bounds checking.
//
// If a method has multiple return values (e.g. some return + an error), those
// are generated as output arguments in ObjC. To avoid weird generated names like
// ret_0 for them, please always assign names to output variables if tuples.
//
// Note, a panic *cannot* cross over language boundaries, instead will result in
// an undebuggable SEGFAULT in the process. For error handling only ever use error
// returns, which may be the only or the second return.
package geth

View file

@ -1,312 +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 <http://www.gnu.org/licenses/>.
// Contains a wrapper for the Ethereum client.
package geth
import (
"math/big"
"github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/XinFinOrg/XDPoSChain/ethclient"
)
// EthereumClient provides access to the Ethereum APIs.
type EthereumClient struct {
client *ethclient.Client
}
// NewEthereumClient connects a client to the given URL.
func NewEthereumClient(rawurl string) (client *EthereumClient, _ error) {
rawClient, err := ethclient.Dial(rawurl)
return &EthereumClient{rawClient}, err
}
// GetBlockByHash returns the given full block.
func (ec *EthereumClient) GetBlockByHash(ctx *Context, hash *Hash) (block *Block, _ error) {
rawBlock, err := ec.client.BlockByHash(ctx.context, hash.hash)
return &Block{rawBlock}, err
}
// GetBlockByNumber returns a block from the current canonical chain. If number is <0, the
// latest known block is returned.
func (ec *EthereumClient) GetBlockByNumber(ctx *Context, number int64) (block *Block, _ error) {
if number < 0 {
rawBlock, err := ec.client.BlockByNumber(ctx.context, nil)
return &Block{rawBlock}, err
}
rawBlock, err := ec.client.BlockByNumber(ctx.context, big.NewInt(number))
return &Block{rawBlock}, err
}
// GetHeaderByHash returns the block header with the given hash.
func (ec *EthereumClient) GetHeaderByHash(ctx *Context, hash *Hash) (header *Header, _ error) {
rawHeader, err := ec.client.HeaderByHash(ctx.context, hash.hash)
return &Header{rawHeader}, err
}
// GetHeaderByNumber returns a block header from the current canonical chain. If number is <0,
// the latest known header is returned.
func (ec *EthereumClient) GetHeaderByNumber(ctx *Context, number int64) (header *Header, _ error) {
if number < 0 {
rawHeader, err := ec.client.HeaderByNumber(ctx.context, nil)
return &Header{rawHeader}, err
}
rawHeader, err := ec.client.HeaderByNumber(ctx.context, big.NewInt(number))
return &Header{rawHeader}, err
}
// GetTransactionByHash returns the transaction with the given hash.
func (ec *EthereumClient) GetTransactionByHash(ctx *Context, hash *Hash) (tx *Transaction, _ error) {
// TODO(karalabe): handle isPending
rawTx, _, err := ec.client.TransactionByHash(ctx.context, hash.hash)
return &Transaction{rawTx}, err
}
// GetTransactionSender returns the sender address of a transaction. The transaction must
// be included in blockchain at the given block and index.
func (ec *EthereumClient) GetTransactionSender(ctx *Context, tx *Transaction, blockhash *Hash, index int) (sender *Address, _ error) {
addr, err := ec.client.TransactionSender(ctx.context, tx.tx, blockhash.hash, uint(index))
return &Address{addr}, err
}
// GetTransactionCount returns the total number of transactions in the given block.
func (ec *EthereumClient) GetTransactionCount(ctx *Context, hash *Hash) (count int, _ error) {
rawCount, err := ec.client.TransactionCount(ctx.context, hash.hash)
return int(rawCount), err
}
// GetTransactionInBlock returns a single transaction at index in the given block.
func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) {
rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index))
return &Transaction{rawTx}, err
}
// GetTransactionReceipt returns the receipt of a transaction by transaction hash.
// Note that the receipt is not available for pending transactions.
func (ec *EthereumClient) GetTransactionReceipt(ctx *Context, hash *Hash) (receipt *Receipt, _ error) {
rawReceipt, err := ec.client.TransactionReceipt(ctx.context, hash.hash)
return &Receipt{rawReceipt}, err
}
// SyncProgress retrieves the current progress of the sync algorithm. If there's
// no sync currently running, it returns nil.
func (ec *EthereumClient) SyncProgress(ctx *Context) (progress *SyncProgress, _ error) {
rawProgress, err := ec.client.SyncProgress(ctx.context)
if rawProgress == nil {
return nil, err
}
return &SyncProgress{*rawProgress}, err
}
// NewHeadHandler is a client-side subscription callback to invoke on events and
// subscription failure.
type NewHeadHandler interface {
OnNewHead(header *Header)
OnError(failure string)
}
// SubscribeNewHead subscribes to notifications about the current blockchain head
// on the given channel.
func (ec *EthereumClient) SubscribeNewHead(ctx *Context, handler NewHeadHandler, buffer int) (sub *Subscription, _ error) {
// Subscribe to the event internally
ch := make(chan *types.Header, buffer)
rawSub, err := ec.client.SubscribeNewHead(ctx.context, ch)
if err != nil {
return nil, err
}
// Start up a dispatcher to feed into the callback
go func() {
for {
select {
case header := <-ch:
handler.OnNewHead(&Header{header})
case err := <-rawSub.Err():
handler.OnError(err.Error())
return
}
}
}()
return &Subscription{rawSub}, nil
}
// State Access
// GetBalanceAt returns the wei balance of the given account.
// The block number can be <0, in which case the balance is taken from the latest known block.
func (ec *EthereumClient) GetBalanceAt(ctx *Context, account *Address, number int64) (balance *BigInt, _ error) {
if number < 0 {
rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, nil)
return &BigInt{rawBalance}, err
}
rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, big.NewInt(number))
return &BigInt{rawBalance}, err
}
// GetStorageAt returns the value of key in the contract storage of the given account.
// The block number can be <0, in which case the value is taken from the latest known block.
func (ec *EthereumClient) GetStorageAt(ctx *Context, account *Address, key *Hash, number int64) (storage []byte, _ error) {
if number < 0 {
return ec.client.StorageAt(ctx.context, account.address, key.hash, nil)
}
return ec.client.StorageAt(ctx.context, account.address, key.hash, big.NewInt(number))
}
// GetCodeAt returns the contract code of the given account.
// The block number can be <0, in which case the code is taken from the latest known block.
func (ec *EthereumClient) GetCodeAt(ctx *Context, account *Address, number int64) (code []byte, _ error) {
if number < 0 {
return ec.client.CodeAt(ctx.context, account.address, nil)
}
return ec.client.CodeAt(ctx.context, account.address, big.NewInt(number))
}
// GetNonceAt returns the account nonce of the given account.
// The block number can be <0, in which case the nonce is taken from the latest known block.
func (ec *EthereumClient) GetNonceAt(ctx *Context, account *Address, number int64) (nonce int64, _ error) {
if number < 0 {
rawNonce, err := ec.client.NonceAt(ctx.context, account.address, nil)
return int64(rawNonce), err
}
rawNonce, err := ec.client.NonceAt(ctx.context, account.address, big.NewInt(number))
return int64(rawNonce), err
}
// Filters
// FilterLogs executes a filter query.
func (ec *EthereumClient) FilterLogs(ctx *Context, query *FilterQuery) (logs *Logs, _ error) {
rawLogs, err := ec.client.FilterLogs(ctx.context, query.query)
if err != nil {
return nil, err
}
// Temp hack due to vm.Logs being []*vm.Log
res := make([]*types.Log, len(rawLogs))
for i := range rawLogs {
res[i] = &rawLogs[i]
}
return &Logs{res}, nil
}
// FilterLogsHandler is a client-side subscription callback to invoke on events and
// subscription failure.
type FilterLogsHandler interface {
OnFilterLogs(log *Log)
OnError(failure string)
}
// SubscribeFilterLogs subscribes to the results of a streaming filter query.
func (ec *EthereumClient) SubscribeFilterLogs(ctx *Context, query *FilterQuery, handler FilterLogsHandler, buffer int) (sub *Subscription, _ error) {
// Subscribe to the event internally
ch := make(chan types.Log, buffer)
rawSub, err := ec.client.SubscribeFilterLogs(ctx.context, query.query, ch)
if err != nil {
return nil, err
}
// Start up a dispatcher to feed into the callback
go func() {
for {
select {
case log := <-ch:
handler.OnFilterLogs(&Log{&log})
case err := <-rawSub.Err():
handler.OnError(err.Error())
return
}
}
}()
return &Subscription{rawSub}, nil
}
// Pending State
// GetPendingBalanceAt returns the wei balance of the given account in the pending state.
func (ec *EthereumClient) GetPendingBalanceAt(ctx *Context, account *Address) (balance *BigInt, _ error) {
rawBalance, err := ec.client.PendingBalanceAt(ctx.context, account.address)
return &BigInt{rawBalance}, err
}
// GetPendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
func (ec *EthereumClient) GetPendingStorageAt(ctx *Context, account *Address, key *Hash) (storage []byte, _ error) {
return ec.client.PendingStorageAt(ctx.context, account.address, key.hash)
}
// GetPendingCodeAt returns the contract code of the given account in the pending state.
func (ec *EthereumClient) GetPendingCodeAt(ctx *Context, account *Address) (code []byte, _ error) {
return ec.client.PendingCodeAt(ctx.context, account.address)
}
// GetPendingNonceAt returns the account nonce of the given account in the pending state.
// This is the nonce that should be used for the next transaction.
func (ec *EthereumClient) GetPendingNonceAt(ctx *Context, account *Address) (nonce int64, _ error) {
rawNonce, err := ec.client.PendingNonceAt(ctx.context, account.address)
return int64(rawNonce), err
}
// GetPendingTransactionCount returns the total number of transactions in the pending state.
func (ec *EthereumClient) GetPendingTransactionCount(ctx *Context) (count int, _ error) {
rawCount, err := ec.client.PendingTransactionCount(ctx.context)
return int(rawCount), err
}
// Contract Calling
// CallContract executes a message call transaction, which is directly executed in the VM
// of the node, but never mined into the blockchain.
//
// blockNumber selects the block height at which the call runs. It can be <0, in which
// case the code is taken from the latest known block. Note that state from very old
// blocks might not be available.
func (ec *EthereumClient) CallContract(ctx *Context, msg *CallMsg, number int64) (output []byte, _ error) {
if number < 0 {
return ec.client.CallContract(ctx.context, msg.msg, nil)
}
return ec.client.CallContract(ctx.context, msg.msg, big.NewInt(number))
}
// PendingCallContract executes a message call transaction using the EVM.
// The state seen by the contract call is the pending state.
func (ec *EthereumClient) PendingCallContract(ctx *Context, msg *CallMsg) (output []byte, _ error) {
return ec.client.PendingCallContract(ctx.context, msg.msg)
}
// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
// execution of a transaction.
func (ec *EthereumClient) SuggestGasPrice(ctx *Context) (price *BigInt, _ error) {
rawPrice, err := ec.client.SuggestGasPrice(ctx.context)
return &BigInt{rawPrice}, err
}
// EstimateGas tries to estimate the gas needed to execute a specific transaction based on
// the current pending state of the backend blockchain. There is no guarantee that this is
// the true gas limit requirement as other transactions may be added or removed by miners,
// but it should provide a basis for setting a reasonable default.
func (ec *EthereumClient) EstimateGas(ctx *Context, msg *CallMsg) (gas int64, _ error) {
rawGas, err := ec.client.EstimateGas(ctx.context, msg.msg)
return int64(rawGas), err
}
// 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 *EthereumClient) SendTransaction(ctx *Context, tx *Transaction) error {
return ec.client.SendTransaction(ctx.context, tx.tx)
}

View file

@ -1,148 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the go-ethereum root package.
package geth
import (
"errors"
ethereum "github.com/XinFinOrg/XDPoSChain"
"github.com/XinFinOrg/XDPoSChain/common"
)
// Subscription represents an event subscription where events are
// delivered on a data channel.
type Subscription struct {
sub ethereum.Subscription
}
// Unsubscribe cancels the sending of events to the data channel
// and closes the error channel.
func (s *Subscription) Unsubscribe() {
s.sub.Unsubscribe()
}
// CallMsg contains parameters for contract calls.
type CallMsg struct {
msg ethereum.CallMsg
}
// NewCallMsg creates an empty contract call parameter list.
func NewCallMsg() *CallMsg {
return new(CallMsg)
}
func (msg *CallMsg) GetFrom() *Address { return &Address{msg.msg.From} }
func (msg *CallMsg) GetGas() int64 { return int64(msg.msg.Gas) }
func (msg *CallMsg) GetGasPrice() *BigInt { return &BigInt{msg.msg.GasPrice} }
func (msg *CallMsg) GetValue() *BigInt { return &BigInt{msg.msg.Value} }
func (msg *CallMsg) GetData() []byte { return msg.msg.Data }
func (msg *CallMsg) GetTo() *Address {
if to := msg.msg.To; to != nil {
return &Address{*msg.msg.To}
}
return nil
}
func (msg *CallMsg) SetFrom(address *Address) { msg.msg.From = address.address }
func (msg *CallMsg) SetGas(gas int64) { msg.msg.Gas = uint64(gas) }
func (msg *CallMsg) SetGasPrice(price *BigInt) { msg.msg.GasPrice = price.bigint }
func (msg *CallMsg) SetValue(value *BigInt) { msg.msg.Value = value.bigint }
func (msg *CallMsg) SetData(data []byte) { msg.msg.Data = common.CopyBytes(data) }
func (msg *CallMsg) SetTo(address *Address) {
if address == nil {
msg.msg.To = nil
} else {
msg.msg.To = &address.address
}
}
// SyncProgress gives progress indications when the node is synchronising with
// the Ethereum network.
type SyncProgress struct {
progress ethereum.SyncProgress
}
func (p *SyncProgress) GetStartingBlock() int64 { return int64(p.progress.StartingBlock) }
func (p *SyncProgress) GetCurrentBlock() int64 { return int64(p.progress.CurrentBlock) }
func (p *SyncProgress) GetHighestBlock() int64 { return int64(p.progress.HighestBlock) }
func (p *SyncProgress) GetPulledStates() int64 { return int64(p.progress.PulledStates) }
func (p *SyncProgress) GetKnownStates() int64 { return int64(p.progress.KnownStates) }
// Topics is a set of topic lists to filter events with.
type Topics struct{ topics [][]common.Hash }
// NewTopics creates a slice of uninitialized Topics.
func NewTopics(size int) *Topics {
return &Topics{
topics: make([][]common.Hash, size),
}
}
// NewTopicsEmpty creates an empty slice of Topics values.
func NewTopicsEmpty() *Topics {
return NewTopics(0)
}
// Size returns the number of topic lists inside the set
func (t *Topics) Size() int {
return len(t.topics)
}
// Get returns the topic list at the given index from the slice.
func (t *Topics) Get(index int) (hashes *Hashes, _ error) {
if index < 0 || index >= len(t.topics) {
return nil, errors.New("index out of bounds")
}
return &Hashes{t.topics[index]}, nil
}
// Set sets the topic list at the given index in the slice.
func (t *Topics) Set(index int, topics *Hashes) error {
if index < 0 || index >= len(t.topics) {
return errors.New("index out of bounds")
}
t.topics[index] = topics.hashes
return nil
}
// Append adds a new topic list to the end of the slice.
func (t *Topics) Append(topics *Hashes) {
t.topics = append(t.topics, topics.hashes)
}
// FilterQuery contains options for contact log filtering.
type FilterQuery struct {
query ethereum.FilterQuery
}
// NewFilterQuery creates an empty filter query for contact log filtering.
func NewFilterQuery() *FilterQuery {
return new(FilterQuery)
}
func (fq *FilterQuery) GetFromBlock() *BigInt { return &BigInt{fq.query.FromBlock} }
func (fq *FilterQuery) GetToBlock() *BigInt { return &BigInt{fq.query.ToBlock} }
func (fq *FilterQuery) GetAddresses() *Addresses { return &Addresses{fq.query.Addresses} }
func (fq *FilterQuery) GetTopics() *Topics { return &Topics{fq.query.Topics} }
func (fq *FilterQuery) SetFromBlock(fromBlock *BigInt) { fq.query.FromBlock = fromBlock.bigint }
func (fq *FilterQuery) SetToBlock(toBlock *BigInt) { fq.query.ToBlock = toBlock.bigint }
func (fq *FilterQuery) SetAddresses(addresses *Addresses) { fq.query.Addresses = addresses.addresses }
func (fq *FilterQuery) SetTopics(topics *Topics) { fq.query.Topics = topics.topics }

View file

@ -1,196 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the node package to support client side node
// management on mobile platforms.
package geth
import (
"encoding/json"
"fmt"
"path/filepath"
"github.com/XinFinOrg/XDPoSChain/core"
"github.com/XinFinOrg/XDPoSChain/eth/downloader"
"github.com/XinFinOrg/XDPoSChain/eth/ethconfig"
"github.com/XinFinOrg/XDPoSChain/ethclient"
"github.com/XinFinOrg/XDPoSChain/ethstats"
"github.com/XinFinOrg/XDPoSChain/les"
"github.com/XinFinOrg/XDPoSChain/node"
"github.com/XinFinOrg/XDPoSChain/p2p"
"github.com/XinFinOrg/XDPoSChain/p2p/nat"
"github.com/XinFinOrg/XDPoSChain/params"
)
// NodeConfig represents the collection of configuration values to fine tune the Geth
// node embedded into a mobile process. The available values are a subset of the
// entire API provided by go-ethereum to reduce the maintenance surface and dev
// complexity.
type NodeConfig struct {
// Bootstrap nodes used to establish connectivity with the rest of the network.
BootstrapNodes *Enodes
// MaxPeers is the maximum number of peers that can be connected. If this is
// set to zero, then only the configured static and trusted peers can connect.
MaxPeers int
// EthereumEnabled specifies whether the node should run the Ethereum protocol.
EthereumEnabled bool
// EthereumNetworkID is the network identifier used by the Ethereum protocol to
// decide if remote peers should be accepted or not.
EthereumNetworkID int64 // uint64 in truth, but Java can't handle that...
// EthereumGenesis is the genesis JSON to use to seed the blockchain with. An
// empty genesis state is equivalent to using the mainnet's state.
EthereumGenesis string
// EthereumDatabaseCache is the system memory in MB to allocate for database caching.
// A minimum of 16MB is always reserved.
EthereumDatabaseCache int
// EthereumNetStats is a netstats connection string to use to report various
// chain, transaction and node stats to a monitoring server.
//
// It has the form "nodename:secret@host:port"
EthereumNetStats string
}
// defaultNodeConfig contains the default node configuration values to use if all
// or some fields are missing from the user's specified list.
var defaultNodeConfig = &NodeConfig{
BootstrapNodes: FoundationBootnodes(),
MaxPeers: 25,
EthereumEnabled: true,
EthereumNetworkID: 1,
EthereumDatabaseCache: 16,
}
// NewNodeConfig creates a new node option set, initialized to the default values.
func NewNodeConfig() *NodeConfig {
config := *defaultNodeConfig
return &config
}
// Node represents a Geth Ethereum node instance.
type Node struct {
node *node.Node
}
// NewNode creates and configures a new Geth node.
func NewNode(datadir string, config *NodeConfig) (stack *Node, _ error) {
// If no or partial configurations were specified, use defaults
if config == nil {
config = NewNodeConfig()
}
if config.MaxPeers == 0 {
config.MaxPeers = defaultNodeConfig.MaxPeers
}
if config.BootstrapNodes == nil || config.BootstrapNodes.Size() == 0 {
config.BootstrapNodes = defaultNodeConfig.BootstrapNodes
}
// Create the empty networking stack
nodeConf := &node.Config{
Name: clientIdentifier,
Version: params.Version,
DataDir: datadir,
KeyStoreDir: filepath.Join(datadir, "keystore"), // Mobile should never use internal keystores!
P2P: p2p.Config{
NoDiscovery: true,
DiscoveryV5: true,
BootstrapNodesV5: config.BootstrapNodes.nodes,
ListenAddr: ":0",
NAT: nat.Any(),
MaxPeers: config.MaxPeers,
},
}
rawStack, err := node.New(nodeConf)
if err != nil {
return nil, err
}
var genesis *core.Genesis
if config.EthereumGenesis != "" {
// Parse the user supplied genesis spec if not mainnet
genesis = new(core.Genesis)
if err := json.Unmarshal([]byte(config.EthereumGenesis), genesis); err != nil {
return nil, fmt.Errorf("invalid genesis spec: %v", err)
}
// If we have the testnet, hard code the chain configs too
if config.EthereumGenesis == TestnetGenesis() {
genesis.Config = params.TestnetChainConfig
if config.EthereumNetworkID == 1 {
config.EthereumNetworkID = 3
}
}
}
// Register the Ethereum protocol if requested
if config.EthereumEnabled {
ethConf := ethconfig.Defaults
ethConf.Genesis = genesis
ethConf.SyncMode = downloader.LightSync
ethConf.NetworkId = uint64(config.EthereumNetworkID)
ethConf.DatabaseCache = config.EthereumDatabaseCache
if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
return les.New(ctx, &ethConf)
}); err != nil {
return nil, fmt.Errorf("ethereum init: %v", err)
}
// If netstats reporting is requested, do it
if config.EthereumNetStats != "" {
if err := rawStack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
var lesServ *les.LightEthereum
ctx.Service(&lesServ)
return ethstats.New(config.EthereumNetStats, nil, lesServ)
}); err != nil {
return nil, fmt.Errorf("netstats init: %v", err)
}
}
}
return &Node{rawStack}, nil
}
// Start creates a live P2P node and starts running it.
func (n *Node) Start() error {
return n.node.Start()
}
// Stop terminates a running node along with all it's services. In the node was
// not started, an error is returned.
func (n *Node) Stop() error {
return n.node.Stop()
}
// GetEthereumClient retrieves a client to access the Ethereum subsystem.
func (n *Node) GetEthereumClient() (client *EthereumClient, _ error) {
rpc, err := n.node.Attach()
if err != nil {
return nil, err
}
return &EthereumClient{ethclient.NewClient(rpc)}, nil
}
// GetNodeInfo gathers and returns a collection of metadata known about the host.
func (n *Node) GetNodeInfo() *NodeInfo {
return &NodeInfo{n.node.Server().NodeInfo()}
}
// GetPeersInfo returns an array of metadata objects describing connected peers.
func (n *Node) GetPeersInfo() *PeerInfos {
return &PeerInfos{n.node.Server().PeersInfo()}
}

View file

@ -1,22 +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 <http://www.gnu.org/licenses/>.
// +build android
package geth
// clientIdentifier is a hard coded identifier to report into the network.
var clientIdentifier = "GethDroid"

View file

@ -1,22 +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 <http://www.gnu.org/licenses/>.
// +build ios
package geth
// clientIdentifier is a hard coded identifier to report into the network.
var clientIdentifier = "iGeth"

View file

@ -1,22 +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 <http://www.gnu.org/licenses/>.
// +build !android,!ios
package geth
// clientIdentifier is a hard coded identifier to report into the network.
var clientIdentifier = "GethMobile"

View file

@ -1,34 +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 <http://www.gnu.org/licenses/>.
// Contains initialization code for the mbile library.
package geth
import (
"os"
"runtime"
"github.com/XinFinOrg/XDPoSChain/log"
)
func init() {
// Initialize the logger
log.SetDefault(log.NewLogger(log.NewTerminalHandlerWithLevel(os.Stderr, log.LevelInfo, false)))
// Initialize the goroutine count
runtime.GOMAXPROCS(runtime.NumCPU())
}

View file

@ -1,148 +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 <http://www.gnu.org/licenses/>.
// Contains perverted wrappers to allow crossing over empty interfaces.
package geth
import (
"errors"
"math/big"
"github.com/XinFinOrg/XDPoSChain/common"
)
// Interface represents a wrapped version of Go's interface{}, with the capacity
// to store arbitrary data types.
//
// Since it's impossible to get the arbitrary-ness converted between Go and mobile
// platforms, we're using explicit getters and setters for the conversions. There
// is of course no point in enumerating everything, just enough to support the
// contract bindins requiring client side generated code.
type Interface struct {
object interface{}
}
// NewInterface creates a new empty interface that can be used to pass around
// generic types.
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) SetDefaultBool() { i.object = new(bool) }
func (i *Interface) SetDefaultBools() { i.object = new([]bool) }
func (i *Interface) SetDefaultString() { i.object = new(string) }
func (i *Interface) SetDefaultStrings() { i.object = new([]string) }
func (i *Interface) SetDefaultBinary() { i.object = new([]byte) }
func (i *Interface) SetDefaultBinaries() { i.object = new([][]byte) }
func (i *Interface) SetDefaultAddress() { i.object = new(common.Address) }
func (i *Interface) SetDefaultAddresses() { i.object = new([]common.Address) }
func (i *Interface) SetDefaultHash() { i.object = new(common.Hash) }
func (i *Interface) SetDefaultHashes() { i.object = new([]common.Hash) }
func (i *Interface) SetDefaultInt8() { i.object = new(int8) }
func (i *Interface) SetDefaultInt16() { i.object = new(int16) }
func (i *Interface) SetDefaultInt32() { i.object = new(int32) }
func (i *Interface) SetDefaultInt64() { i.object = new(int64) }
func (i *Interface) SetDefaultUint8() { i.object = new(uint8) }
func (i *Interface) SetDefaultUint16() { i.object = new(uint16) }
func (i *Interface) SetDefaultUint32() { i.object = new(uint32) }
func (i *Interface) SetDefaultUint64() { i.object = new(uint64) }
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) 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) 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)} }
func (i *Interface) GetHashes() *Hashes { return &Hashes{*i.object.(*[]common.Hash)} }
func (i *Interface) GetInt8() int8 { return *i.object.(*int8) }
func (i *Interface) GetInt16() int16 { return *i.object.(*int16) }
func (i *Interface) GetInt32() int32 { return *i.object.(*int32) }
func (i *Interface) GetInt64() int64 { return *i.object.(*int64) }
func (i *Interface) GetUint8() *BigInt {
return &BigInt{new(big.Int).SetUint64(uint64(*i.object.(*uint8)))}
}
func (i *Interface) GetUint16() *BigInt {
return &BigInt{new(big.Int).SetUint64(uint64(*i.object.(*uint16)))}
}
func (i *Interface) GetUint32() *BigInt {
return &BigInt{new(big.Int).SetUint64(uint64(*i.object.(*uint32)))}
}
func (i *Interface) GetUint64() *BigInt {
return &BigInt{new(big.Int).SetUint64(*i.object.(*uint64))}
}
func (i *Interface) GetBigInt() *BigInt { return &BigInt{*i.object.(**big.Int)} }
func (i *Interface) GetBigInts() *BigInts { return &BigInts{*i.object.(*[]*big.Int)} }
// Interfaces is a slices of wrapped generic objects.
type Interfaces struct {
objects []interface{}
}
// NewInterfaces creates a slice of uninitialized interfaces.
func NewInterfaces(size int) *Interfaces {
return &Interfaces{
objects: make([]interface{}, size),
}
}
// Size returns the number of interfaces in the slice.
func (i *Interfaces) Size() int {
return len(i.objects)
}
// Get returns the bigint at the given index from the slice.
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
}
// Set sets the big int at the given index in the slice.
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
return nil
}

View file

@ -1,28 +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 <http://www.gnu.org/licenses/>.
package geth
import (
"os"
"github.com/XinFinOrg/XDPoSChain/log"
)
// SetVerbosity sets the global verbosity level (between 0 and 6 - see logger/verbosity.go).
func SetVerbosity(level int) {
log.SetDefault(log.NewLogger(log.NewTerminalHandlerWithLevel(os.Stderr, log.FromLegacyLevel(level), false)))
}

View file

@ -1,74 +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 <http://www.gnu.org/licenses/>.
// Contains wrappers for the p2p package.
package geth
import (
"errors"
"github.com/XinFinOrg/XDPoSChain/p2p"
)
// NodeInfo represents pi short summary of the information known about the host.
type NodeInfo struct {
info *p2p.NodeInfo
}
func (ni *NodeInfo) GetID() string { return ni.info.ID }
func (ni *NodeInfo) GetName() string { return ni.info.Name }
func (ni *NodeInfo) GetEnode() string { return ni.info.Enode }
func (ni *NodeInfo) GetIP() string { return ni.info.IP }
func (ni *NodeInfo) GetDiscoveryPort() int { return ni.info.Ports.Discovery }
func (ni *NodeInfo) GetListenerPort() int { return ni.info.Ports.Listener }
func (ni *NodeInfo) GetListenerAddress() string { return ni.info.ListenAddr }
func (ni *NodeInfo) GetProtocols() *Strings {
protos := []string{}
for proto := range ni.info.Protocols {
protos = append(protos, proto)
}
return &Strings{protos}
}
// PeerInfo represents pi short summary of the information known about pi connected peer.
type PeerInfo struct {
info *p2p.PeerInfo
}
func (pi *PeerInfo) GetID() string { return pi.info.ID }
func (pi *PeerInfo) GetName() string { return pi.info.Name }
func (pi *PeerInfo) GetCaps() *Strings { return &Strings{pi.info.Caps} }
func (pi *PeerInfo) GetLocalAddress() string { return pi.info.Network.LocalAddress }
func (pi *PeerInfo) GetRemoteAddress() string { return pi.info.Network.RemoteAddress }
// PeerInfos represents a slice of infos about remote peers.
type PeerInfos struct {
infos []*p2p.PeerInfo
}
// Size returns the number of peer info entries in the slice.
func (pi *PeerInfos) Size() int {
return len(pi.infos)
}
// Get returns the peer info at the given index from the slice.
func (pi *PeerInfos) Get(index int) (info *PeerInfo, _ error) {
if index < 0 || index >= len(pi.infos) {
return nil, errors.New("index out of bounds")
}
return &PeerInfo{pi.infos[index]}, nil
}

View file

@ -1,61 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the params package.
package geth
import (
"encoding/json"
"github.com/XinFinOrg/XDPoSChain/core"
"github.com/XinFinOrg/XDPoSChain/p2p/discv5"
"github.com/XinFinOrg/XDPoSChain/params"
)
// MainnetGenesis returns the JSON spec to use for the main Ethereum network. It
// is actually empty since that defaults to the hard coded binary genesis block.
func MainnetGenesis() string {
return ""
}
// TestnetGenesis returns the JSON spec to use for the Ethereum test network.
func TestnetGenesis() string {
enc, err := json.Marshal(core.DefaultTestnetGenesisBlock())
if err != nil {
panic(err)
}
return string(enc)
}
// RinkebyGenesis returns the JSON spec to use for the Rinkeby test network
func RinkebyGenesis() string {
enc, err := json.Marshal(core.DefaultRinkebyGenesisBlock())
if err != nil {
panic(err)
}
return string(enc)
}
// FoundationBootnodes returns the enode URLs of the P2P bootstrap nodes operated
// by the foundation running the V5 discovery protocol.
func FoundationBootnodes() *Enodes {
nodes := &Enodes{nodes: make([]*discv5.Node, len(params.DiscoveryV5Bootnodes))}
for i, url := range params.DiscoveryV5Bootnodes {
nodes.nodes[i] = discv5.MustParseNode(url)
}
return nodes
}

View file

@ -1,54 +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 <http://www.gnu.org/licenses/>.
// Contains various wrappers for primitive types.
package geth
import (
"errors"
"fmt"
)
// Strings represents s slice of strs.
type Strings struct{ strs []string }
// Size returns the number of strs in the slice.
func (s *Strings) Size() int {
return len(s.strs)
}
// Get returns the string at the given index from the slice.
func (s *Strings) Get(index int) (str string, _ error) {
if index < 0 || index >= len(s.strs) {
return "", errors.New("index out of bounds")
}
return s.strs[index], nil
}
// Set sets the string at the given index in the slice.
func (s *Strings) Set(index int, str string) error {
if index < 0 || index >= len(s.strs) {
return errors.New("index out of bounds")
}
s.strs[index] = str
return nil
}
// String implements the Stringer interface.
func (s *Strings) String() string {
return fmt.Sprintf("%v", s.strs)
}

View file

@ -1,362 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the core/types package.
package geth
import (
"encoding/json"
"errors"
"fmt"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/XinFinOrg/XDPoSChain/rlp"
)
// A Nonce is a 64-bit hash which proves (combined with the mix-hash) that
// a sufficient amount of computation has been carried out on a block.
type Nonce struct {
nonce types.BlockNonce
}
// GetBytes retrieves the byte representation of the block nonce.
func (n *Nonce) GetBytes() []byte {
return n.nonce[:]
}
// GetHex retrieves the hex string representation of the block nonce.
func (n *Nonce) GetHex() string {
return fmt.Sprintf("%#x", n.nonce[:])
}
// Bloom represents a 256 bit bloom filter.
type Bloom struct {
bloom types.Bloom
}
// GetBytes retrieves the byte representation of the bloom filter.
func (b *Bloom) GetBytes() []byte {
return b.bloom[:]
}
// GetHex retrieves the hex string representation of the bloom filter.
func (b *Bloom) GetHex() string {
return fmt.Sprintf("%#x", b.bloom[:])
}
// Header represents a block header in the Ethereum blockchain.
type Header struct {
header *types.Header
}
// NewHeaderFromRLP parses a header from an RLP data dump.
func NewHeaderFromRLP(data []byte) (*Header, error) {
h := &Header{
header: new(types.Header),
}
if err := rlp.DecodeBytes(common.CopyBytes(data), h.header); err != nil {
return nil, err
}
return h, nil
}
// EncodeRLP encodes a header into an RLP data dump.
func (h *Header) EncodeRLP() ([]byte, error) {
return rlp.EncodeToBytes(h.header)
}
// NewHeaderFromJSON parses a header from an JSON data dump.
func NewHeaderFromJSON(data string) (*Header, error) {
h := &Header{
header: new(types.Header),
}
if err := json.Unmarshal([]byte(data), h.header); err != nil {
return nil, err
}
return h, nil
}
// EncodeJSON encodes a header into an JSON data dump.
func (h *Header) EncodeJSON() (string, error) {
data, err := json.Marshal(h.header)
return string(data), err
}
// String implements the fmt.Stringer interface to print some semi-meaningful
// data dump of the header for debugging purposes.
func (h *Header) String() string {
return h.header.String()
}
func (h *Header) GetParentHash() *Hash { return &Hash{h.header.ParentHash} }
func (h *Header) GetUncleHash() *Hash { return &Hash{h.header.UncleHash} }
func (h *Header) GetCoinbase() *Address { return &Address{h.header.Coinbase} }
func (h *Header) GetRoot() *Hash { return &Hash{h.header.Root} }
func (h *Header) GetTxHash() *Hash { return &Hash{h.header.TxHash} }
func (h *Header) GetReceiptHash() *Hash { return &Hash{h.header.ReceiptHash} }
func (h *Header) GetBloom() *Bloom { return &Bloom{h.header.Bloom} }
func (h *Header) GetDifficulty() *BigInt { return &BigInt{h.header.Difficulty} }
func (h *Header) GetNumber() int64 { return h.header.Number.Int64() }
func (h *Header) GetGasLimit() int64 { return int64(h.header.GasLimit) }
func (h *Header) GetGasUsed() int64 { return int64(h.header.GasUsed) }
func (h *Header) GetTime() int64 { return h.header.Time.Int64() }
func (h *Header) GetExtra() []byte { return h.header.Extra }
func (h *Header) GetMixDigest() *Hash { return &Hash{h.header.MixDigest} }
func (h *Header) GetNonce() *Nonce { return &Nonce{h.header.Nonce} }
func (h *Header) GetHash() *Hash { return &Hash{h.header.Hash()} }
// Headers represents a slice of headers.
type Headers struct{ headers []*types.Header }
// Size returns the number of headers in the slice.
func (h *Headers) Size() int {
return len(h.headers)
}
// Get returns the header at the given index from the slice.
func (h *Headers) Get(index int) (header *Header, _ error) {
if index < 0 || index >= len(h.headers) {
return nil, errors.New("index out of bounds")
}
return &Header{h.headers[index]}, nil
}
// Block represents an entire block in the Ethereum blockchain.
type Block struct {
block *types.Block
}
// NewBlockFromRLP parses a block from an RLP data dump.
func NewBlockFromRLP(data []byte) (*Block, error) {
b := &Block{
block: new(types.Block),
}
if err := rlp.DecodeBytes(common.CopyBytes(data), b.block); err != nil {
return nil, err
}
return b, nil
}
// EncodeRLP encodes a block into an RLP data dump.
func (b *Block) EncodeRLP() ([]byte, error) {
return rlp.EncodeToBytes(b.block)
}
// NewBlockFromJSON parses a block from an JSON data dump.
func NewBlockFromJSON(data string) (*Block, error) {
b := &Block{
block: new(types.Block),
}
if err := json.Unmarshal([]byte(data), b.block); err != nil {
return nil, err
}
return b, nil
}
// EncodeJSON encodes a block into an JSON data dump.
func (b *Block) EncodeJSON() (string, error) {
data, err := json.Marshal(b.block)
return string(data), err
}
// String implements the fmt.Stringer interface to print some semi-meaningful
// data dump of the block for debugging purposes.
func (b *Block) String() string {
return b.block.String()
}
func (b *Block) GetParentHash() *Hash { return &Hash{b.block.ParentHash()} }
func (b *Block) GetUncleHash() *Hash { return &Hash{b.block.UncleHash()} }
func (b *Block) GetCoinbase() *Address { return &Address{b.block.Coinbase()} }
func (b *Block) GetRoot() *Hash { return &Hash{b.block.Root()} }
func (b *Block) GetTxHash() *Hash { return &Hash{b.block.TxHash()} }
func (b *Block) GetReceiptHash() *Hash { return &Hash{b.block.ReceiptHash()} }
func (b *Block) GetBloom() *Bloom { return &Bloom{b.block.Bloom()} }
func (b *Block) GetDifficulty() *BigInt { return &BigInt{b.block.Difficulty()} }
func (b *Block) GetNumber() int64 { return b.block.Number().Int64() }
func (b *Block) GetGasLimit() int64 { return int64(b.block.GasLimit()) }
func (b *Block) GetGasUsed() int64 { return int64(b.block.GasUsed()) }
func (b *Block) GetTime() int64 { return b.block.Time().Int64() }
func (b *Block) GetExtra() []byte { return b.block.Extra() }
func (b *Block) GetMixDigest() *Hash { return &Hash{b.block.MixDigest()} }
func (b *Block) GetNonce() int64 { return int64(b.block.Nonce()) }
func (b *Block) GetHash() *Hash { return &Hash{b.block.Hash()} }
func (b *Block) GetHashNoNonce() *Hash { return &Hash{b.block.HashNoNonce()} }
func (b *Block) GetHeader() *Header { return &Header{b.block.Header()} }
func (b *Block) GetUncles() *Headers { return &Headers{b.block.Uncles()} }
func (b *Block) GetTransactions() *Transactions { return &Transactions{b.block.Transactions()} }
func (b *Block) GetTransaction(hash *Hash) *Transaction {
return &Transaction{b.block.Transaction(hash.hash)}
}
// Transaction represents a single Ethereum transaction.
type Transaction struct {
tx *types.Transaction
}
// NewTransaction creates a new transaction with the given properties.
func NewTransaction(nonce int64, to *Address, amount *BigInt, gasLimit int64, gasPrice *BigInt, data []byte) *Transaction {
return &Transaction{types.NewTransaction(uint64(nonce), to.address, amount.bigint, uint64(gasLimit), gasPrice.bigint, common.CopyBytes(data))}
}
// NewTransactionFromRLP parses a transaction from an RLP data dump.
func NewTransactionFromRLP(data []byte) (*Transaction, error) {
tx := &Transaction{
tx: new(types.Transaction),
}
if err := rlp.DecodeBytes(common.CopyBytes(data), tx.tx); err != nil {
return nil, err
}
return tx, nil
}
// EncodeRLP encodes a transaction into an RLP data dump.
func (tx *Transaction) EncodeRLP() ([]byte, error) {
return rlp.EncodeToBytes(tx.tx)
}
// NewTransactionFromJSON parses a transaction from an JSON data dump.
func NewTransactionFromJSON(data string) (*Transaction, error) {
tx := &Transaction{
tx: new(types.Transaction),
}
if err := json.Unmarshal([]byte(data), tx.tx); err != nil {
return nil, err
}
return tx, nil
}
// EncodeJSON encodes a transaction into an JSON data dump.
func (tx *Transaction) EncodeJSON() (string, error) {
data, err := json.Marshal(tx.tx)
return string(data), err
}
// String implements the fmt.Stringer interface to print some semi-meaningful
// data dump of the transaction for debugging purposes.
func (tx *Transaction) String() string {
return tx.tx.String()
}
func (tx *Transaction) GetData() []byte { return tx.tx.Data() }
func (tx *Transaction) GetGas() int64 { return int64(tx.tx.Gas()) }
func (tx *Transaction) GetGasPrice() *BigInt { return &BigInt{tx.tx.GasPrice()} }
func (tx *Transaction) GetValue() *BigInt { return &BigInt{tx.tx.Value()} }
func (tx *Transaction) GetNonce() int64 { return int64(tx.tx.Nonce()) }
func (tx *Transaction) GetHash() *Hash { return &Hash{tx.tx.Hash()} }
func (tx *Transaction) GetCost() *BigInt { return &BigInt{tx.tx.Cost()} }
// Deprecated: GetSigHash cannot know which signer to use.
func (tx *Transaction) GetSigHash() *Hash { return &Hash{types.HomesteadSigner{}.Hash(tx.tx)} }
// Deprecated: use EthereumClient.TransactionSender
func (tx *Transaction) GetFrom(chainID *BigInt) (address *Address, _ error) {
var signer types.Signer = types.HomesteadSigner{}
if chainID != nil {
signer = types.NewEIP155Signer(chainID.bigint)
}
from, err := types.Sender(signer, tx.tx)
return &Address{from}, err
}
func (tx *Transaction) GetTo() *Address {
if to := tx.tx.To(); to != nil {
return &Address{*to}
}
return nil
}
func (tx *Transaction) WithSignature(sig []byte, chainID *BigInt) (signedTx *Transaction, _ error) {
var signer types.Signer = types.HomesteadSigner{}
if chainID != nil {
signer = types.NewEIP155Signer(chainID.bigint)
}
rawTx, err := tx.tx.WithSignature(signer, common.CopyBytes(sig))
return &Transaction{rawTx}, err
}
// Transactions represents a slice of transactions.
type Transactions struct{ txs types.Transactions }
// Size returns the number of transactions in the slice.
func (txs *Transactions) Size() int {
return len(txs.txs)
}
// Get returns the transaction at the given index from the slice.
func (txs *Transactions) Get(index int) (tx *Transaction, _ error) {
if index < 0 || index >= len(txs.txs) {
return nil, errors.New("index out of bounds")
}
return &Transaction{txs.txs[index]}, nil
}
// Receipt represents the results of a transaction.
type Receipt struct {
receipt *types.Receipt
}
// NewReceiptFromRLP parses a transaction receipt from an RLP data dump.
func NewReceiptFromRLP(data []byte) (*Receipt, error) {
r := &Receipt{
receipt: new(types.Receipt),
}
if err := rlp.DecodeBytes(common.CopyBytes(data), r.receipt); err != nil {
return nil, err
}
return r, nil
}
// EncodeRLP encodes a transaction receipt into an RLP data dump.
func (r *Receipt) EncodeRLP() ([]byte, error) {
return rlp.EncodeToBytes(r.receipt)
}
// NewReceiptFromJSON parses a transaction receipt from an JSON data dump.
func NewReceiptFromJSON(data string) (*Receipt, error) {
r := &Receipt{
receipt: new(types.Receipt),
}
if err := json.Unmarshal([]byte(data), r.receipt); err != nil {
return nil, err
}
return r, nil
}
// EncodeJSON encodes a transaction receipt into an JSON data dump.
func (r *Receipt) EncodeJSON() (string, error) {
data, err := rlp.EncodeToBytes(r.receipt)
return string(data), err
}
// String implements the fmt.Stringer interface to print some semi-meaningful
// data dump of the transaction receipt for debugging purposes.
func (r *Receipt) String() string {
return r.receipt.String()
}
func (r *Receipt) GetPostState() []byte { return r.receipt.PostState }
func (r *Receipt) GetCumulativeGasUsed() int64 { return int64(r.receipt.CumulativeGasUsed) }
func (r *Receipt) GetBloom() *Bloom { return &Bloom{r.receipt.Bloom} }
func (r *Receipt) GetLogs() *Logs { return &Logs{r.receipt.Logs} }
func (r *Receipt) GetTxHash() *Hash { return &Hash{r.receipt.TxHash} }
func (r *Receipt) GetContractAddress() *Address { return &Address{r.receipt.ContractAddress} }
func (r *Receipt) GetGasUsed() int64 { return int64(r.receipt.GasUsed) }

View file

@ -1,56 +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 <http://www.gnu.org/licenses/>.
// Contains all the wrappers from the core/types package.
package geth
import (
"errors"
"github.com/XinFinOrg/XDPoSChain/core/types"
)
// Log represents a contract log event. These events are generated by the LOG
// opcode and stored/indexed by the node.
type Log struct {
log *types.Log
}
func (l *Log) GetAddress() *Address { return &Address{l.log.Address} }
func (l *Log) GetTopics() *Hashes { return &Hashes{l.log.Topics} }
func (l *Log) GetData() []byte { return l.log.Data }
func (l *Log) GetBlockNumber() int64 { return int64(l.log.BlockNumber) }
func (l *Log) GetTxHash() *Hash { return &Hash{l.log.TxHash} }
func (l *Log) GetTxIndex() int { return int(l.log.TxIndex) }
func (l *Log) GetBlockHash() *Hash { return &Hash{l.log.BlockHash} }
func (l *Log) GetIndex() int { return int(l.log.Index) }
// Logs represents a slice of VM logs.
type Logs struct{ logs []*types.Log }
// Size returns the number of logs in the slice.
func (l *Logs) Size() int {
return len(l.logs)
}
// Get returns the log at the given index from the slice.
func (l *Logs) Get(index int) (log *Log, _ error) {
if index < 0 || index >= len(l.logs) {
return nil, errors.New("index out of bounds")
}
return &Log{l.logs[index]}, nil
}