From bee66da91aac516d6ba60cd78c1a7debaff72186 Mon Sep 17 00:00:00 2001 From: dC$rb <49501729+t4n6a1ka@users.noreply.github.com> Date: Tue, 2 Jul 2019 07:34:11 +0800 Subject: [PATCH] Master (#2) /*/ # * eth: fix sync bloom panic (#19757). # * eth: fix sync bloom panic. # * eth: delete useless test cases. * mobile: fix mobile interface (#19180) * mobile: fix mobile interface * mobile, accounts: generate correct java binding * accounts: fix java type binding * mobile: support integer slice * accounts/abi/bind, cmd/abigen: implement java binding tests * les: prefer nil slices over zero-length slices (#19081) * all: on-chain oracle checkpoint syncing (#19543) * all: implement simple checkpoint syncing cmd, les, node: remove callback mechanism cmd, node: remove callback definition les: simplify the registrar les: expose checkpoint rpc services in the light client les, light: don't store untrusted receipt cmd, contracts, les: discard stale checkpoint cmd, contracts/registrar: loose restriction of registeration cmd, contracts: add replay-protection all: off-chain multi-signature contract params: deploy checkpoint contract for rinkeby cmd/registrar: add raw signing mode for registrar cmd/registrar, contracts/registrar, les: fixed messages * cmd/registrar, contracts/registrar: fix lints * accounts/abi/bind, les: address comments * cmd, contracts, les, light, params: minor checkpoint sync cleanups * cmd, eth, les, light: move checkpoint config to config file * cmd, eth, les, params: address comments * eth, les, params: address comments * cmd: polish up the checkpoint admin CLI * cmd, contracts, params: deploy new version contract * cmd/checkpoint-admin: add another flag for clef mode signing * cmd, contracts, les: rename and regen checkpoint oracle with abigen * accounts/abi: Fix method overwritten by same name methods. (#17099) * accounts/abi: Fix method overwritten by same name methods. * accounts/abi: Fix method overwritten by same name methods. * accounts/abi: avoid possible name conflict Co-authored-by: Guillaume Ballet * Delete COPYING * Create LICENSE /*/ --- COPYING => LICENSE | 59 ++- accounts/abi/abi.go | 20 +- accounts/abi/abi_test.go | 45 +- accounts/abi/bind/backends/simulated.go | 24 +- accounts/abi/bind/base_test.go | 26 -- accounts/abi/bind/bind.go | 211 ++++----- accounts/abi/bind/bind_test.go | 402 ++++++++++++++++- accounts/abi/bind/template.go | 163 +++---- accounts/abi/bind/util_test.go | 3 +- cmd/abigen/main.go | 2 - cmd/checkpoint-admin/common.go | 166 +++++++ cmd/checkpoint-admin/exec.go | 335 ++++++++++++++ cmd/checkpoint-admin/main.go | 124 ++++++ cmd/checkpoint-admin/status.go | 61 +++ cmd/geth/main.go | 37 +- cmd/puppeth/wizard_genesis.go | 17 +- contracts/checkpointoracle/contract/oracle.go | 415 ++++++++++++++++++ .../checkpointoracle/contract/oracle.sol | 174 ++++++++ contracts/checkpointoracle/oracle.go | 91 ++++ contracts/checkpointoracle/oracle_test.go | 333 ++++++++++++++ core/chain_indexer.go | 7 +- eth/backend.go | 21 +- eth/config.go | 6 + eth/gen_config.go | 19 + eth/handler.go | 29 +- eth/handler_test.go | 20 +- eth/helper_test.go | 2 +- eth/sync.go | 8 - internal/web3ext/web3ext.go | 26 ++ les/api.go | 58 +++ les/backend.go | 66 +-- les/checkpointoracle.go | 158 +++++++ les/commons.go | 52 ++- les/handler.go | 34 +- les/handler_test.go | 57 +-- les/helper_test.go | 247 +++++++---- les/odr_requests.go | 61 +-- les/odr_test.go | 8 +- les/peer.go | 27 +- les/request_test.go | 2 +- les/server.go | 97 ++-- les/sync.go | 157 ++++++- les/sync_test.go | 133 ++++++ les/transactions.rlp | 0 les/txrelay.go | 20 +- les/ulc_test.go | 21 +- light/lightchain.go | 30 +- light/lightchain_test.go | 6 +- light/odr.go | 22 +- light/odr_test.go | 2 +- light/odr_util.go | 34 ++ light/txpool_test.go | 2 +- mobile/bind.go | 40 +- mobile/common.go | 11 + mobile/interface.go | 180 ++++++-- mobile/interface_test.go | 90 ++++ mobile/primitives.go | 62 +++ node/node.go | 1 - p2p/message.go | 2 +- params/config.go | 56 ++- params/network_params.go | 6 + 61 files changed, 3912 insertions(+), 676 deletions(-) rename COPYING => LICENSE (91%) create mode 100644 cmd/checkpoint-admin/common.go create mode 100644 cmd/checkpoint-admin/exec.go create mode 100644 cmd/checkpoint-admin/main.go create mode 100644 cmd/checkpoint-admin/status.go create mode 100644 contracts/checkpointoracle/contract/oracle.go create mode 100644 contracts/checkpointoracle/contract/oracle.sol create mode 100644 contracts/checkpointoracle/oracle.go create mode 100644 contracts/checkpointoracle/oracle_test.go create mode 100644 les/checkpointoracle.go create mode 100644 les/sync_test.go delete mode 100755 les/transactions.rlp create mode 100644 mobile/interface_test.go diff --git a/COPYING b/LICENSE similarity index 91% rename from COPYING rename to LICENSE index 8d66e87723..f288702d2f 100644 --- a/COPYING +++ b/LICENSE @@ -1,7 +1,7 @@ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2014 The go-ethereum Authors. + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @@ -616,4 +616,59 @@ above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. \ No newline at end of file +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index c3d809e5a9..97a3a98bd3 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -136,15 +136,27 @@ func (abi *ABI) UnmarshalJSON(data []byte) error { } // empty defaults to function according to the abi spec case "function", "": - abi.Methods[field.Name] = Method{ - Name: field.Name, + name := field.Name + _, ok := abi.Methods[name] + for idx := 0; ok; idx++ { + name = fmt.Sprintf("%s%d", field.Name, idx) + _, ok = abi.Methods[name] + } + abi.Methods[name] = Method{ + Name: name, Const: field.Constant, Inputs: field.Inputs, Outputs: field.Outputs, } case "event": - abi.Events[field.Name] = Event{ - Name: field.Name, + name := field.Name + _, ok := abi.Events[name] + for idx := 0; ok; idx++ { + name = fmt.Sprintf("%s%d", field.Name, idx) + _, ok = abi.Events[name] + } + abi.Events[name] = Event{ + Name: name, Anonymous: field.Anonymous, Inputs: field.Inputs, } diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index fc6ac628bf..9cfe4208d5 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -832,9 +832,6 @@ func TestUnpackIntoMapNamingConflict(t *testing.T) { if err = abi.UnpackIntoMap(receivedMap, "received", data); err != nil { t.Error("naming conflict between two events; no error expected") } - if len(receivedMap) != 1 { - t.Error("naming conflict between two events; event defined latest in the abi expected to be used") - } // Method and event have the same name abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"received","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"receivedAddr","type":"event"}]` @@ -999,3 +996,45 @@ func TestABI_EventById(t *testing.T) { } } } + +func TestDuplicateMethodNames(t *testing.T) { + abiJSON := `[{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"},{"name":"customFallback","type":"string"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]` + contractAbi, err := JSON(strings.NewReader(abiJSON)) + if err != nil { + t.Fatal(err) + } + if _, ok := contractAbi.Methods["transfer"]; !ok { + t.Fatalf("Could not find original method") + } + if _, ok := contractAbi.Methods["transfer0"]; !ok { + t.Fatalf("Could not find duplicate method") + } + if _, ok := contractAbi.Methods["transfer1"]; !ok { + t.Fatalf("Could not find duplicate method") + } + if _, ok := contractAbi.Methods["transfer2"]; ok { + t.Fatalf("Should not have found extra method") + } +} + +// TestDoubleDuplicateMethodNames checks that if transfer0 already exists, there won't be a name +// conflict and that the second transfer method will be renamed transfer1. +func TestDoubleDuplicateMethodNames(t *testing.T) { + abiJSON := `[{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"}],"name":"transfer0","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"},{"name":"customFallback","type":"string"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]` + contractAbi, err := JSON(strings.NewReader(abiJSON)) + if err != nil { + t.Fatal(err) + } + if _, ok := contractAbi.Methods["transfer"]; !ok { + t.Fatalf("Could not find original method") + } + if _, ok := contractAbi.Methods["transfer0"]; !ok { + t.Fatalf("Could not find duplicate method") + } + if _, ok := contractAbi.Methods["transfer1"]; !ok { + t.Fatalf("Could not find duplicate method") + } + if _, ok := contractAbi.Methods["transfer2"]; ok { + t.Fatalf("Should not have found extra method") + } +} diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 236c575646..6c59092b79 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -45,8 +45,10 @@ import ( // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend. var _ bind.ContractBackend = (*SimulatedBackend)(nil) -var errBlockNumberUnsupported = errors.New("SimulatedBackend cannot access blocks other than the latest block") -var errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction") +var ( + errBlockNumberUnsupported = errors.New("simulatedBackend cannot access blocks other than the latest block") + errGasEstimationFailed = errors.New("gas required exceeds allowance or always failing transaction") +) // SimulatedBackend implements bind.ContractBackend, simulating a blockchain in // the background. Its main purpose is to allow easily testing contract bindings. @@ -63,10 +65,9 @@ type SimulatedBackend struct { config *params.ChainConfig } -// NewSimulatedBackend creates a new binding backend using a simulated blockchain -// for testing purposes. -func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { - database := rawdb.NewMemoryDatabase() +// NewSimulatedBackendWithDatabase creates a new binding backend based on the given database +// and uses a simulated blockchain for testing purposes. +func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { genesis := core.Genesis{Config: params.AllEthashProtocolChanges, GasLimit: gasLimit, Alloc: alloc} genesis.MustCommit(database) blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}, nil) @@ -81,6 +82,12 @@ func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBac return backend } +// NewSimulatedBackend creates a new binding backend using a simulated blockchain +// for testing purposes. +func NewSimulatedBackend(alloc core.GenesisAlloc, gasLimit uint64) *SimulatedBackend { + return NewSimulatedBackendWithDatabase(rawdb.NewMemoryDatabase(), alloc, gasLimit) +} + // Commit imports all the pending transactions as a single block and starts a // fresh new state. func (b *SimulatedBackend) Commit() { @@ -424,6 +431,11 @@ func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error { return nil } +// Blockchain returns the underlying blockchain. +func (b *SimulatedBackend) Blockchain() *core.BlockChain { + return b.blockchain +} + // callmsg implements core.Message to allow passing it as a transaction simulator. type callmsg struct { ethereum.CallMsg diff --git a/accounts/abi/bind/base_test.go b/accounts/abi/bind/base_test.go index f65c9e9b49..3ae685e00f 100644 --- a/accounts/abi/bind/base_test.go +++ b/accounts/abi/bind/base_test.go @@ -345,29 +345,3 @@ func TestUnpackIndexedBytesTyLogIntoMap(t *testing.T) { t.Error("unpacked map does not match expected map") } } - -func TestUnpackIntoMapNamingConflict(t *testing.T) { - hash := crypto.Keccak256Hash([]byte("testName")) - mockLog := types.Log{ - Address: common.HexToAddress("0x0"), - Topics: []common.Hash{ - common.HexToHash("0x0"), - hash, - }, - Data: hexutil.MustDecode(hexData), - BlockNumber: uint64(26), - TxHash: common.HexToHash("0x0"), - TxIndex: 111, - BlockHash: common.BytesToHash([]byte{1, 2, 3, 4, 5}), - Index: 7, - Removed: false, - } - - abiString := `[{"anonymous":false,"inputs":[{"indexed":true,"name":"name","type":"string"},{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"}],"name":"received","type":"event"}]` - parsedAbi, _ := abi.JSON(strings.NewReader(abiString)) - bc := bind.NewBoundContract(common.HexToAddress("0x0"), parsedAbi, nil, nil, nil) - receivedMap := make(map[string]interface{}) - if err := bc.UnpackLogIntoMap(receivedMap, "received", mockLog); err == nil { - t.Error("naming conflict between two events; error expected") - } -} diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index 5ee30d0249..7d4a539764 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -38,7 +38,6 @@ type Lang int const ( LangGo Lang = iota LangJava - LangObjC ) // Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant @@ -164,124 +163,62 @@ var bindType = map[Lang]func(kind abi.Type) string{ LangJava: bindTypeJava, } -// 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. -// -// Returned array sizes are in the same order as solidity signatures; inner array size first. -// Array sizes may also be "", indicating a dynamic array. -func wrapArray(stringKind string, innerLen int, innerMapping string) (string, []string) { - remainder := stringKind[innerLen:] - //find all the sizes - matches := regexp.MustCompile(`\[(\d*)\]`).FindAllStringSubmatch(remainder, -1) - parts := make([]string, 0, len(matches)) - for _, match := range matches { - //get group 1 from the regex match - parts = append(parts, match[1]) - } - return innerMapping, parts -} - -// Translates the array sizes to a Go-lang declaration of a (nested) array of the inner type. -// Simply returns the inner type if arraySizes is empty. -func arrayBindingGo(inner string, arraySizes []string) string { - out := "" - //prepend all array sizes, from outer (end arraySizes) to inner (start arraySizes) - for i := len(arraySizes) - 1; i >= 0; i-- { - out += "[" + arraySizes[i] + "]" - } - out += inner - return out -} - -// bindTypeGo converts a Solidity type to a Go one. Since there is no clear mapping -// from all Solidity types to Go ones (e.g. uint17), those that cannot be exactly -// mapped will use an upscaled type (e.g. *big.Int). -func bindTypeGo(kind abi.Type) string { - stringKind := kind.String() - innerLen, innerMapping := bindUnnestedTypeGo(stringKind) - return arrayBindingGo(wrapArray(stringKind, innerLen, innerMapping)) -} - -// The inner function of bindTypeGo, 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 translated type. -func bindUnnestedTypeGo(stringKind string) (int, string) { - - switch { - case strings.HasPrefix(stringKind, "address"): - return len("address"), "common.Address" - - case strings.HasPrefix(stringKind, "bytes"): - parts := regexp.MustCompile(`bytes([0-9]*)`).FindStringSubmatch(stringKind) - return len(parts[0]), fmt.Sprintf("[%s]byte", parts[1]) - - case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): - parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(stringKind) +// bindBasicTypeGo converts basic solidity types(except array, slice and tuple) to Go one. +func bindBasicTypeGo(kind abi.Type) string { + switch kind.T { + case abi.AddressTy: + return "common.Address" + case abi.IntTy, abi.UintTy: + parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(kind.String()) switch parts[2] { case "8", "16", "32", "64": - return len(parts[0]), fmt.Sprintf("%sint%s", parts[1], parts[2]) + return fmt.Sprintf("%sint%s", parts[1], parts[2]) } - return len(parts[0]), "*big.Int" - - case strings.HasPrefix(stringKind, "bool"): - return len("bool"), "bool" - - case strings.HasPrefix(stringKind, "string"): - return len("string"), "string" - + return "*big.Int" + case abi.FixedBytesTy: + return fmt.Sprintf("[%d]byte", kind.Size) + case abi.BytesTy: + return "[]byte" + case abi.FunctionTy: + // todo(rjl493456442) + return "" default: - return len(stringKind), stringKind + // string, bool types + return kind.String() } } -// Translates the array sizes to a Java declaration of a (nested) array of the inner type. -// Simply returns the inner type if arraySizes is empty. -func arrayBindingJava(inner string, arraySizes []string) string { - // Java array type declarations do not include the length. - return inner + strings.Repeat("[]", len(arraySizes)) -} - -// bindTypeJava converts a Solidity type to a Java one. Since there is no clear mapping -// from all Solidity types to Java ones (e.g. uint17), those that cannot be exactly +// bindTypeGo converts solidity types to Go ones. Since there is no clear mapping +// from all Solidity types to Go 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)) +func bindTypeGo(kind abi.Type) string { + // todo(rjl493456442) tuple + switch kind.T { + case abi.ArrayTy: + return fmt.Sprintf("[%d]", kind.Size) + bindTypeGo(*kind.Elem) + case abi.SliceTy: + return "[]" + bindTypeGo(*kind.Elem) + default: + return bindBasicTypeGo(kind) + } } -// 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 translated type. -func bindUnnestedTypeJava(stringKind string) (int, string) { - - switch { - case strings.HasPrefix(stringKind, "address"): - parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind) - if len(parts) != 2 { - return len(stringKind), stringKind - } - if parts[1] == "" { - return len("address"), "Address" - } - return len(parts[0]), "Addresses" - - case strings.HasPrefix(stringKind, "bytes"): - parts := regexp.MustCompile(`bytes([0-9]*)`).FindStringSubmatch(stringKind) - if len(parts) != 2 { - return len(stringKind), stringKind - } - return len(parts[0]), "byte[]" - - case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): - //Note that uint and int (without digits) are also matched, +// bindBasicTypeJava converts basic solidity types(except array, slice and tuple) to Java one. +func bindBasicTypeJava(kind abi.Type) string { + switch kind.T { + case abi.AddressTy: + return "Address" + case abi.IntTy, abi.UintTy: + // Note that uint and int (without digits) are also matched, // these are size 256, and will translate to BigInt (the default). - parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(stringKind) + parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(kind.String()) if len(parts) != 3 { - return len(stringKind), stringKind + return kind.String() + } + // All unsigned integers should be translated to BigInt since gomobile doesn't + // support them. + if parts[1] == "u" { + return "BigInt" } namedSize := map[string]string{ @@ -291,20 +228,48 @@ func bindUnnestedTypeJava(stringKind string) (int, string) { "64": "long", }[parts[2]] - //default to BigInt + // default to BigInt if namedSize == "" { namedSize = "BigInt" } - return len(parts[0]), namedSize - - case strings.HasPrefix(stringKind, "bool"): - return len("bool"), "boolean" - - case strings.HasPrefix(stringKind, "string"): - return len("string"), "String" - + return namedSize + case abi.FixedBytesTy, abi.BytesTy: + return "byte[]" + case abi.BoolTy: + return "boolean" + case abi.StringTy: + return "String" + case abi.FunctionTy: + // todo(rjl493456442) + return "" default: - return len(stringKind), stringKind + return kind.String() + } +} + +// 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 { + switch kind.T { + case abi.ArrayTy, abi.SliceTy: + // Explicitly convert multidimensional types to predefined type in go side. + inner := bindTypeJava(*kind.Elem) + switch inner { + case "boolean": + return "Bools" + case "String": + return "Strings" + case "Address": + return "Addresses" + case "byte[]": + return "Binaries" + case "BigInt": + return "BigInts" + } + return inner + "[]" + default: + return bindBasicTypeJava(kind) } } @@ -329,7 +294,7 @@ func bindTopicTypeGo(kind abi.Type) string { // 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" { + if bound == "String" || bound == "byte[]" { bound = "Hash" } return bound @@ -348,18 +313,8 @@ 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 { diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index eae12b3f4d..e32a7d743d 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -475,11 +475,12 @@ var bindTests = []struct { ` "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" + "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/common" `, ` // Create a simulator and wrap a non-deployed contract - sim := backends.NewSimulatedBackend(nil, uint64(10000000000)) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{}, uint64(10000000000)) nonexistent, err := NewNonExistent(common.Address{}, sim) if err != nil { @@ -960,7 +961,7 @@ var bindTests = []struct { // Tests that packages generated by the binder can be successfully compiled and // the requested tester run against it. -func TestBindings(t *testing.T) { +func TestGolangBindings(t *testing.T) { // Skip the test if no Go command can be found gocmd := runtime.GOROOT() + "/bin/go" if !common.FileExist(gocmd) { @@ -1011,3 +1012,400 @@ func TestBindings(t *testing.T) { t.Fatalf("failed to run binding test: %v\n%s", err, out) } } + +// Tests that java binding generated by the binder is exactly matched. +func TestJavaBindings(t *testing.T) { + var cases = []struct { + name string + contract string + abi string + bytecode string + expected string + }{ + { + "test", + ` + pragma experimental ABIEncoderV2; + pragma solidity ^0.5.2; + + contract test { + function setAddress(address a) public returns(address){} + function setAddressList(address[] memory a_l) public returns(address[] memory){} + function setAddressArray(address[2] memory a_a) public returns(address[2] memory){} + + function setUint8(uint8 u8) public returns(uint8){} + function setUint16(uint16 u16) public returns(uint16){} + function setUint32(uint32 u32) public returns(uint32){} + function setUint64(uint64 u64) public returns(uint64){} + function setUint256(uint256 u256) public returns(uint256){} + function setUint256List(uint256[] memory u256_l) public returns(uint256[] memory){} + function setUint256Array(uint256[2] memory u256_a) public returns(uint256[2] memory){} + + function setInt8(int8 i8) public returns(int8){} + function setInt16(int16 i16) public returns(int16){} + function setInt32(int32 i32) public returns(int32){} + function setInt64(int64 i64) public returns(int64){} + function setInt256(int256 i256) public returns(int256){} + function setInt256List(int256[] memory i256_l) public returns(int256[] memory){} + function setInt256Array(int256[2] memory i256_a) public returns(int256[2] memory){} + + function setBytes1(bytes1 b1) public returns(bytes1) {} + function setBytes32(bytes32 b32) public returns(bytes32) {} + function setBytes(bytes memory bs) public returns(bytes memory) {} + function setBytesList(bytes[] memory bs_l) public returns(bytes[] memory) {} + function setBytesArray(bytes[2] memory bs_a) public returns(bytes[2] memory) {} + + function setString(string memory s) public returns(string memory) {} + function setStringList(string[] memory s_l) public returns(string[] memory) {} + function setStringArray(string[2] memory s_a) public returns(string[2] memory) {} + + function setBool(bool b) public returns(bool) {} + function setBoolList(bool[] memory b_l) public returns(bool[] memory) {} + function setBoolArray(bool[2] memory b_a) public returns(bool[2] memory) {} + }`, + `[{"constant":false,"inputs":[{"name":"u16","type":"uint16"}],"name":"setUint16","outputs":[{"name":"","type":"uint16"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"b_a","type":"bool[2]"}],"name":"setBoolArray","outputs":[{"name":"","type":"bool[2]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"a_a","type":"address[2]"}],"name":"setAddressArray","outputs":[{"name":"","type":"address[2]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bs_l","type":"bytes[]"}],"name":"setBytesList","outputs":[{"name":"","type":"bytes[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"u8","type":"uint8"}],"name":"setUint8","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"u32","type":"uint32"}],"name":"setUint32","outputs":[{"name":"","type":"uint32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"b","type":"bool"}],"name":"setBool","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"i256_l","type":"int256[]"}],"name":"setInt256List","outputs":[{"name":"","type":"int256[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"u256_a","type":"uint256[2]"}],"name":"setUint256Array","outputs":[{"name":"","type":"uint256[2]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"b_l","type":"bool[]"}],"name":"setBoolList","outputs":[{"name":"","type":"bool[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bs_a","type":"bytes[2]"}],"name":"setBytesArray","outputs":[{"name":"","type":"bytes[2]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"a_l","type":"address[]"}],"name":"setAddressList","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"i256_a","type":"int256[2]"}],"name":"setInt256Array","outputs":[{"name":"","type":"int256[2]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"s_a","type":"string[2]"}],"name":"setStringArray","outputs":[{"name":"","type":"string[2]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"s","type":"string"}],"name":"setString","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"u64","type":"uint64"}],"name":"setUint64","outputs":[{"name":"","type":"uint64"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"i16","type":"int16"}],"name":"setInt16","outputs":[{"name":"","type":"int16"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"i8","type":"int8"}],"name":"setInt8","outputs":[{"name":"","type":"int8"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"u256_l","type":"uint256[]"}],"name":"setUint256List","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"i256","type":"int256"}],"name":"setInt256","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"i32","type":"int32"}],"name":"setInt32","outputs":[{"name":"","type":"int32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"b32","type":"bytes32"}],"name":"setBytes32","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"s_l","type":"string[]"}],"name":"setStringList","outputs":[{"name":"","type":"string[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"u256","type":"uint256"}],"name":"setUint256","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"bs","type":"bytes"}],"name":"setBytes","outputs":[{"name":"","type":"bytes"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"a","type":"address"}],"name":"setAddress","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"i64","type":"int64"}],"name":"setInt64","outputs":[{"name":"","type":"int64"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"b1","type":"bytes1"}],"name":"setBytes1","outputs":[{"name":"","type":"bytes1"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]`, + `608060405234801561001057600080fd5b5061265a806100206000396000f3fe608060405234801561001057600080fd5b50600436106101e1576000357c0100000000000000000000000000000000000000000000000000000000900480637fcaf66611610116578063c2b12a73116100b4578063da359dc81161008e578063da359dc814610666578063e30081a014610696578063e673eb32146106c6578063fba1a1c3146106f6576101e1565b8063c2b12a73146105d6578063c577796114610606578063d2282dc514610636576101e1565b80639a19a953116100f05780639a19a95314610516578063a0709e1914610546578063a53b1c1e14610576578063b7d5df31146105a6576101e1565b80637fcaf66614610486578063822cba69146104b657806386114cea146104e6576101e1565b806322722302116101835780635119655d1161015d5780635119655d146103c65780635be6b37e146103f65780636aa482fc146104265780637173b69514610456576101e1565b806322722302146103365780632766a755146103665780634d5ee6da14610396576101e1565b806316c105e2116101bf57806316c105e2146102765780631774e646146102a65780631c9352e2146102d65780631e26fd3314610306576101e1565b80630477988a146101e6578063118a971814610216578063151f547114610246575b600080fd5b61020060048036036101fb9190810190611599565b610726565b60405161020d9190611f01565b60405180910390f35b610230600480360361022b919081019061118d565b61072d565b60405161023d9190611ca6565b60405180910390f35b610260600480360361025b9190810190611123565b61073a565b60405161026d9190611c69565b60405180910390f35b610290600480360361028b9190810190611238565b610747565b60405161029d9190611d05565b60405180910390f35b6102c060048036036102bb919081019061163d565b61074e565b6040516102cd9190611f6d565b60405180910390f35b6102f060048036036102eb91908101906115eb565b610755565b6040516102fd9190611f37565b60405180910390f35b610320600480360361031b91908101906113cf565b61075c565b60405161032d9190611de5565b60405180910390f35b610350600480360361034b91908101906112a2565b610763565b60405161035d9190611d42565b60405180910390f35b610380600480360361037b9190810190611365565b61076a565b60405161038d9190611da8565b60405180910390f35b6103b060048036036103ab91908101906111b6565b610777565b6040516103bd9190611cc1565b60405180910390f35b6103e060048036036103db91908101906111f7565b61077e565b6040516103ed9190611ce3565b60405180910390f35b610410600480360361040b919081019061114c565b61078b565b60405161041d9190611c84565b60405180910390f35b610440600480360361043b9190810190611279565b610792565b60405161044d9190611d27565b60405180910390f35b610470600480360361046b91908101906112e3565b61079f565b60405161047d9190611d64565b60405180910390f35b6104a0600480360361049b9190810190611558565b6107ac565b6040516104ad9190611edf565b60405180910390f35b6104d060048036036104cb9190810190611614565b6107b3565b6040516104dd9190611f52565b60405180910390f35b61050060048036036104fb919081019061148b565b6107ba565b60405161050d9190611e58565b60405180910390f35b610530600480360361052b919081019061152f565b6107c1565b60405161053d9190611ec4565b60405180910390f35b610560600480360361055b919081019061138e565b6107c8565b60405161056d9190611dc3565b60405180910390f35b610590600480360361058b91908101906114b4565b6107cf565b60405161059d9190611e73565b60405180910390f35b6105c060048036036105bb91908101906114dd565b6107d6565b6040516105cd9190611e8e565b60405180910390f35b6105f060048036036105eb9190810190611421565b6107dd565b6040516105fd9190611e1b565b60405180910390f35b610620600480360361061b9190810190611324565b6107e4565b60405161062d9190611d86565b60405180910390f35b610650600480360361064b91908101906115c2565b6107eb565b60405161065d9190611f1c565b60405180910390f35b610680600480360361067b919081019061144a565b6107f2565b60405161068d9190611e36565b60405180910390f35b6106b060048036036106ab91908101906110fa565b6107f9565b6040516106bd9190611c4e565b60405180910390f35b6106e060048036036106db9190810190611506565b610800565b6040516106ed9190611ea9565b60405180910390f35b610710600480360361070b91908101906113f8565b610807565b60405161071d9190611e00565b60405180910390f35b6000919050565b61073561080e565b919050565b610742610830565b919050565b6060919050565b6000919050565b6000919050565b6000919050565b6060919050565b610772610852565b919050565b6060919050565b610786610874565b919050565b6060919050565b61079a61089b565b919050565b6107a76108bd565b919050565b6060919050565b6000919050565b6000919050565b6000919050565b6060919050565b6000919050565b6000919050565b6000919050565b6060919050565b6000919050565b6060919050565b6000919050565b6000919050565b6000919050565b6040805190810160405280600290602082028038833980820191505090505090565b6040805190810160405280600290602082028038833980820191505090505090565b6040805190810160405280600290602082028038833980820191505090505090565b60408051908101604052806002905b60608152602001906001900390816108835790505090565b6040805190810160405280600290602082028038833980820191505090505090565b60408051908101604052806002905b60608152602001906001900390816108cc5790505090565b60006108f082356124f2565b905092915050565b600082601f830112151561090b57600080fd5b600261091e61091982611fb5565b611f88565b9150818385602084028201111561093457600080fd5b60005b83811015610964578161094a88826108e4565b845260208401935060208301925050600181019050610937565b5050505092915050565b600082601f830112151561098157600080fd5b813561099461098f82611fd7565b611f88565b915081818352602084019350602081019050838560208402820111156109b957600080fd5b60005b838110156109e957816109cf88826108e4565b8452602084019350602083019250506001810190506109bc565b5050505092915050565b600082601f8301121515610a0657600080fd5b6002610a19610a1482611fff565b611f88565b91508183856020840282011115610a2f57600080fd5b60005b83811015610a5f5781610a458882610e9e565b845260208401935060208301925050600181019050610a32565b5050505092915050565b600082601f8301121515610a7c57600080fd5b8135610a8f610a8a82612021565b611f88565b91508181835260208401935060208101905083856020840282011115610ab457600080fd5b60005b83811015610ae45781610aca8882610e9e565b845260208401935060208301925050600181019050610ab7565b5050505092915050565b600082601f8301121515610b0157600080fd5b6002610b14610b0f82612049565b611f88565b9150818360005b83811015610b4b5781358601610b318882610eda565b845260208401935060208301925050600181019050610b1b565b5050505092915050565b600082601f8301121515610b6857600080fd5b8135610b7b610b768261206b565b611f88565b9150818183526020840193506020810190508360005b83811015610bc15781358601610ba78882610eda565b845260208401935060208301925050600181019050610b91565b5050505092915050565b600082601f8301121515610bde57600080fd5b6002610bf1610bec82612093565b611f88565b91508183856020840282011115610c0757600080fd5b60005b83811015610c375781610c1d8882610f9a565b845260208401935060208301925050600181019050610c0a565b5050505092915050565b600082601f8301121515610c5457600080fd5b8135610c67610c62826120b5565b611f88565b91508181835260208401935060208101905083856020840282011115610c8c57600080fd5b60005b83811015610cbc5781610ca28882610f9a565b845260208401935060208301925050600181019050610c8f565b5050505092915050565b600082601f8301121515610cd957600080fd5b6002610cec610ce7826120dd565b611f88565b9150818360005b83811015610d235781358601610d098882610fea565b845260208401935060208301925050600181019050610cf3565b5050505092915050565b600082601f8301121515610d4057600080fd5b8135610d53610d4e826120ff565b611f88565b9150818183526020840193506020810190508360005b83811015610d995781358601610d7f8882610fea565b845260208401935060208301925050600181019050610d69565b5050505092915050565b600082601f8301121515610db657600080fd5b6002610dc9610dc482612127565b611f88565b91508183856020840282011115610ddf57600080fd5b60005b83811015610e0f5781610df588826110aa565b845260208401935060208301925050600181019050610de2565b5050505092915050565b600082601f8301121515610e2c57600080fd5b8135610e3f610e3a82612149565b611f88565b91508181835260208401935060208101905083856020840282011115610e6457600080fd5b60005b83811015610e945781610e7a88826110aa565b845260208401935060208301925050600181019050610e67565b5050505092915050565b6000610eaa8235612504565b905092915050565b6000610ebe8235612510565b905092915050565b6000610ed2823561253c565b905092915050565b600082601f8301121515610eed57600080fd5b8135610f00610efb82612171565b611f88565b91508082526020830160208301858383011115610f1c57600080fd5b610f278382846125cd565b50505092915050565b600082601f8301121515610f4357600080fd5b8135610f56610f518261219d565b611f88565b91508082526020830160208301858383011115610f7257600080fd5b610f7d8382846125cd565b50505092915050565b6000610f928235612546565b905092915050565b6000610fa68235612553565b905092915050565b6000610fba823561255d565b905092915050565b6000610fce823561256a565b905092915050565b6000610fe28235612577565b905092915050565b600082601f8301121515610ffd57600080fd5b813561101061100b826121c9565b611f88565b9150808252602083016020830185838301111561102c57600080fd5b6110378382846125cd565b50505092915050565b600082601f830112151561105357600080fd5b8135611066611061826121f5565b611f88565b9150808252602083016020830185838301111561108257600080fd5b61108d8382846125cd565b50505092915050565b60006110a28235612584565b905092915050565b60006110b68235612592565b905092915050565b60006110ca823561259c565b905092915050565b60006110de82356125ac565b905092915050565b60006110f282356125c0565b905092915050565b60006020828403121561110c57600080fd5b600061111a848285016108e4565b91505092915050565b60006040828403121561113557600080fd5b6000611143848285016108f8565b91505092915050565b60006020828403121561115e57600080fd5b600082013567ffffffffffffffff81111561117857600080fd5b6111848482850161096e565b91505092915050565b60006040828403121561119f57600080fd5b60006111ad848285016109f3565b91505092915050565b6000602082840312156111c857600080fd5b600082013567ffffffffffffffff8111156111e257600080fd5b6111ee84828501610a69565b91505092915050565b60006020828403121561120957600080fd5b600082013567ffffffffffffffff81111561122357600080fd5b61122f84828501610aee565b91505092915050565b60006020828403121561124a57600080fd5b600082013567ffffffffffffffff81111561126457600080fd5b61127084828501610b55565b91505092915050565b60006040828403121561128b57600080fd5b600061129984828501610bcb565b91505092915050565b6000602082840312156112b457600080fd5b600082013567ffffffffffffffff8111156112ce57600080fd5b6112da84828501610c41565b91505092915050565b6000602082840312156112f557600080fd5b600082013567ffffffffffffffff81111561130f57600080fd5b61131b84828501610cc6565b91505092915050565b60006020828403121561133657600080fd5b600082013567ffffffffffffffff81111561135057600080fd5b61135c84828501610d2d565b91505092915050565b60006040828403121561137757600080fd5b600061138584828501610da3565b91505092915050565b6000602082840312156113a057600080fd5b600082013567ffffffffffffffff8111156113ba57600080fd5b6113c684828501610e19565b91505092915050565b6000602082840312156113e157600080fd5b60006113ef84828501610e9e565b91505092915050565b60006020828403121561140a57600080fd5b600061141884828501610eb2565b91505092915050565b60006020828403121561143357600080fd5b600061144184828501610ec6565b91505092915050565b60006020828403121561145c57600080fd5b600082013567ffffffffffffffff81111561147657600080fd5b61148284828501610f30565b91505092915050565b60006020828403121561149d57600080fd5b60006114ab84828501610f86565b91505092915050565b6000602082840312156114c657600080fd5b60006114d484828501610f9a565b91505092915050565b6000602082840312156114ef57600080fd5b60006114fd84828501610fae565b91505092915050565b60006020828403121561151857600080fd5b600061152684828501610fc2565b91505092915050565b60006020828403121561154157600080fd5b600061154f84828501610fd6565b91505092915050565b60006020828403121561156a57600080fd5b600082013567ffffffffffffffff81111561158457600080fd5b61159084828501611040565b91505092915050565b6000602082840312156115ab57600080fd5b60006115b984828501611096565b91505092915050565b6000602082840312156115d457600080fd5b60006115e2848285016110aa565b91505092915050565b6000602082840312156115fd57600080fd5b600061160b848285016110be565b91505092915050565b60006020828403121561162657600080fd5b6000611634848285016110d2565b91505092915050565b60006020828403121561164f57600080fd5b600061165d848285016110e6565b91505092915050565b61166f816123f7565b82525050565b61167e816122ab565b61168782612221565b60005b828110156116b95761169d858351611666565b6116a68261235b565b915060208501945060018101905061168a565b5050505050565b60006116cb826122b6565b8084526020840193506116dd8361222b565b60005b8281101561170f576116f3868351611666565b6116fc82612368565b91506020860195506001810190506116e0565b50849250505092915050565b611724816122c1565b61172d82612238565b60005b8281101561175f57611743858351611ab3565b61174c82612375565b9150602085019450600181019050611730565b5050505050565b6000611771826122cc565b80845260208401935061178383612242565b60005b828110156117b557611799868351611ab3565b6117a282612382565b9150602086019550600181019050611786565b50849250505092915050565b60006117cc826122d7565b836020820285016117dc8561224f565b60005b848110156118155783830388526117f7838351611b16565b92506118028261238f565b91506020880197506001810190506117df565b508196508694505050505092915050565b6000611831826122e2565b8084526020840193508360208202850161184a85612259565b60005b84811015611883578383038852611865838351611b16565b92506118708261239c565b915060208801975060018101905061184d565b508196508694505050505092915050565b61189d816122ed565b6118a682612266565b60005b828110156118d8576118bc858351611b5b565b6118c5826123a9565b91506020850194506001810190506118a9565b5050505050565b60006118ea826122f8565b8084526020840193506118fc83612270565b60005b8281101561192e57611912868351611b5b565b61191b826123b6565b91506020860195506001810190506118ff565b50849250505092915050565b600061194582612303565b836020820285016119558561227d565b60005b8481101561198e578383038852611970838351611bcd565b925061197b826123c3565b9150602088019750600181019050611958565b508196508694505050505092915050565b60006119aa8261230e565b808452602084019350836020820285016119c385612287565b60005b848110156119fc5783830388526119de838351611bcd565b92506119e9826123d0565b91506020880197506001810190506119c6565b508196508694505050505092915050565b611a1681612319565b611a1f82612294565b60005b82811015611a5157611a35858351611c12565b611a3e826123dd565b9150602085019450600181019050611a22565b5050505050565b6000611a6382612324565b808452602084019350611a758361229e565b60005b82811015611aa757611a8b868351611c12565b611a94826123ea565b9150602086019550600181019050611a78565b50849250505092915050565b611abc81612409565b82525050565b611acb81612415565b82525050565b611ada81612441565b82525050565b6000611aeb8261233a565b808452611aff8160208601602086016125dc565b611b088161260f565b602085010191505092915050565b6000611b218261232f565b808452611b358160208601602086016125dc565b611b3e8161260f565b602085010191505092915050565b611b558161244b565b82525050565b611b6481612458565b82525050565b611b7381612462565b82525050565b611b828161246f565b82525050565b611b918161247c565b82525050565b6000611ba282612350565b808452611bb68160208601602086016125dc565b611bbf8161260f565b602085010191505092915050565b6000611bd882612345565b808452611bec8160208601602086016125dc565b611bf58161260f565b602085010191505092915050565b611c0c81612489565b82525050565b611c1b816124b7565b82525050565b611c2a816124c1565b82525050565b611c39816124d1565b82525050565b611c48816124e5565b82525050565b6000602082019050611c636000830184611666565b92915050565b6000604082019050611c7e6000830184611675565b92915050565b60006020820190508181036000830152611c9e81846116c0565b905092915050565b6000604082019050611cbb600083018461171b565b92915050565b60006020820190508181036000830152611cdb8184611766565b905092915050565b60006020820190508181036000830152611cfd81846117c1565b905092915050565b60006020820190508181036000830152611d1f8184611826565b905092915050565b6000604082019050611d3c6000830184611894565b92915050565b60006020820190508181036000830152611d5c81846118df565b905092915050565b60006020820190508181036000830152611d7e818461193a565b905092915050565b60006020820190508181036000830152611da0818461199f565b905092915050565b6000604082019050611dbd6000830184611a0d565b92915050565b60006020820190508181036000830152611ddd8184611a58565b905092915050565b6000602082019050611dfa6000830184611ab3565b92915050565b6000602082019050611e156000830184611ac2565b92915050565b6000602082019050611e306000830184611ad1565b92915050565b60006020820190508181036000830152611e508184611ae0565b905092915050565b6000602082019050611e6d6000830184611b4c565b92915050565b6000602082019050611e886000830184611b5b565b92915050565b6000602082019050611ea36000830184611b6a565b92915050565b6000602082019050611ebe6000830184611b79565b92915050565b6000602082019050611ed96000830184611b88565b92915050565b60006020820190508181036000830152611ef98184611b97565b905092915050565b6000602082019050611f166000830184611c03565b92915050565b6000602082019050611f316000830184611c12565b92915050565b6000602082019050611f4c6000830184611c21565b92915050565b6000602082019050611f676000830184611c30565b92915050565b6000602082019050611f826000830184611c3f565b92915050565b6000604051905081810181811067ffffffffffffffff82111715611fab57600080fd5b8060405250919050565b600067ffffffffffffffff821115611fcc57600080fd5b602082029050919050565b600067ffffffffffffffff821115611fee57600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561201657600080fd5b602082029050919050565b600067ffffffffffffffff82111561203857600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561206057600080fd5b602082029050919050565b600067ffffffffffffffff82111561208257600080fd5b602082029050602081019050919050565b600067ffffffffffffffff8211156120aa57600080fd5b602082029050919050565b600067ffffffffffffffff8211156120cc57600080fd5b602082029050602081019050919050565b600067ffffffffffffffff8211156120f457600080fd5b602082029050919050565b600067ffffffffffffffff82111561211657600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561213e57600080fd5b602082029050919050565b600067ffffffffffffffff82111561216057600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561218857600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff8211156121b457600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff8211156121e057600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff82111561220c57600080fd5b601f19601f8301169050602081019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600081519050919050565b600081519050919050565b600081519050919050565b600081519050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b600061240282612497565b9050919050565b60008115159050919050565b60007fff0000000000000000000000000000000000000000000000000000000000000082169050919050565b6000819050919050565b60008160010b9050919050565b6000819050919050565b60008160030b9050919050565b60008160070b9050919050565b60008160000b9050919050565b600061ffff82169050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b600063ffffffff82169050919050565b600067ffffffffffffffff82169050919050565b600060ff82169050919050565b60006124fd82612497565b9050919050565b60008115159050919050565b60007fff0000000000000000000000000000000000000000000000000000000000000082169050919050565b6000819050919050565b60008160010b9050919050565b6000819050919050565b60008160030b9050919050565b60008160070b9050919050565b60008160000b9050919050565b600061ffff82169050919050565b6000819050919050565b600063ffffffff82169050919050565b600067ffffffffffffffff82169050919050565b600060ff82169050919050565b82818337600083830152505050565b60005b838110156125fa5780820151818401526020810190506125df565b83811115612609576000848401525b50505050565b6000601f19601f830116905091905056fea265627a7a723058206fe37171cf1b10ebd291cfdca61d67e7fc3c208795e999c833c42a14d86cf00d6c6578706572696d656e74616cf50037`, + ` +// This file is an automatically generated Java binding. Do not modify as any +// change will likely be lost upon the next re-generation! + +package bindtest; + +import org.ethereum.geth.*; + + +public class Test { + // ABI is the input ABI used to generate the binding from. + public final static String ABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"u16\",\"type\":\"uint16\"}],\"name\":\"setUint16\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"b_a\",\"type\":\"bool[2]\"}],\"name\":\"setBoolArray\",\"outputs\":[{\"name\":\"\",\"type\":\"bool[2]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a_a\",\"type\":\"address[2]\"}],\"name\":\"setAddressArray\",\"outputs\":[{\"name\":\"\",\"type\":\"address[2]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"bs_l\",\"type\":\"bytes[]\"}],\"name\":\"setBytesList\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"u8\",\"type\":\"uint8\"}],\"name\":\"setUint8\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"u32\",\"type\":\"uint32\"}],\"name\":\"setUint32\",\"outputs\":[{\"name\":\"\",\"type\":\"uint32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"b\",\"type\":\"bool\"}],\"name\":\"setBool\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"i256_l\",\"type\":\"int256[]\"}],\"name\":\"setInt256List\",\"outputs\":[{\"name\":\"\",\"type\":\"int256[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"u256_a\",\"type\":\"uint256[2]\"}],\"name\":\"setUint256Array\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256[2]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"b_l\",\"type\":\"bool[]\"}],\"name\":\"setBoolList\",\"outputs\":[{\"name\":\"\",\"type\":\"bool[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"bs_a\",\"type\":\"bytes[2]\"}],\"name\":\"setBytesArray\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes[2]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a_l\",\"type\":\"address[]\"}],\"name\":\"setAddressList\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"i256_a\",\"type\":\"int256[2]\"}],\"name\":\"setInt256Array\",\"outputs\":[{\"name\":\"\",\"type\":\"int256[2]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"s_a\",\"type\":\"string[2]\"}],\"name\":\"setStringArray\",\"outputs\":[{\"name\":\"\",\"type\":\"string[2]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"s\",\"type\":\"string\"}],\"name\":\"setString\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"u64\",\"type\":\"uint64\"}],\"name\":\"setUint64\",\"outputs\":[{\"name\":\"\",\"type\":\"uint64\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"i16\",\"type\":\"int16\"}],\"name\":\"setInt16\",\"outputs\":[{\"name\":\"\",\"type\":\"int16\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"i8\",\"type\":\"int8\"}],\"name\":\"setInt8\",\"outputs\":[{\"name\":\"\",\"type\":\"int8\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"u256_l\",\"type\":\"uint256[]\"}],\"name\":\"setUint256List\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"i256\",\"type\":\"int256\"}],\"name\":\"setInt256\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"i32\",\"type\":\"int32\"}],\"name\":\"setInt32\",\"outputs\":[{\"name\":\"\",\"type\":\"int32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"b32\",\"type\":\"bytes32\"}],\"name\":\"setBytes32\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"s_l\",\"type\":\"string[]\"}],\"name\":\"setStringList\",\"outputs\":[{\"name\":\"\",\"type\":\"string[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"u256\",\"type\":\"uint256\"}],\"name\":\"setUint256\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"bs\",\"type\":\"bytes\"}],\"name\":\"setBytes\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"address\"}],\"name\":\"setAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"i64\",\"type\":\"int64\"}],\"name\":\"setInt64\",\"outputs\":[{\"name\":\"\",\"type\":\"int64\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"b1\",\"type\":\"bytes1\"}],\"name\":\"setBytes1\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes1\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; + + + // BYTECODE is the compiled bytecode used for deploying new contracts. + public final static String BYTECODE = "0x608060405234801561001057600080fd5b5061265a806100206000396000f3fe608060405234801561001057600080fd5b50600436106101e1576000357c0100000000000000000000000000000000000000000000000000000000900480637fcaf66611610116578063c2b12a73116100b4578063da359dc81161008e578063da359dc814610666578063e30081a014610696578063e673eb32146106c6578063fba1a1c3146106f6576101e1565b8063c2b12a73146105d6578063c577796114610606578063d2282dc514610636576101e1565b80639a19a953116100f05780639a19a95314610516578063a0709e1914610546578063a53b1c1e14610576578063b7d5df31146105a6576101e1565b80637fcaf66614610486578063822cba69146104b657806386114cea146104e6576101e1565b806322722302116101835780635119655d1161015d5780635119655d146103c65780635be6b37e146103f65780636aa482fc146104265780637173b69514610456576101e1565b806322722302146103365780632766a755146103665780634d5ee6da14610396576101e1565b806316c105e2116101bf57806316c105e2146102765780631774e646146102a65780631c9352e2146102d65780631e26fd3314610306576101e1565b80630477988a146101e6578063118a971814610216578063151f547114610246575b600080fd5b61020060048036036101fb9190810190611599565b610726565b60405161020d9190611f01565b60405180910390f35b610230600480360361022b919081019061118d565b61072d565b60405161023d9190611ca6565b60405180910390f35b610260600480360361025b9190810190611123565b61073a565b60405161026d9190611c69565b60405180910390f35b610290600480360361028b9190810190611238565b610747565b60405161029d9190611d05565b60405180910390f35b6102c060048036036102bb919081019061163d565b61074e565b6040516102cd9190611f6d565b60405180910390f35b6102f060048036036102eb91908101906115eb565b610755565b6040516102fd9190611f37565b60405180910390f35b610320600480360361031b91908101906113cf565b61075c565b60405161032d9190611de5565b60405180910390f35b610350600480360361034b91908101906112a2565b610763565b60405161035d9190611d42565b60405180910390f35b610380600480360361037b9190810190611365565b61076a565b60405161038d9190611da8565b60405180910390f35b6103b060048036036103ab91908101906111b6565b610777565b6040516103bd9190611cc1565b60405180910390f35b6103e060048036036103db91908101906111f7565b61077e565b6040516103ed9190611ce3565b60405180910390f35b610410600480360361040b919081019061114c565b61078b565b60405161041d9190611c84565b60405180910390f35b610440600480360361043b9190810190611279565b610792565b60405161044d9190611d27565b60405180910390f35b610470600480360361046b91908101906112e3565b61079f565b60405161047d9190611d64565b60405180910390f35b6104a0600480360361049b9190810190611558565b6107ac565b6040516104ad9190611edf565b60405180910390f35b6104d060048036036104cb9190810190611614565b6107b3565b6040516104dd9190611f52565b60405180910390f35b61050060048036036104fb919081019061148b565b6107ba565b60405161050d9190611e58565b60405180910390f35b610530600480360361052b919081019061152f565b6107c1565b60405161053d9190611ec4565b60405180910390f35b610560600480360361055b919081019061138e565b6107c8565b60405161056d9190611dc3565b60405180910390f35b610590600480360361058b91908101906114b4565b6107cf565b60405161059d9190611e73565b60405180910390f35b6105c060048036036105bb91908101906114dd565b6107d6565b6040516105cd9190611e8e565b60405180910390f35b6105f060048036036105eb9190810190611421565b6107dd565b6040516105fd9190611e1b565b60405180910390f35b610620600480360361061b9190810190611324565b6107e4565b60405161062d9190611d86565b60405180910390f35b610650600480360361064b91908101906115c2565b6107eb565b60405161065d9190611f1c565b60405180910390f35b610680600480360361067b919081019061144a565b6107f2565b60405161068d9190611e36565b60405180910390f35b6106b060048036036106ab91908101906110fa565b6107f9565b6040516106bd9190611c4e565b60405180910390f35b6106e060048036036106db9190810190611506565b610800565b6040516106ed9190611ea9565b60405180910390f35b610710600480360361070b91908101906113f8565b610807565b60405161071d9190611e00565b60405180910390f35b6000919050565b61073561080e565b919050565b610742610830565b919050565b6060919050565b6000919050565b6000919050565b6000919050565b6060919050565b610772610852565b919050565b6060919050565b610786610874565b919050565b6060919050565b61079a61089b565b919050565b6107a76108bd565b919050565b6060919050565b6000919050565b6000919050565b6000919050565b6060919050565b6000919050565b6000919050565b6000919050565b6060919050565b6000919050565b6060919050565b6000919050565b6000919050565b6000919050565b6040805190810160405280600290602082028038833980820191505090505090565b6040805190810160405280600290602082028038833980820191505090505090565b6040805190810160405280600290602082028038833980820191505090505090565b60408051908101604052806002905b60608152602001906001900390816108835790505090565b6040805190810160405280600290602082028038833980820191505090505090565b60408051908101604052806002905b60608152602001906001900390816108cc5790505090565b60006108f082356124f2565b905092915050565b600082601f830112151561090b57600080fd5b600261091e61091982611fb5565b611f88565b9150818385602084028201111561093457600080fd5b60005b83811015610964578161094a88826108e4565b845260208401935060208301925050600181019050610937565b5050505092915050565b600082601f830112151561098157600080fd5b813561099461098f82611fd7565b611f88565b915081818352602084019350602081019050838560208402820111156109b957600080fd5b60005b838110156109e957816109cf88826108e4565b8452602084019350602083019250506001810190506109bc565b5050505092915050565b600082601f8301121515610a0657600080fd5b6002610a19610a1482611fff565b611f88565b91508183856020840282011115610a2f57600080fd5b60005b83811015610a5f5781610a458882610e9e565b845260208401935060208301925050600181019050610a32565b5050505092915050565b600082601f8301121515610a7c57600080fd5b8135610a8f610a8a82612021565b611f88565b91508181835260208401935060208101905083856020840282011115610ab457600080fd5b60005b83811015610ae45781610aca8882610e9e565b845260208401935060208301925050600181019050610ab7565b5050505092915050565b600082601f8301121515610b0157600080fd5b6002610b14610b0f82612049565b611f88565b9150818360005b83811015610b4b5781358601610b318882610eda565b845260208401935060208301925050600181019050610b1b565b5050505092915050565b600082601f8301121515610b6857600080fd5b8135610b7b610b768261206b565b611f88565b9150818183526020840193506020810190508360005b83811015610bc15781358601610ba78882610eda565b845260208401935060208301925050600181019050610b91565b5050505092915050565b600082601f8301121515610bde57600080fd5b6002610bf1610bec82612093565b611f88565b91508183856020840282011115610c0757600080fd5b60005b83811015610c375781610c1d8882610f9a565b845260208401935060208301925050600181019050610c0a565b5050505092915050565b600082601f8301121515610c5457600080fd5b8135610c67610c62826120b5565b611f88565b91508181835260208401935060208101905083856020840282011115610c8c57600080fd5b60005b83811015610cbc5781610ca28882610f9a565b845260208401935060208301925050600181019050610c8f565b5050505092915050565b600082601f8301121515610cd957600080fd5b6002610cec610ce7826120dd565b611f88565b9150818360005b83811015610d235781358601610d098882610fea565b845260208401935060208301925050600181019050610cf3565b5050505092915050565b600082601f8301121515610d4057600080fd5b8135610d53610d4e826120ff565b611f88565b9150818183526020840193506020810190508360005b83811015610d995781358601610d7f8882610fea565b845260208401935060208301925050600181019050610d69565b5050505092915050565b600082601f8301121515610db657600080fd5b6002610dc9610dc482612127565b611f88565b91508183856020840282011115610ddf57600080fd5b60005b83811015610e0f5781610df588826110aa565b845260208401935060208301925050600181019050610de2565b5050505092915050565b600082601f8301121515610e2c57600080fd5b8135610e3f610e3a82612149565b611f88565b91508181835260208401935060208101905083856020840282011115610e6457600080fd5b60005b83811015610e945781610e7a88826110aa565b845260208401935060208301925050600181019050610e67565b5050505092915050565b6000610eaa8235612504565b905092915050565b6000610ebe8235612510565b905092915050565b6000610ed2823561253c565b905092915050565b600082601f8301121515610eed57600080fd5b8135610f00610efb82612171565b611f88565b91508082526020830160208301858383011115610f1c57600080fd5b610f278382846125cd565b50505092915050565b600082601f8301121515610f4357600080fd5b8135610f56610f518261219d565b611f88565b91508082526020830160208301858383011115610f7257600080fd5b610f7d8382846125cd565b50505092915050565b6000610f928235612546565b905092915050565b6000610fa68235612553565b905092915050565b6000610fba823561255d565b905092915050565b6000610fce823561256a565b905092915050565b6000610fe28235612577565b905092915050565b600082601f8301121515610ffd57600080fd5b813561101061100b826121c9565b611f88565b9150808252602083016020830185838301111561102c57600080fd5b6110378382846125cd565b50505092915050565b600082601f830112151561105357600080fd5b8135611066611061826121f5565b611f88565b9150808252602083016020830185838301111561108257600080fd5b61108d8382846125cd565b50505092915050565b60006110a28235612584565b905092915050565b60006110b68235612592565b905092915050565b60006110ca823561259c565b905092915050565b60006110de82356125ac565b905092915050565b60006110f282356125c0565b905092915050565b60006020828403121561110c57600080fd5b600061111a848285016108e4565b91505092915050565b60006040828403121561113557600080fd5b6000611143848285016108f8565b91505092915050565b60006020828403121561115e57600080fd5b600082013567ffffffffffffffff81111561117857600080fd5b6111848482850161096e565b91505092915050565b60006040828403121561119f57600080fd5b60006111ad848285016109f3565b91505092915050565b6000602082840312156111c857600080fd5b600082013567ffffffffffffffff8111156111e257600080fd5b6111ee84828501610a69565b91505092915050565b60006020828403121561120957600080fd5b600082013567ffffffffffffffff81111561122357600080fd5b61122f84828501610aee565b91505092915050565b60006020828403121561124a57600080fd5b600082013567ffffffffffffffff81111561126457600080fd5b61127084828501610b55565b91505092915050565b60006040828403121561128b57600080fd5b600061129984828501610bcb565b91505092915050565b6000602082840312156112b457600080fd5b600082013567ffffffffffffffff8111156112ce57600080fd5b6112da84828501610c41565b91505092915050565b6000602082840312156112f557600080fd5b600082013567ffffffffffffffff81111561130f57600080fd5b61131b84828501610cc6565b91505092915050565b60006020828403121561133657600080fd5b600082013567ffffffffffffffff81111561135057600080fd5b61135c84828501610d2d565b91505092915050565b60006040828403121561137757600080fd5b600061138584828501610da3565b91505092915050565b6000602082840312156113a057600080fd5b600082013567ffffffffffffffff8111156113ba57600080fd5b6113c684828501610e19565b91505092915050565b6000602082840312156113e157600080fd5b60006113ef84828501610e9e565b91505092915050565b60006020828403121561140a57600080fd5b600061141884828501610eb2565b91505092915050565b60006020828403121561143357600080fd5b600061144184828501610ec6565b91505092915050565b60006020828403121561145c57600080fd5b600082013567ffffffffffffffff81111561147657600080fd5b61148284828501610f30565b91505092915050565b60006020828403121561149d57600080fd5b60006114ab84828501610f86565b91505092915050565b6000602082840312156114c657600080fd5b60006114d484828501610f9a565b91505092915050565b6000602082840312156114ef57600080fd5b60006114fd84828501610fae565b91505092915050565b60006020828403121561151857600080fd5b600061152684828501610fc2565b91505092915050565b60006020828403121561154157600080fd5b600061154f84828501610fd6565b91505092915050565b60006020828403121561156a57600080fd5b600082013567ffffffffffffffff81111561158457600080fd5b61159084828501611040565b91505092915050565b6000602082840312156115ab57600080fd5b60006115b984828501611096565b91505092915050565b6000602082840312156115d457600080fd5b60006115e2848285016110aa565b91505092915050565b6000602082840312156115fd57600080fd5b600061160b848285016110be565b91505092915050565b60006020828403121561162657600080fd5b6000611634848285016110d2565b91505092915050565b60006020828403121561164f57600080fd5b600061165d848285016110e6565b91505092915050565b61166f816123f7565b82525050565b61167e816122ab565b61168782612221565b60005b828110156116b95761169d858351611666565b6116a68261235b565b915060208501945060018101905061168a565b5050505050565b60006116cb826122b6565b8084526020840193506116dd8361222b565b60005b8281101561170f576116f3868351611666565b6116fc82612368565b91506020860195506001810190506116e0565b50849250505092915050565b611724816122c1565b61172d82612238565b60005b8281101561175f57611743858351611ab3565b61174c82612375565b9150602085019450600181019050611730565b5050505050565b6000611771826122cc565b80845260208401935061178383612242565b60005b828110156117b557611799868351611ab3565b6117a282612382565b9150602086019550600181019050611786565b50849250505092915050565b60006117cc826122d7565b836020820285016117dc8561224f565b60005b848110156118155783830388526117f7838351611b16565b92506118028261238f565b91506020880197506001810190506117df565b508196508694505050505092915050565b6000611831826122e2565b8084526020840193508360208202850161184a85612259565b60005b84811015611883578383038852611865838351611b16565b92506118708261239c565b915060208801975060018101905061184d565b508196508694505050505092915050565b61189d816122ed565b6118a682612266565b60005b828110156118d8576118bc858351611b5b565b6118c5826123a9565b91506020850194506001810190506118a9565b5050505050565b60006118ea826122f8565b8084526020840193506118fc83612270565b60005b8281101561192e57611912868351611b5b565b61191b826123b6565b91506020860195506001810190506118ff565b50849250505092915050565b600061194582612303565b836020820285016119558561227d565b60005b8481101561198e578383038852611970838351611bcd565b925061197b826123c3565b9150602088019750600181019050611958565b508196508694505050505092915050565b60006119aa8261230e565b808452602084019350836020820285016119c385612287565b60005b848110156119fc5783830388526119de838351611bcd565b92506119e9826123d0565b91506020880197506001810190506119c6565b508196508694505050505092915050565b611a1681612319565b611a1f82612294565b60005b82811015611a5157611a35858351611c12565b611a3e826123dd565b9150602085019450600181019050611a22565b5050505050565b6000611a6382612324565b808452602084019350611a758361229e565b60005b82811015611aa757611a8b868351611c12565b611a94826123ea565b9150602086019550600181019050611a78565b50849250505092915050565b611abc81612409565b82525050565b611acb81612415565b82525050565b611ada81612441565b82525050565b6000611aeb8261233a565b808452611aff8160208601602086016125dc565b611b088161260f565b602085010191505092915050565b6000611b218261232f565b808452611b358160208601602086016125dc565b611b3e8161260f565b602085010191505092915050565b611b558161244b565b82525050565b611b6481612458565b82525050565b611b7381612462565b82525050565b611b828161246f565b82525050565b611b918161247c565b82525050565b6000611ba282612350565b808452611bb68160208601602086016125dc565b611bbf8161260f565b602085010191505092915050565b6000611bd882612345565b808452611bec8160208601602086016125dc565b611bf58161260f565b602085010191505092915050565b611c0c81612489565b82525050565b611c1b816124b7565b82525050565b611c2a816124c1565b82525050565b611c39816124d1565b82525050565b611c48816124e5565b82525050565b6000602082019050611c636000830184611666565b92915050565b6000604082019050611c7e6000830184611675565b92915050565b60006020820190508181036000830152611c9e81846116c0565b905092915050565b6000604082019050611cbb600083018461171b565b92915050565b60006020820190508181036000830152611cdb8184611766565b905092915050565b60006020820190508181036000830152611cfd81846117c1565b905092915050565b60006020820190508181036000830152611d1f8184611826565b905092915050565b6000604082019050611d3c6000830184611894565b92915050565b60006020820190508181036000830152611d5c81846118df565b905092915050565b60006020820190508181036000830152611d7e818461193a565b905092915050565b60006020820190508181036000830152611da0818461199f565b905092915050565b6000604082019050611dbd6000830184611a0d565b92915050565b60006020820190508181036000830152611ddd8184611a58565b905092915050565b6000602082019050611dfa6000830184611ab3565b92915050565b6000602082019050611e156000830184611ac2565b92915050565b6000602082019050611e306000830184611ad1565b92915050565b60006020820190508181036000830152611e508184611ae0565b905092915050565b6000602082019050611e6d6000830184611b4c565b92915050565b6000602082019050611e886000830184611b5b565b92915050565b6000602082019050611ea36000830184611b6a565b92915050565b6000602082019050611ebe6000830184611b79565b92915050565b6000602082019050611ed96000830184611b88565b92915050565b60006020820190508181036000830152611ef98184611b97565b905092915050565b6000602082019050611f166000830184611c03565b92915050565b6000602082019050611f316000830184611c12565b92915050565b6000602082019050611f4c6000830184611c21565b92915050565b6000602082019050611f676000830184611c30565b92915050565b6000602082019050611f826000830184611c3f565b92915050565b6000604051905081810181811067ffffffffffffffff82111715611fab57600080fd5b8060405250919050565b600067ffffffffffffffff821115611fcc57600080fd5b602082029050919050565b600067ffffffffffffffff821115611fee57600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561201657600080fd5b602082029050919050565b600067ffffffffffffffff82111561203857600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561206057600080fd5b602082029050919050565b600067ffffffffffffffff82111561208257600080fd5b602082029050602081019050919050565b600067ffffffffffffffff8211156120aa57600080fd5b602082029050919050565b600067ffffffffffffffff8211156120cc57600080fd5b602082029050602081019050919050565b600067ffffffffffffffff8211156120f457600080fd5b602082029050919050565b600067ffffffffffffffff82111561211657600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561213e57600080fd5b602082029050919050565b600067ffffffffffffffff82111561216057600080fd5b602082029050602081019050919050565b600067ffffffffffffffff82111561218857600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff8211156121b457600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff8211156121e057600080fd5b601f19601f8301169050602081019050919050565b600067ffffffffffffffff82111561220c57600080fd5b601f19601f8301169050602081019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b6000819050919050565b6000602082019050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600060029050919050565b600081519050919050565b600081519050919050565b600081519050919050565b600081519050919050565b600081519050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b6000602082019050919050565b600061240282612497565b9050919050565b60008115159050919050565b60007fff0000000000000000000000000000000000000000000000000000000000000082169050919050565b6000819050919050565b60008160010b9050919050565b6000819050919050565b60008160030b9050919050565b60008160070b9050919050565b60008160000b9050919050565b600061ffff82169050919050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b6000819050919050565b600063ffffffff82169050919050565b600067ffffffffffffffff82169050919050565b600060ff82169050919050565b60006124fd82612497565b9050919050565b60008115159050919050565b60007fff0000000000000000000000000000000000000000000000000000000000000082169050919050565b6000819050919050565b60008160010b9050919050565b6000819050919050565b60008160030b9050919050565b60008160070b9050919050565b60008160000b9050919050565b600061ffff82169050919050565b6000819050919050565b600063ffffffff82169050919050565b600067ffffffffffffffff82169050919050565b600060ff82169050919050565b82818337600083830152505050565b60005b838110156125fa5780820151818401526020810190506125df565b83811115612609576000848401525b50505050565b6000601f19601f830116905091905056fea265627a7a723058206fe37171cf1b10ebd291cfdca61d67e7fc3c208795e999c833c42a14d86cf00d6c6578706572696d656e74616cf50037"; + + // deploy deploys a new Ethereum contract, binding an instance of Test to it. + public static Test deploy(TransactOpts auth, EthereumClient client) throws Exception { + Interfaces args = Geth.newInterfaces(0); + + return new Test(Geth.deployContract(auth, ABI, Geth.decodeFromHex(BYTECODE), client, args)); + } + + // Internal constructor used by contract deployment. + private Test(BoundContract deployment) { + this.Address = deployment.getAddress(); + this.Deployer = deployment.getDeployer(); + this.Contract = deployment; + } + + + // 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 Test, bound to a specific deployed contract. + public Test(Address address, EthereumClient client) throws Exception { + this(Geth.bindContract(address, ABI, client)); + } + + + + + // setAddress is a paid mutator transaction binding the contract method 0xe30081a0. + // + // Solidity: function setAddress(address a) returns(address) + public Transaction setAddress(TransactOpts opts, Address a) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setAddress(a);args.set(0,arg0); + + return this.Contract.transact(opts, "setAddress" , args); + } + + // setAddressArray is a paid mutator transaction binding the contract method 0x151f5471. + // + // Solidity: function setAddressArray(address[2] a_a) returns(address[2]) + public Transaction setAddressArray(TransactOpts opts, Addresses a_a) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setAddresses(a_a);args.set(0,arg0); + + return this.Contract.transact(opts, "setAddressArray" , args); + } + + // setAddressList is a paid mutator transaction binding the contract method 0x5be6b37e. + // + // Solidity: function setAddressList(address[] a_l) returns(address[]) + public Transaction setAddressList(TransactOpts opts, Addresses a_l) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setAddresses(a_l);args.set(0,arg0); + + return this.Contract.transact(opts, "setAddressList" , args); + } + + // setBool is a paid mutator transaction binding the contract method 0x1e26fd33. + // + // Solidity: function setBool(bool b) returns(bool) + public Transaction setBool(TransactOpts opts, boolean b) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBool(b);args.set(0,arg0); + + return this.Contract.transact(opts, "setBool" , args); + } + + // setBoolArray is a paid mutator transaction binding the contract method 0x118a9718. + // + // Solidity: function setBoolArray(bool[2] b_a) returns(bool[2]) + public Transaction setBoolArray(TransactOpts opts, Bools b_a) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBools(b_a);args.set(0,arg0); + + return this.Contract.transact(opts, "setBoolArray" , args); + } + + // setBoolList is a paid mutator transaction binding the contract method 0x4d5ee6da. + // + // Solidity: function setBoolList(bool[] b_l) returns(bool[]) + public Transaction setBoolList(TransactOpts opts, Bools b_l) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBools(b_l);args.set(0,arg0); + + return this.Contract.transact(opts, "setBoolList" , args); + } + + // setBytes is a paid mutator transaction binding the contract method 0xda359dc8. + // + // Solidity: function setBytes(bytes bs) returns(bytes) + public Transaction setBytes(TransactOpts opts, byte[] bs) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBinary(bs);args.set(0,arg0); + + return this.Contract.transact(opts, "setBytes" , args); + } + + // setBytes1 is a paid mutator transaction binding the contract method 0xfba1a1c3. + // + // Solidity: function setBytes1(bytes1 b1) returns(bytes1) + public Transaction setBytes1(TransactOpts opts, byte[] b1) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBinary(b1);args.set(0,arg0); + + return this.Contract.transact(opts, "setBytes1" , args); + } + + // setBytes32 is a paid mutator transaction binding the contract method 0xc2b12a73. + // + // Solidity: function setBytes32(bytes32 b32) returns(bytes32) + public Transaction setBytes32(TransactOpts opts, byte[] b32) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBinary(b32);args.set(0,arg0); + + return this.Contract.transact(opts, "setBytes32" , args); + } + + // setBytesArray is a paid mutator transaction binding the contract method 0x5119655d. + // + // Solidity: function setBytesArray(bytes[2] bs_a) returns(bytes[2]) + public Transaction setBytesArray(TransactOpts opts, Binaries bs_a) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBinaries(bs_a);args.set(0,arg0); + + return this.Contract.transact(opts, "setBytesArray" , args); + } + + // setBytesList is a paid mutator transaction binding the contract method 0x16c105e2. + // + // Solidity: function setBytesList(bytes[] bs_l) returns(bytes[]) + public Transaction setBytesList(TransactOpts opts, Binaries bs_l) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBinaries(bs_l);args.set(0,arg0); + + return this.Contract.transact(opts, "setBytesList" , args); + } + + // setInt16 is a paid mutator transaction binding the contract method 0x86114cea. + // + // Solidity: function setInt16(int16 i16) returns(int16) + public Transaction setInt16(TransactOpts opts, short i16) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setInt16(i16);args.set(0,arg0); + + return this.Contract.transact(opts, "setInt16" , args); + } + + // setInt256 is a paid mutator transaction binding the contract method 0xa53b1c1e. + // + // Solidity: function setInt256(int256 i256) returns(int256) + public Transaction setInt256(TransactOpts opts, BigInt i256) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBigInt(i256);args.set(0,arg0); + + return this.Contract.transact(opts, "setInt256" , args); + } + + // setInt256Array is a paid mutator transaction binding the contract method 0x6aa482fc. + // + // Solidity: function setInt256Array(int256[2] i256_a) returns(int256[2]) + public Transaction setInt256Array(TransactOpts opts, BigInts i256_a) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBigInts(i256_a);args.set(0,arg0); + + return this.Contract.transact(opts, "setInt256Array" , args); + } + + // setInt256List is a paid mutator transaction binding the contract method 0x22722302. + // + // Solidity: function setInt256List(int256[] i256_l) returns(int256[]) + public Transaction setInt256List(TransactOpts opts, BigInts i256_l) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBigInts(i256_l);args.set(0,arg0); + + return this.Contract.transact(opts, "setInt256List" , args); + } + + // setInt32 is a paid mutator transaction binding the contract method 0xb7d5df31. + // + // Solidity: function setInt32(int32 i32) returns(int32) + public Transaction setInt32(TransactOpts opts, int i32) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setInt32(i32);args.set(0,arg0); + + return this.Contract.transact(opts, "setInt32" , args); + } + + // setInt64 is a paid mutator transaction binding the contract method 0xe673eb32. + // + // Solidity: function setInt64(int64 i64) returns(int64) + public Transaction setInt64(TransactOpts opts, long i64) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setInt64(i64);args.set(0,arg0); + + return this.Contract.transact(opts, "setInt64" , args); + } + + // setInt8 is a paid mutator transaction binding the contract method 0x9a19a953. + // + // Solidity: function setInt8(int8 i8) returns(int8) + public Transaction setInt8(TransactOpts opts, byte i8) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setInt8(i8);args.set(0,arg0); + + return this.Contract.transact(opts, "setInt8" , args); + } + + // setString is a paid mutator transaction binding the contract method 0x7fcaf666. + // + // Solidity: function setString(string s) returns(string) + public Transaction setString(TransactOpts opts, String s) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setString(s);args.set(0,arg0); + + return this.Contract.transact(opts, "setString" , args); + } + + // setStringArray is a paid mutator transaction binding the contract method 0x7173b695. + // + // Solidity: function setStringArray(string[2] s_a) returns(string[2]) + public Transaction setStringArray(TransactOpts opts, Strings s_a) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setStrings(s_a);args.set(0,arg0); + + return this.Contract.transact(opts, "setStringArray" , args); + } + + // setStringList is a paid mutator transaction binding the contract method 0xc5777961. + // + // Solidity: function setStringList(string[] s_l) returns(string[]) + public Transaction setStringList(TransactOpts opts, Strings s_l) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setStrings(s_l);args.set(0,arg0); + + return this.Contract.transact(opts, "setStringList" , args); + } + + // setUint16 is a paid mutator transaction binding the contract method 0x0477988a. + // + // Solidity: function setUint16(uint16 u16) returns(uint16) + public Transaction setUint16(TransactOpts opts, BigInt u16) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setUint16(u16);args.set(0,arg0); + + return this.Contract.transact(opts, "setUint16" , args); + } + + // setUint256 is a paid mutator transaction binding the contract method 0xd2282dc5. + // + // Solidity: function setUint256(uint256 u256) returns(uint256) + public Transaction setUint256(TransactOpts opts, BigInt u256) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBigInt(u256);args.set(0,arg0); + + return this.Contract.transact(opts, "setUint256" , args); + } + + // setUint256Array is a paid mutator transaction binding the contract method 0x2766a755. + // + // Solidity: function setUint256Array(uint256[2] u256_a) returns(uint256[2]) + public Transaction setUint256Array(TransactOpts opts, BigInts u256_a) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBigInts(u256_a);args.set(0,arg0); + + return this.Contract.transact(opts, "setUint256Array" , args); + } + + // setUint256List is a paid mutator transaction binding the contract method 0xa0709e19. + // + // Solidity: function setUint256List(uint256[] u256_l) returns(uint256[]) + public Transaction setUint256List(TransactOpts opts, BigInts u256_l) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setBigInts(u256_l);args.set(0,arg0); + + return this.Contract.transact(opts, "setUint256List" , args); + } + + // setUint32 is a paid mutator transaction binding the contract method 0x1c9352e2. + // + // Solidity: function setUint32(uint32 u32) returns(uint32) + public Transaction setUint32(TransactOpts opts, BigInt u32) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setUint32(u32);args.set(0,arg0); + + return this.Contract.transact(opts, "setUint32" , args); + } + + // setUint64 is a paid mutator transaction binding the contract method 0x822cba69. + // + // Solidity: function setUint64(uint64 u64) returns(uint64) + public Transaction setUint64(TransactOpts opts, BigInt u64) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setUint64(u64);args.set(0,arg0); + + return this.Contract.transact(opts, "setUint64" , args); + } + + // setUint8 is a paid mutator transaction binding the contract method 0x1774e646. + // + // Solidity: function setUint8(uint8 u8) returns(uint8) + public Transaction setUint8(TransactOpts opts, BigInt u8) throws Exception { + Interfaces args = Geth.newInterfaces(1); + Interface arg0 = Geth.newInterface();arg0.setUint8(u8);args.set(0,arg0); + + return this.Contract.transact(opts, "setUint8" , args); + } + +} + +`, + }, + } + for i, c := range cases { + binding, err := Bind([]string{c.name}, []string{c.abi}, []string{c.bytecode}, "bindtest", LangJava) + if err != nil { + t.Fatalf("test %d: failed to generate binding: %v", i, err) + } + if binding != c.expected { + t.Fatalf("test %d: generated binding mismatch, has %s, want %s", i, binding, c.expected) + } + } +} diff --git a/accounts/abi/bind/template.go b/accounts/abi/bind/template.go index 02d0258e0c..f5a0ca6ef0 100644 --- a/accounts/abi/bind/template.go +++ b/accounts/abi/bind/template.go @@ -439,6 +439,18 @@ var ( } }), nil } + + // Parse{{.Normalized.Name}} is a log parse operation binding the contract event 0x{{printf "%x" .Original.Id}}. + // + // Solidity: {{.Original.String}} + func (_{{$contract.Type}} *{{$contract.Type}}Filterer) Parse{{.Normalized.Name}}(log types.Log) (*{{$contract.Type}}{{.Normalized.Name}}, error) { + event := new({{$contract.Type}}{{.Normalized.Name}}) + if err := _{{$contract.Type}}.contract.UnpackLog(event, "{{.Original.Name}}", log); err != nil { + return nil, err + } + return event, nil + } + {{end}} {{end}} ` @@ -452,95 +464,92 @@ const tmplSourceJava = ` 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}}"; +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(); + {{if .InputBin}} + // BYTECODE is the compiled bytecode used for deploying new contracts. + public final static String BYTECODE = "0x{{.InputBin}}"; - // deploy deploys a new Ethereum contract, binding an instance of {{.Type}} to it. - public static {{.Type}} deploy(TransactOpts auth, EthereumClient client{{range .Constructor.Inputs}}, {{bindtype .Type}} {{.Name}}{{end}}) throws Exception { - 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; - } + // 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}}Interface arg{{$index}} = Geth.newInterface();arg{{$index}}.set{{namedtype (bindtype .Type) .Type}}({{.Name}});args.set({{$index}},arg{{$index}}); {{end}} + return new {{.Type}}(Geth.deployContract(auth, ABI, Geth.decodeFromHex(BYTECODE), client, args)); + } - // Ethereum address where this contract is located at. - public final Address Address; + // Internal constructor used by contract deployment. + private {{.Type}}(BoundContract deployment) { + this.Address = deployment.getAddress(); + this.Deployer = deployment.getDeployer(); + this.Contract = deployment; + } + {{end}} - // Ethereum transaction in which this contract was deployed (if known!). - public final Transaction Deployer; + // Ethereum address where this contract is located at. + public final Address Address; - // Contract instance bound to a blockchain address. - private final BoundContract Contract; + // Ethereum transaction in which this contract was deployed (if known!). + public final Transaction Deployer; - // 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)); - } + // Contract instance bound to a blockchain address. + private final BoundContract Contract; - {{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}} + // 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)); + } - // {{.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); - } + {{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}}Interface arg{{$index}} = Geth.newInterface();arg{{$index}}.set{{namedtype (bindtype .Type) .Type}}({{.Name}});args.set({{$index}},arg{{$index}}); + {{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}}Interface arg{{$index}} = Geth.newInterface();arg{{$index}}.set{{namedtype (bindtype .Type) .Type}}({{.Name}});args.set({{$index}},arg{{$index}}); + {{end}} + return this.Contract.transact(opts, "{{.Original.Name}}" , args); + } + {{end}} +} {{end}} ` diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go index 8f4092971f..87bc29822b 100644 --- a/accounts/abi/bind/util_test.go +++ b/accounts/abi/bind/util_test.go @@ -56,7 +56,8 @@ func TestWaitDeployed(t *testing.T) { backend := backends.NewSimulatedBackend( core.GenesisAlloc{ crypto.PubkeyToAddress(testKey.PublicKey): {Balance: big.NewInt(10000000000)}, - }, 10000000, + }, + 10000000, ) // Create the transaction. diff --git a/cmd/abigen/main.go b/cmd/abigen/main.go index 461c294681..3bc78ebfea 100644 --- a/cmd/abigen/main.go +++ b/cmd/abigen/main.go @@ -69,8 +69,6 @@ func main() { 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) diff --git a/cmd/checkpoint-admin/common.go b/cmd/checkpoint-admin/common.go new file mode 100644 index 0000000000..1f4a34a414 --- /dev/null +++ b/cmd/checkpoint-admin/common.go @@ -0,0 +1,166 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of go-ethereum. +// +// go-ethereum is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// go-ethereum is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with go-ethereum. If not, see . + +package main + +import ( + "io/ioutil" + "strconv" + "strings" + + "github.com/ethereum/go-ethereum/accounts/keystore" + "github.com/ethereum/go-ethereum/cmd/utils" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/console" + "github.com/ethereum/go-ethereum/contracts/checkpointoracle" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/ethereum/go-ethereum/params" + "github.com/ethereum/go-ethereum/rpc" + "gopkg.in/urfave/cli.v1" +) + +// newClient creates a client with specified remote URL. +func newClient(ctx *cli.Context) *ethclient.Client { + client, err := ethclient.Dial(ctx.GlobalString(nodeURLFlag.Name)) + if err != nil { + utils.Fatalf("Failed to connect to Ethereum node: %v", err) + } + return client +} + +// newRPCClient creates a rpc client with specified node URL. +func newRPCClient(url string) *rpc.Client { + client, err := rpc.Dial(url) + if err != nil { + utils.Fatalf("Failed to connect to Ethereum node: %v", err) + } + return client +} + +// getContractAddr retrieves the register contract address through +// rpc request. +func getContractAddr(client *rpc.Client) common.Address { + var addr string + if err := client.Call(&addr, "les_getCheckpointContractAddress"); err != nil { + utils.Fatalf("Failed to fetch checkpoint oracle address: %v", err) + } + return common.HexToAddress(addr) +} + +// getCheckpoint retrieves the specified checkpoint or the latest one +// through rpc request. +func getCheckpoint(ctx *cli.Context, client *rpc.Client) *params.TrustedCheckpoint { + var checkpoint *params.TrustedCheckpoint + + if ctx.GlobalIsSet(indexFlag.Name) { + var result [3]string + index := uint64(ctx.GlobalInt64(indexFlag.Name)) + if err := client.Call(&result, "les_getCheckpoint", index); err != nil { + utils.Fatalf("Failed to get local checkpoint %v, please ensure the les API is exposed", err) + } + checkpoint = ¶ms.TrustedCheckpoint{ + SectionIndex: index, + SectionHead: common.HexToHash(result[0]), + CHTRoot: common.HexToHash(result[1]), + BloomRoot: common.HexToHash(result[2]), + } + } else { + var result [4]string + err := client.Call(&result, "les_latestCheckpoint") + if err != nil { + utils.Fatalf("Failed to get local checkpoint %v, please ensure the les API is exposed", err) + } + index, err := strconv.ParseUint(result[0], 0, 64) + if err != nil { + utils.Fatalf("Failed to parse checkpoint index %v", err) + } + checkpoint = ¶ms.TrustedCheckpoint{ + SectionIndex: index, + SectionHead: common.HexToHash(result[1]), + CHTRoot: common.HexToHash(result[2]), + BloomRoot: common.HexToHash(result[3]), + } + } + return checkpoint +} + +// newContract creates a registrar contract instance with specified +// contract address or the default contracts for mainnet or testnet. +func newContract(client *rpc.Client) (common.Address, *checkpointoracle.CheckpointOracle) { + addr := getContractAddr(client) + if addr == (common.Address{}) { + utils.Fatalf("No specified registrar contract address") + } + contract, err := checkpointoracle.NewCheckpointOracle(addr, ethclient.NewClient(client)) + if err != nil { + utils.Fatalf("Failed to setup registrar contract %s: %v", addr, err) + } + return addr, contract +} + +// promptPassphrase prompts the user for a passphrase. +// Set confirmation to true to require the user to confirm the passphrase. +func promptPassphrase(confirmation bool) string { + passphrase, err := console.Stdin.PromptPassword("Passphrase: ") + if err != nil { + utils.Fatalf("Failed to read passphrase: %v", err) + } + + if confirmation { + confirm, err := console.Stdin.PromptPassword("Repeat passphrase: ") + if err != nil { + utils.Fatalf("Failed to read passphrase confirmation: %v", err) + } + if passphrase != confirm { + utils.Fatalf("Passphrases do not match") + } + } + return passphrase +} + +// getPassphrase obtains a passphrase given by the user. It first checks the +// --password command line flag and ultimately prompts the user for a +// passphrase. +func getPassphrase(ctx *cli.Context) string { + passphraseFile := ctx.String(utils.PasswordFileFlag.Name) + if passphraseFile != "" { + content, err := ioutil.ReadFile(passphraseFile) + if err != nil { + utils.Fatalf("Failed to read passphrase file '%s': %v", + passphraseFile, err) + } + return strings.TrimRight(string(content), "\r\n") + } + // Otherwise prompt the user for the passphrase. + return promptPassphrase(false) +} + +// getKey retrieves the user key through specified key file. +func getKey(ctx *cli.Context) *keystore.Key { + // Read key from file. + keyFile := ctx.GlobalString(keyFileFlag.Name) + keyJson, err := ioutil.ReadFile(keyFile) + if err != nil { + utils.Fatalf("Failed to read the keyfile at '%s': %v", keyFile, err) + } + // Decrypt key with passphrase. + passphrase := getPassphrase(ctx) + key, err := keystore.DecryptKey(keyJson, passphrase) + if err != nil { + utils.Fatalf("Failed to decrypt user key '%s': %v", keyFile, err) + } + return key +} diff --git a/cmd/checkpoint-admin/exec.go b/cmd/checkpoint-admin/exec.go new file mode 100644 index 0000000000..02c4f35cc5 --- /dev/null +++ b/cmd/checkpoint-admin/exec.go @@ -0,0 +1,335 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of go-ethereum. +// +// go-ethereum is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// go-ethereum is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with go-ethereum. If not, see . + +package main + +import ( + "bytes" + "context" + "encoding/binary" + "fmt" + "math/big" + "strings" + "time" + + "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/cmd/utils" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" + "github.com/ethereum/go-ethereum/contracts/checkpointoracle" + "github.com/ethereum/go-ethereum/contracts/checkpointoracle/contract" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/ethclient" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/params" + "github.com/ethereum/go-ethereum/rpc" + "gopkg.in/urfave/cli.v1" +) + +var commandDeploy = cli.Command{ + Name: "deploy", + Usage: "Deploy a new checkpoint oracle contract", + Flags: []cli.Flag{ + nodeURLFlag, + clefURLFlag, + signersFlag, + thresholdFlag, + keyFileFlag, + utils.PasswordFileFlag, + }, + Action: utils.MigrateFlags(deploy), +} + +var commandSign = cli.Command{ + Name: "sign", + Usage: "Sign the checkpoint with the specified key", + Flags: []cli.Flag{ + nodeURLFlag, + clefURLFlag, + indexFlag, + hashFlag, + oracleFlag, + keyFileFlag, + signerFlag, + utils.PasswordFileFlag, + }, + Action: utils.MigrateFlags(sign), +} + +var commandPublish = cli.Command{ + Name: "publish", + Usage: "Publish a checkpoint into the oracle", + Flags: []cli.Flag{ + nodeURLFlag, + indexFlag, + signaturesFlag, + keyFileFlag, + utils.PasswordFileFlag, + }, + Action: utils.MigrateFlags(publish), +} + +// deploy deploys the checkpoint registrar contract. +// +// Note the network where the contract is deployed depends on +// the network where the connected node is located. +func deploy(ctx *cli.Context) error { + // Gather all the addresses that should be permitted to sign + var addrs []common.Address + for _, account := range strings.Split(ctx.String(signersFlag.Name), ",") { + if trimmed := strings.TrimSpace(account); !common.IsHexAddress(trimmed) { + utils.Fatalf("Invalid account in --signers: '%s'", trimmed) + } + addrs = append(addrs, common.HexToAddress(account)) + } + // Retrieve and validate the signing threshold + needed := ctx.Int(thresholdFlag.Name) + if needed == 0 || needed > len(addrs) { + utils.Fatalf("Invalid signature threshold %d", needed) + } + // Print a summary to ensure the user understands what they're signing + fmt.Printf("Deploying new checkpoint oracle:\n\n") + for i, addr := range addrs { + fmt.Printf("Admin %d => %s\n", i+1, addr.Hex()) + } + fmt.Printf("\nSignatures needed to publish: %d\n", needed) + + // Retrieve the private key, create an abigen transactor and an RPC client + transactor := bind.NewKeyedTransactor(getKey(ctx).PrivateKey) + client := newClient(ctx) + + // Deploy the checkpoint oracle + oracle, tx, _, err := contract.DeployCheckpointOracle(transactor, client, addrs, big.NewInt(int64(params.CheckpointFrequency)), + big.NewInt(int64(params.CheckpointProcessConfirmations)), big.NewInt(int64(needed))) + if err != nil { + utils.Fatalf("Failed to deploy checkpoint oracle %v", err) + } + log.Info("Deployed checkpoint oracle", "address", oracle, "tx", tx.Hash().Hex()) + + return nil +} + +// sign creates the signature for specific checkpoint +// with local key. Only contract admins have the permission to +// sign checkpoint. +func sign(ctx *cli.Context) error { + var ( + offline bool // The indicator whether we sign checkpoint by offline. + chash common.Hash + cindex uint64 + address common.Address + + node *rpc.Client + oracle *checkpointoracle.CheckpointOracle + ) + if !ctx.GlobalIsSet(nodeURLFlag.Name) { + // Offline mode signing + offline = true + if !ctx.IsSet(hashFlag.Name) { + utils.Fatalf("Please specify the checkpoint hash (--hash) to sign in offline mode") + } + chash = common.HexToHash(ctx.String(hashFlag.Name)) + + if !ctx.IsSet(indexFlag.Name) { + utils.Fatalf("Please specify checkpoint index (--index) to sign in offline mode") + } + cindex = ctx.Uint64(indexFlag.Name) + + if !ctx.IsSet(oracleFlag.Name) { + utils.Fatalf("Please specify oracle address (--oracle) to sign in offline mode") + } + address = common.HexToAddress(ctx.String(oracleFlag.Name)) + } else { + // Interactive mode signing, retrieve the data from the remote node + node = newRPCClient(ctx.GlobalString(nodeURLFlag.Name)) + + checkpoint := getCheckpoint(ctx, node) + chash = checkpoint.Hash() + cindex = checkpoint.SectionIndex + address = getContractAddr(node) + + // Check the validity of checkpoint + reqCtx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelFn() + + head, err := ethclient.NewClient(node).HeaderByNumber(reqCtx, nil) + if err != nil { + return err + } + num := head.Number.Uint64() + if num < ((cindex+1)*params.CheckpointFrequency + params.CheckpointProcessConfirmations) { + utils.Fatalf("Invalid future checkpoint") + } + _, oracle = newContract(node) + latest, _, h, err := oracle.Contract().GetLatestCheckpoint(nil) + if err != nil { + return err + } + if cindex < latest { + utils.Fatalf("Checkpoint is too old") + } + if cindex == latest && (latest != 0 || h.Uint64() != 0) { + utils.Fatalf("Stale checkpoint, latest registered %d, given %d", latest, cindex) + } + } + var ( + signature string + signer string + ) + // isAdmin checks whether the specified signer is admin. + isAdmin := func(addr common.Address) error { + signers, err := oracle.Contract().GetAllAdmin(nil) + if err != nil { + return err + } + for _, s := range signers { + if s == addr { + return nil + } + } + return fmt.Errorf("signer %v is not the admin", addr.Hex()) + } + // Print to the user the data thy are about to sign + fmt.Printf("Oracle => %s\n", address.Hex()) + fmt.Printf("Index %4d => %s\n", cindex, chash.Hex()) + + switch { + case ctx.GlobalIsSet(clefURLFlag.Name): + // Sign checkpoint in clef mode. + signer = ctx.String(signerFlag.Name) + + if !offline { + if err := isAdmin(common.HexToAddress(signer)); err != nil { + return err + } + } + clef := newRPCClient(ctx.GlobalString(clefURLFlag.Name)) + p := make(map[string]string) + buf := make([]byte, 8) + binary.BigEndian.PutUint64(buf, cindex) + p["address"] = address.Hex() + p["message"] = hexutil.Encode(append(buf, chash.Bytes()...)) + if err := clef.Call(&signature, "account_signData", accounts.MimetypeDataWithValidator, signer, p); err != nil { + utils.Fatalf("Failed to sign checkpoint, err %v", err) + } + case ctx.GlobalIsSet(keyFileFlag.Name): + // Sign checkpoint in raw private key file mode. + key := getKey(ctx) + signer = key.Address.Hex() + + if !offline { + if err := isAdmin(key.Address); err != nil { + return err + } + } + sig, err := crypto.Sign(sighash(cindex, address, chash), key.PrivateKey) + if err != nil { + utils.Fatalf("Failed to sign checkpoint, err %v", err) + } + sig[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper + signature = common.Bytes2Hex(sig) + default: + utils.Fatalf("Please specify clef URL or private key file path to sign checkpoint") + } + fmt.Printf("Signer => %s\n", signer) + fmt.Printf("Signature => %s\n", signature) + return nil +} + +// sighash calculates the hash of the data to sign for the checkpoint oracle. +func sighash(index uint64, oracle common.Address, hash common.Hash) []byte { + buf := make([]byte, 8) + binary.BigEndian.PutUint64(buf, index) + + data := append([]byte{0x19, 0x00}, append(oracle[:], append(buf, hash[:]...)...)...) + return crypto.Keccak256(data) +} + +// ecrecover calculates the sender address from a sighash and signature combo. +func ecrecover(sighash []byte, sig []byte) common.Address { + sig[64] -= 27 + defer func() { sig[64] += 27 }() + + signer, err := crypto.SigToPub(sighash, sig) + if err != nil { + utils.Fatalf("Failed to recover sender from signature %x: %v", sig, err) + } + return crypto.PubkeyToAddress(*signer) +} + +// publish registers the specified checkpoint which generated by connected node +// with a authorised private key. +func publish(ctx *cli.Context) error { + // Print the checkpoint oracle's current status to make sure we're interacting + // with the correct network and contract. + status(ctx) + + // Gather the signatures from the CLI + var sigs [][]byte + for _, sig := range strings.Split(ctx.String(signaturesFlag.Name), ",") { + trimmed := strings.TrimPrefix(strings.TrimSpace(sig), "0x") + if len(trimmed) != 130 { + utils.Fatalf("Invalid signature in --signature: '%s'", trimmed) + } else { + sigs = append(sigs, common.Hex2Bytes(trimmed)) + } + } + // Retrieve the checkpoint we want to sign to sort the signatures + var ( + client = newRPCClient(ctx.GlobalString(nodeURLFlag.Name)) + addr, oracle = newContract(client) + checkpoint = getCheckpoint(ctx, client) + sighash = sighash(checkpoint.SectionIndex, addr, checkpoint.Hash()) + ) + for i := 0; i < len(sigs); i++ { + for j := i + 1; j < len(sigs); j++ { + signerA := ecrecover(sighash, sigs[i]) + signerB := ecrecover(sighash, sigs[j]) + if bytes.Compare(signerA.Bytes(), signerB.Bytes()) > 0 { + sigs[i], sigs[j] = sigs[j], sigs[i] + } + } + } + // Retrieve recent header info to protect replay attack + reqCtx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelFn() + + head, err := ethclient.NewClient(client).HeaderByNumber(reqCtx, nil) + if err != nil { + return err + } + num := head.Number.Uint64() + recent, err := ethclient.NewClient(client).HeaderByNumber(reqCtx, big.NewInt(int64(num-128))) + if err != nil { + return err + } + // Print a summary of the operation that's going to be performed + fmt.Printf("Publishing %d => %s:\n\n", checkpoint.SectionIndex, checkpoint.Hash().Hex()) + for i, sig := range sigs { + fmt.Printf("Signer %d => %s\n", i+1, ecrecover(sighash, sig).Hex()) + } + fmt.Println() + fmt.Printf("Sentry number => %d\nSentry hash => %s\n", recent.Number, recent.Hash().Hex()) + + // Publish the checkpoint into the oracle + tx, err := oracle.RegisterCheckpoint(getKey(ctx).PrivateKey, checkpoint.SectionIndex, checkpoint.Hash().Bytes(), recent.Number, recent.Hash(), sigs) + if err != nil { + utils.Fatalf("Register contract failed %v", err) + } + log.Info("Successfully registered checkpoint", "tx", tx.Hash().Hex()) + return nil +} diff --git a/cmd/checkpoint-admin/main.go b/cmd/checkpoint-admin/main.go new file mode 100644 index 0000000000..39eae6878e --- /dev/null +++ b/cmd/checkpoint-admin/main.go @@ -0,0 +1,124 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of go-ethereum. +// +// go-ethereum is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// go-ethereum is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with go-ethereum. If not, see . + +// checkpoint-admin is a utility that can be used to query checkpoint information +// and register stable checkpoints into an oracle contract. +package main + +import ( + "fmt" + "os" + + "github.com/ethereum/go-ethereum/cmd/utils" + "github.com/ethereum/go-ethereum/common/fdlimit" + "github.com/ethereum/go-ethereum/log" + "gopkg.in/urfave/cli.v1" +) + +const ( + commandHelperTemplate = `{{.Name}}{{if .Subcommands}} command{{end}}{{if .Flags}} [command options]{{end}} [arguments...] +{{if .Description}}{{.Description}} +{{end}}{{if .Subcommands}} +SUBCOMMANDS: + {{range .Subcommands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}} + {{end}}{{end}}{{if .Flags}} +OPTIONS: +{{range $.Flags}}{{"\t"}}{{.}} +{{end}} +{{end}}` +) + +var ( + // Git SHA1 commit hash of the release (set via linker flags) + gitCommit = "" + gitDate = "" +) + +var app *cli.App + +func init() { + app = utils.NewApp(gitCommit, gitDate, "ethereum checkpoint helper tool") + app.Commands = []cli.Command{ + commandStatus, + commandDeploy, + commandSign, + commandPublish, + } + app.Flags = []cli.Flag{ + oracleFlag, + keyFileFlag, + nodeURLFlag, + clefURLFlag, + utils.PasswordFileFlag, + } + cli.CommandHelpTemplate = commandHelperTemplate +} + +// Commonly used command line flags. +var ( + indexFlag = cli.Int64Flag{ + Name: "index", + Usage: "Checkpoint index (query latest from remote node if not specified)", + } + hashFlag = cli.StringFlag{ + Name: "hash", + Usage: "Checkpoint hash (query latest from remote node if not specified)", + } + oracleFlag = cli.StringFlag{ + Name: "oracle", + Usage: "Checkpoint oracle address (query from remote node if not specified)", + } + thresholdFlag = cli.Int64Flag{ + Name: "threshold", + Usage: "Minimal number of signatures required to approve a checkpoint", + } + keyFileFlag = cli.StringFlag{ + Name: "keyfile", + Usage: "The private key file (keyfile signature is not recommended)", + } + nodeURLFlag = cli.StringFlag{ + Name: "rpc", + Value: "http://localhost:8545", + Usage: "The rpc endpoint of a local or remote geth node", + } + clefURLFlag = cli.StringFlag{ + Name: "clef", + Value: "http://localhost:8550", + Usage: "The rpc endpoint of clef", + } + signerFlag = cli.StringFlag{ + Name: "signer", + Usage: "Signer address for clef mode signing", + } + signersFlag = cli.StringFlag{ + Name: "signers", + Usage: "Comma separated accounts of trusted checkpoint signers", + } + signaturesFlag = cli.StringFlag{ + Name: "signatures", + Usage: "Comma separated checkpoint signatures to submit", + } +) + +func main() { + log.Root().SetHandler(log.LvlFilterHandler(log.LvlInfo, log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) + fdlimit.Raise(2048) + + if err := app.Run(os.Args); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/cmd/checkpoint-admin/status.go b/cmd/checkpoint-admin/status.go new file mode 100644 index 0000000000..c134ec090e --- /dev/null +++ b/cmd/checkpoint-admin/status.go @@ -0,0 +1,61 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of go-ethereum. +// +// go-ethereum is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// go-ethereum is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with go-ethereum. If not, see . + +package main + +import ( + "fmt" + + "github.com/ethereum/go-ethereum/cmd/utils" + "github.com/ethereum/go-ethereum/common" + "gopkg.in/urfave/cli.v1" +) + +var commandStatus = cli.Command{ + Name: "status", + Usage: "Fetches the signers and checkpoint status of the oracle contract", + Flags: []cli.Flag{ + nodeURLFlag, + }, + Action: utils.MigrateFlags(status), +} + +// status fetches the admin list of specified registrar contract. +func status(ctx *cli.Context) error { + // Create a wrapper around the checkpoint oracle contract + addr, oracle := newContract(newRPCClient(ctx.GlobalString(nodeURLFlag.Name))) + fmt.Printf("Oracle => %s\n", addr.Hex()) + fmt.Println() + + // Retrieve the list of authorized signers (admins) + admins, err := oracle.Contract().GetAllAdmin(nil) + if err != nil { + return err + } + for i, admin := range admins { + fmt.Printf("Admin %d => %s\n", i+1, admin.Hex()) + } + fmt.Println() + + // Retrieve the latest checkpoint + index, checkpoint, height, err := oracle.Contract().GetLatestCheckpoint(nil) + if err != nil { + return err + } + fmt.Printf("Checkpoint (published at #%d) %d => %s\n", height, index, common.Hash(checkpoint).Hex()) + + return nil +} diff --git a/cmd/geth/main.go b/cmd/geth/main.go index 00809e2e10..7e94da1f5d 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -37,6 +37,7 @@ import ( "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/internal/debug" + "github.com/ethereum/go-ethereum/les" "github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/metrics" "github.com/ethereum/go-ethereum/node" @@ -323,14 +324,33 @@ func startNode(ctx *cli.Context, stack *node.Node) { events := make(chan accounts.WalletEvent, 16) stack.AccountManager().Subscribe(events) - go func() { - // Create a chain state reader for self-derivation - rpcClient, err := stack.Attach() - if err != nil { - utils.Fatalf("Failed to attach to self: %v", err) - } - stateReader := ethclient.NewClient(rpcClient) + // Create a client to interact with local geth node. + rpcClient, err := stack.Attach() + if err != nil { + utils.Fatalf("Failed to attach to self: %v", err) + } + ethClient := ethclient.NewClient(rpcClient) + // Set contract backend for ethereum service if local node + // is serving LES requests. + if ctx.GlobalInt(utils.LightServFlag.Name) > 0 { + var ethService *eth.Ethereum + if err := stack.Service(ðService); err != nil { + utils.Fatalf("Failed to retrieve ethereum service: %v", err) + } + ethService.SetContractBackend(ethClient) + } + // Set contract backend for les service if local node is + // running as a light client. + if ctx.GlobalString(utils.SyncModeFlag.Name) == "light" { + var lesService *les.LightEthereum + if err := stack.Service(&lesService); err != nil { + utils.Fatalf("Failed to retrieve light ethereum service: %v", err) + } + lesService.SetContractBackend(ethClient) + } + + go func() { // Open any wallets already attached for _, wallet := range stack.AccountManager().Wallets() { if err := wallet.Open(""); err != nil { @@ -354,7 +374,7 @@ func startNode(ctx *cli.Context, stack *node.Node) { } derivationPaths = append(derivationPaths, accounts.DefaultBaseDerivationPath) - event.Wallet.SelfDerive(derivationPaths, stateReader) + event.Wallet.SelfDerive(derivationPaths, ethClient) case accounts.WalletDropped: log.Info("Old wallet dropped", "url", event.Wallet.URL()) @@ -383,7 +403,6 @@ func startNode(ctx *cli.Context, stack *node.Node) { "age", common.PrettyAge(timestamp)) stack.Stop() } - } }() } diff --git a/cmd/puppeth/wizard_genesis.go b/cmd/puppeth/wizard_genesis.go index 6aed09f141..499f320f64 100644 --- a/cmd/puppeth/wizard_genesis.go +++ b/cmd/puppeth/wizard_genesis.go @@ -44,12 +44,13 @@ func (w *wizard) makeGenesis() { Difficulty: big.NewInt(524288), Alloc: make(core.GenesisAlloc), Config: ¶ms.ChainConfig{ - HomesteadBlock: big.NewInt(1), - EIP150Block: big.NewInt(2), - EIP155Block: big.NewInt(3), - EIP158Block: big.NewInt(3), - ByzantiumBlock: big.NewInt(4), - ConstantinopleBlock: big.NewInt(5), + HomesteadBlock: big.NewInt(0), + EIP150Block: big.NewInt(0), + EIP155Block: big.NewInt(0), + EIP158Block: big.NewInt(0), + ByzantiumBlock: big.NewInt(0), + ConstantinopleBlock: big.NewInt(0), + PetersburgBlock: big.NewInt(0), }, } // Figure out which consensus engine to choose @@ -191,7 +192,7 @@ func (w *wizard) importGenesis() { func (w *wizard) manageGenesis() { // Figure out whether to modify or export the genesis fmt.Println() - fmt.Println(" 1. Modify existing fork rules") + fmt.Println(" 1. Modify existing configurations") fmt.Println(" 2. Export genesis configurations") fmt.Println(" 3. Remove genesis configuration") @@ -226,7 +227,7 @@ func (w *wizard) manageGenesis() { w.conf.Genesis.Config.PetersburgBlock = w.conf.Genesis.Config.ConstantinopleBlock } fmt.Println() - fmt.Printf("Which block should Constantinople-Fix (remove EIP-1283) come into effect? (default = %v)\n", w.conf.Genesis.Config.PetersburgBlock) + fmt.Printf("Which block should Petersburg come into effect? (default = %v)\n", w.conf.Genesis.Config.PetersburgBlock) w.conf.Genesis.Config.PetersburgBlock = w.readDefaultBigInt(w.conf.Genesis.Config.PetersburgBlock) out, _ := json.MarshalIndent(w.conf.Genesis.Config, "", " ") diff --git a/contracts/checkpointoracle/contract/oracle.go b/contracts/checkpointoracle/contract/oracle.go new file mode 100644 index 0000000000..3bb351792f --- /dev/null +++ b/contracts/checkpointoracle/contract/oracle.go @@ -0,0 +1,415 @@ +// Code generated - DO NOT EDIT. +// This file is a generated binding and any manual changes will be lost. + +package contract + +import ( + "math/big" + "strings" + + ethereum "github.com/ethereum/go-ethereum" + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/event" +) + +// Reference imports to suppress errors if they are not otherwise used. +var ( + _ = big.NewInt + _ = strings.NewReader + _ = ethereum.NotFound + _ = abi.U256 + _ = bind.Bind + _ = common.Big1 + _ = types.BloomLookup + _ = event.NewSubscription +) + +// CheckpointOracleABI is the input ABI used to generate the binding from. +const CheckpointOracleABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"GetAllAdmin\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GetLatestCheckpoint\",\"outputs\":[{\"name\":\"\",\"type\":\"uint64\"},{\"name\":\"\",\"type\":\"bytes32\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_recentNumber\",\"type\":\"uint256\"},{\"name\":\"_recentHash\",\"type\":\"bytes32\"},{\"name\":\"_hash\",\"type\":\"bytes32\"},{\"name\":\"_sectionIndex\",\"type\":\"uint64\"},{\"name\":\"v\",\"type\":\"uint8[]\"},{\"name\":\"r\",\"type\":\"bytes32[]\"},{\"name\":\"s\",\"type\":\"bytes32[]\"}],\"name\":\"SetCheckpoint\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_adminlist\",\"type\":\"address[]\"},{\"name\":\"_sectionSize\",\"type\":\"uint256\"},{\"name\":\"_processConfirms\",\"type\":\"uint256\"},{\"name\":\"_threshold\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"index\",\"type\":\"uint64\"},{\"indexed\":false,\"name\":\"checkpointHash\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"v\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"r\",\"type\":\"bytes32\"},{\"indexed\":false,\"name\":\"s\",\"type\":\"bytes32\"}],\"name\":\"NewCheckpointVote\",\"type\":\"event\"}]" + +// CheckpointOracleBin is the compiled bytecode used for deploying new contracts. +const CheckpointOracleBin = `0x608060405234801561001057600080fd5b506040516108153803806108158339818101604052608081101561003357600080fd5b81019080805164010000000081111561004b57600080fd5b8201602081018481111561005e57600080fd5b815185602082028301116401000000008211171561007b57600080fd5b505060208201516040830151606090930151919450925060005b84518110156101415760016000808784815181106100af57fe5b60200260200101516001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548160ff02191690831515021790555060018582815181106100fc57fe5b60209081029190910181015182546001808201855560009485529290932090920180546001600160a01b0319166001600160a01b039093169290921790915501610095565b50600592909255600655600755506106b78061015e6000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c806345848dfc146100465780634d6a304c1461009e578063d459fc46146100cf575b600080fd5b61004e6102b0565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561008a578181015183820152602001610072565b505050509050019250505060405180910390f35b6100a661034f565b6040805167ffffffffffffffff9094168452602084019290925282820152519081900360600190f35b61029c600480360360e08110156100e557600080fd5b81359160208101359160408201359167ffffffffffffffff6060820135169181019060a08101608082013564010000000081111561012257600080fd5b82018360208201111561013457600080fd5b8035906020019184602083028401116401000000008311171561015657600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092959493602081019350359150506401000000008111156101a657600080fd5b8201836020820111156101b857600080fd5b803590602001918460208302840111640100000000831117156101da57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929594936020810193503591505064010000000081111561022a57600080fd5b82018360208201111561023c57600080fd5b8035906020019184602083028401116401000000008311171561025e57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061036a945050505050565b604080519115158252519081900360200190f35b6060806001805490506040519080825280602002602001820160405280156102e2578160200160208202803883390190505b50905060005b60015481101561034957600181815481106102ff57fe5b9060005260206000200160009054906101000a90046001600160a01b031682828151811061032957fe5b6001600160a01b03909216602092830291909101909101526001016102e8565b50905090565b60025460045460035467ffffffffffffffff90921691909192565b3360009081526020819052604081205460ff1661038657600080fd5b8688401461039357600080fd5b82518451146103a157600080fd5b81518451146103af57600080fd5b6006546005548660010167ffffffffffffffff1602014310156103d457506000610677565b60025467ffffffffffffffff90811690861610156103f457506000610677565b60025467ffffffffffffffff8681169116148015610426575067ffffffffffffffff8516151580610426575060035415155b1561043357506000610677565b8561044057506000610677565b60408051601960f81b6020808301919091526000602183018190523060601b60228401526001600160c01b031960c08a901b166036840152603e8084018b905284518085039091018152605e909301909352815191012090805b86518110156106715760006001848984815181106104b457fe5b60200260200101518985815181106104c857fe5b60200260200101518986815181106104dc57fe5b602002602001015160405160008152602001604052604051808581526020018460ff1660ff1681526020018381526020018281526020019450505050506020604051602081039080840390855afa15801561053b573d6000803e3d6000fd5b505060408051601f1901516001600160a01b03811660009081526020819052919091205490925060ff16905061057057600080fd5b826001600160a01b0316816001600160a01b03161161058e57600080fd5b8092508867ffffffffffffffff167fce51ffa16246bcaf0899f6504f473cd0114f430f566cef71ab7e03d3dde42a418b8a85815181106105ca57fe5b60200260200101518a86815181106105de57fe5b60200260200101518a87815181106105f257fe5b6020026020010151604051808581526020018460ff1660ff16815260200183815260200182815260200194505050505060405180910390a260075482600101106106685750505060048790555050436003556002805467ffffffffffffffff191667ffffffffffffffff86161790556001610677565b5060010161049a565b50600080fd5b97965050505050505056fea265627a7a723058207f6a191ce575596a2f1e907c8c0a01003d16b69fb2c4f432d10878e8c0a99a0264736f6c634300050a0032` + +// DeployCheckpointOracle deploys a new Ethereum contract, binding an instance of CheckpointOracle to it. +func DeployCheckpointOracle(auth *bind.TransactOpts, backend bind.ContractBackend, _adminlist []common.Address, _sectionSize *big.Int, _processConfirms *big.Int, _threshold *big.Int) (common.Address, *types.Transaction, *CheckpointOracle, error) { + parsed, err := abi.JSON(strings.NewReader(CheckpointOracleABI)) + if err != nil { + return common.Address{}, nil, nil, err + } + address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(CheckpointOracleBin), backend, _adminlist, _sectionSize, _processConfirms, _threshold) + if err != nil { + return common.Address{}, nil, nil, err + } + return address, tx, &CheckpointOracle{CheckpointOracleCaller: CheckpointOracleCaller{contract: contract}, CheckpointOracleTransactor: CheckpointOracleTransactor{contract: contract}, CheckpointOracleFilterer: CheckpointOracleFilterer{contract: contract}}, nil +} + +// CheckpointOracle is an auto generated Go binding around an Ethereum contract. +type CheckpointOracle struct { + CheckpointOracleCaller // Read-only binding to the contract + CheckpointOracleTransactor // Write-only binding to the contract + CheckpointOracleFilterer // Log filterer for contract events +} + +// CheckpointOracleCaller is an auto generated read-only Go binding around an Ethereum contract. +type CheckpointOracleCaller struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// CheckpointOracleTransactor is an auto generated write-only Go binding around an Ethereum contract. +type CheckpointOracleTransactor struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// CheckpointOracleFilterer is an auto generated log filtering Go binding around an Ethereum contract events. +type CheckpointOracleFilterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls +} + +// CheckpointOracleSession is an auto generated Go binding around an Ethereum contract, +// with pre-set call and transact options. +type CheckpointOracleSession struct { + Contract *CheckpointOracle // Generic contract binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// CheckpointOracleCallerSession is an auto generated read-only Go binding around an Ethereum contract, +// with pre-set call options. +type CheckpointOracleCallerSession struct { + Contract *CheckpointOracleCaller // Generic contract caller binding to set the session for + CallOpts bind.CallOpts // Call options to use throughout this session +} + +// CheckpointOracleTransactorSession is an auto generated write-only Go binding around an Ethereum contract, +// with pre-set transact options. +type CheckpointOracleTransactorSession struct { + Contract *CheckpointOracleTransactor // Generic contract transactor binding to set the session for + TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session +} + +// CheckpointOracleRaw is an auto generated low-level Go binding around an Ethereum contract. +type CheckpointOracleRaw struct { + Contract *CheckpointOracle // Generic contract binding to access the raw methods on +} + +// CheckpointOracleCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. +type CheckpointOracleCallerRaw struct { + Contract *CheckpointOracleCaller // Generic read-only contract binding to access the raw methods on +} + +// CheckpointOracleTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. +type CheckpointOracleTransactorRaw struct { + Contract *CheckpointOracleTransactor // Generic write-only contract binding to access the raw methods on +} + +// NewCheckpointOracle creates a new instance of CheckpointOracle, bound to a specific deployed contract. +func NewCheckpointOracle(address common.Address, backend bind.ContractBackend) (*CheckpointOracle, error) { + contract, err := bindCheckpointOracle(address, backend, backend, backend) + if err != nil { + return nil, err + } + return &CheckpointOracle{CheckpointOracleCaller: CheckpointOracleCaller{contract: contract}, CheckpointOracleTransactor: CheckpointOracleTransactor{contract: contract}, CheckpointOracleFilterer: CheckpointOracleFilterer{contract: contract}}, nil +} + +// NewCheckpointOracleCaller creates a new read-only instance of CheckpointOracle, bound to a specific deployed contract. +func NewCheckpointOracleCaller(address common.Address, caller bind.ContractCaller) (*CheckpointOracleCaller, error) { + contract, err := bindCheckpointOracle(address, caller, nil, nil) + if err != nil { + return nil, err + } + return &CheckpointOracleCaller{contract: contract}, nil +} + +// NewCheckpointOracleTransactor creates a new write-only instance of CheckpointOracle, bound to a specific deployed contract. +func NewCheckpointOracleTransactor(address common.Address, transactor bind.ContractTransactor) (*CheckpointOracleTransactor, error) { + contract, err := bindCheckpointOracle(address, nil, transactor, nil) + if err != nil { + return nil, err + } + return &CheckpointOracleTransactor{contract: contract}, nil +} + +// NewCheckpointOracleFilterer creates a new log filterer instance of CheckpointOracle, bound to a specific deployed contract. +func NewCheckpointOracleFilterer(address common.Address, filterer bind.ContractFilterer) (*CheckpointOracleFilterer, error) { + contract, err := bindCheckpointOracle(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &CheckpointOracleFilterer{contract: contract}, nil +} + +// bindCheckpointOracle binds a generic wrapper to an already deployed contract. +func bindCheckpointOracle(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { + parsed, err := abi.JSON(strings.NewReader(CheckpointOracleABI)) + if err != nil { + return nil, err + } + return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_CheckpointOracle *CheckpointOracleRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { + return _CheckpointOracle.Contract.CheckpointOracleCaller.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_CheckpointOracle *CheckpointOracleRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _CheckpointOracle.Contract.CheckpointOracleTransactor.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_CheckpointOracle *CheckpointOracleRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _CheckpointOracle.Contract.CheckpointOracleTransactor.contract.Transact(opts, method, params...) +} + +// Call invokes the (constant) contract method with params as input values and +// sets the output to result. The result type might be a single field for simple +// returns, a slice of interfaces for anonymous returns and a struct for named +// returns. +func (_CheckpointOracle *CheckpointOracleCallerRaw) Call(opts *bind.CallOpts, result interface{}, method string, params ...interface{}) error { + return _CheckpointOracle.Contract.contract.Call(opts, result, method, params...) +} + +// Transfer initiates a plain transaction to move funds to the contract, calling +// its default method if one is available. +func (_CheckpointOracle *CheckpointOracleTransactorRaw) Transfer(opts *bind.TransactOpts) (*types.Transaction, error) { + return _CheckpointOracle.Contract.contract.Transfer(opts) +} + +// Transact invokes the (paid) contract method with params as input values. +func (_CheckpointOracle *CheckpointOracleTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (*types.Transaction, error) { + return _CheckpointOracle.Contract.contract.Transact(opts, method, params...) +} + +// GetAllAdmin is a free data retrieval call binding the contract method 0x45848dfc. +// +// Solidity: function GetAllAdmin() constant returns(address[]) +func (_CheckpointOracle *CheckpointOracleCaller) GetAllAdmin(opts *bind.CallOpts) ([]common.Address, error) { + var ( + ret0 = new([]common.Address) + ) + out := ret0 + err := _CheckpointOracle.contract.Call(opts, out, "GetAllAdmin") + return *ret0, err +} + +// GetAllAdmin is a free data retrieval call binding the contract method 0x45848dfc. +// +// Solidity: function GetAllAdmin() constant returns(address[]) +func (_CheckpointOracle *CheckpointOracleSession) GetAllAdmin() ([]common.Address, error) { + return _CheckpointOracle.Contract.GetAllAdmin(&_CheckpointOracle.CallOpts) +} + +// GetAllAdmin is a free data retrieval call binding the contract method 0x45848dfc. +// +// Solidity: function GetAllAdmin() constant returns(address[]) +func (_CheckpointOracle *CheckpointOracleCallerSession) GetAllAdmin() ([]common.Address, error) { + return _CheckpointOracle.Contract.GetAllAdmin(&_CheckpointOracle.CallOpts) +} + +// GetLatestCheckpoint is a free data retrieval call binding the contract method 0x4d6a304c. +// +// Solidity: function GetLatestCheckpoint() constant returns(uint64, bytes32, uint256) +func (_CheckpointOracle *CheckpointOracleCaller) GetLatestCheckpoint(opts *bind.CallOpts) (uint64, [32]byte, *big.Int, error) { + var ( + ret0 = new(uint64) + ret1 = new([32]byte) + ret2 = new(*big.Int) + ) + out := &[]interface{}{ + ret0, + ret1, + ret2, + } + err := _CheckpointOracle.contract.Call(opts, out, "GetLatestCheckpoint") + return *ret0, *ret1, *ret2, err +} + +// GetLatestCheckpoint is a free data retrieval call binding the contract method 0x4d6a304c. +// +// Solidity: function GetLatestCheckpoint() constant returns(uint64, bytes32, uint256) +func (_CheckpointOracle *CheckpointOracleSession) GetLatestCheckpoint() (uint64, [32]byte, *big.Int, error) { + return _CheckpointOracle.Contract.GetLatestCheckpoint(&_CheckpointOracle.CallOpts) +} + +// GetLatestCheckpoint is a free data retrieval call binding the contract method 0x4d6a304c. +// +// Solidity: function GetLatestCheckpoint() constant returns(uint64, bytes32, uint256) +func (_CheckpointOracle *CheckpointOracleCallerSession) GetLatestCheckpoint() (uint64, [32]byte, *big.Int, error) { + return _CheckpointOracle.Contract.GetLatestCheckpoint(&_CheckpointOracle.CallOpts) +} + +// SetCheckpoint is a paid mutator transaction binding the contract method 0xd459fc46. +// +// Solidity: function SetCheckpoint(uint256 _recentNumber, bytes32 _recentHash, bytes32 _hash, uint64 _sectionIndex, uint8[] v, bytes32[] r, bytes32[] s) returns(bool) +func (_CheckpointOracle *CheckpointOracleTransactor) SetCheckpoint(opts *bind.TransactOpts, _recentNumber *big.Int, _recentHash [32]byte, _hash [32]byte, _sectionIndex uint64, v []uint8, r [][32]byte, s [][32]byte) (*types.Transaction, error) { + return _CheckpointOracle.contract.Transact(opts, "SetCheckpoint", _recentNumber, _recentHash, _hash, _sectionIndex, v, r, s) +} + +// SetCheckpoint is a paid mutator transaction binding the contract method 0xd459fc46. +// +// Solidity: function SetCheckpoint(uint256 _recentNumber, bytes32 _recentHash, bytes32 _hash, uint64 _sectionIndex, uint8[] v, bytes32[] r, bytes32[] s) returns(bool) +func (_CheckpointOracle *CheckpointOracleSession) SetCheckpoint(_recentNumber *big.Int, _recentHash [32]byte, _hash [32]byte, _sectionIndex uint64, v []uint8, r [][32]byte, s [][32]byte) (*types.Transaction, error) { + return _CheckpointOracle.Contract.SetCheckpoint(&_CheckpointOracle.TransactOpts, _recentNumber, _recentHash, _hash, _sectionIndex, v, r, s) +} + +// SetCheckpoint is a paid mutator transaction binding the contract method 0xd459fc46. +// +// Solidity: function SetCheckpoint(uint256 _recentNumber, bytes32 _recentHash, bytes32 _hash, uint64 _sectionIndex, uint8[] v, bytes32[] r, bytes32[] s) returns(bool) +func (_CheckpointOracle *CheckpointOracleTransactorSession) SetCheckpoint(_recentNumber *big.Int, _recentHash [32]byte, _hash [32]byte, _sectionIndex uint64, v []uint8, r [][32]byte, s [][32]byte) (*types.Transaction, error) { + return _CheckpointOracle.Contract.SetCheckpoint(&_CheckpointOracle.TransactOpts, _recentNumber, _recentHash, _hash, _sectionIndex, v, r, s) +} + +// CheckpointOracleNewCheckpointVoteIterator is returned from FilterNewCheckpointVote and is used to iterate over the raw logs and unpacked data for NewCheckpointVote events raised by the CheckpointOracle contract. +type CheckpointOracleNewCheckpointVoteIterator struct { + Event *CheckpointOracleNewCheckpointVote // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration +} + +// Next advances the iterator to the subsequent event, returning whether there +// are any more events found. In case of a retrieval or parsing error, false is +// returned and Error() can be queried for the exact failure. +func (it *CheckpointOracleNewCheckpointVoteIterator) Next() bool { + // If the iterator failed, stop iterating + if it.fail != nil { + return false + } + // If the iterator completed, deliver directly whatever's available + if it.done { + select { + case log := <-it.logs: + it.Event = new(CheckpointOracleNewCheckpointVote) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new(CheckpointOracleNewCheckpointVote) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } +} + +// Error returns any retrieval or parsing error occurred during filtering. +func (it *CheckpointOracleNewCheckpointVoteIterator) Error() error { + return it.fail +} + +// Close terminates the iteration process, releasing any pending underlying +// resources. +func (it *CheckpointOracleNewCheckpointVoteIterator) Close() error { + it.sub.Unsubscribe() + return nil +} + +// CheckpointOracleNewCheckpointVote represents a NewCheckpointVote event raised by the CheckpointOracle contract. +type CheckpointOracleNewCheckpointVote struct { + Index uint64 + CheckpointHash [32]byte + V uint8 + R [32]byte + S [32]byte + Raw types.Log // Blockchain specific contextual infos +} + +// FilterNewCheckpointVote is a free log retrieval operation binding the contract event 0xce51ffa16246bcaf0899f6504f473cd0114f430f566cef71ab7e03d3dde42a41. +// +// Solidity: event NewCheckpointVote(uint64 indexed index, bytes32 checkpointHash, uint8 v, bytes32 r, bytes32 s) +func (_CheckpointOracle *CheckpointOracleFilterer) FilterNewCheckpointVote(opts *bind.FilterOpts, index []uint64) (*CheckpointOracleNewCheckpointVoteIterator, error) { + + var indexRule []interface{} + for _, indexItem := range index { + indexRule = append(indexRule, indexItem) + } + + logs, sub, err := _CheckpointOracle.contract.FilterLogs(opts, "NewCheckpointVote", indexRule) + if err != nil { + return nil, err + } + return &CheckpointOracleNewCheckpointVoteIterator{contract: _CheckpointOracle.contract, event: "NewCheckpointVote", logs: logs, sub: sub}, nil +} + +// WatchNewCheckpointVote is a free log subscription operation binding the contract event 0xce51ffa16246bcaf0899f6504f473cd0114f430f566cef71ab7e03d3dde42a41. +// +// Solidity: event NewCheckpointVote(uint64 indexed index, bytes32 checkpointHash, uint8 v, bytes32 r, bytes32 s) +func (_CheckpointOracle *CheckpointOracleFilterer) WatchNewCheckpointVote(opts *bind.WatchOpts, sink chan<- *CheckpointOracleNewCheckpointVote, index []uint64) (event.Subscription, error) { + + var indexRule []interface{} + for _, indexItem := range index { + indexRule = append(indexRule, indexItem) + } + + logs, sub, err := _CheckpointOracle.contract.WatchLogs(opts, "NewCheckpointVote", indexRule) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new(CheckpointOracleNewCheckpointVote) + if err := _CheckpointOracle.contract.UnpackLog(event, "NewCheckpointVote", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// ParseNewCheckpointVote is a log parse operation binding the contract event 0xce51ffa16246bcaf0899f6504f473cd0114f430f566cef71ab7e03d3dde42a41. +// +// Solidity: event NewCheckpointVote(uint64 indexed index, bytes32 checkpointHash, uint8 v, bytes32 r, bytes32 s) +func (_CheckpointOracle *CheckpointOracleFilterer) ParseNewCheckpointVote(log types.Log) (*CheckpointOracleNewCheckpointVote, error) { + event := new(CheckpointOracleNewCheckpointVote) + if err := _CheckpointOracle.contract.UnpackLog(event, "NewCheckpointVote", log); err != nil { + return nil, err + } + return event, nil +} diff --git a/contracts/checkpointoracle/contract/oracle.sol b/contracts/checkpointoracle/contract/oracle.sol new file mode 100644 index 0000000000..0106447273 --- /dev/null +++ b/contracts/checkpointoracle/contract/oracle.sol @@ -0,0 +1,174 @@ +pragma solidity ^0.5.10; + +/** + * @title CheckpointOracle + * @author Gary Rong, Martin Swende + * @dev Implementation of the blockchain checkpoint registrar. + */ +contract CheckpointOracle { + /* + Events + */ + + // NewCheckpointVote is emitted when a new checkpoint proposal receives a vote. + event NewCheckpointVote(uint64 indexed index, bytes32 checkpointHash, uint8 v, bytes32 r, bytes32 s); + + /* + Public Functions + */ + constructor(address[] memory _adminlist, uint _sectionSize, uint _processConfirms, uint _threshold) public { + for (uint i = 0; i < _adminlist.length; i++) { + admins[_adminlist[i]] = true; + adminList.push(_adminlist[i]); + } + sectionSize = _sectionSize; + processConfirms = _processConfirms; + threshold = _threshold; + } + + /** + * @dev Get latest stable checkpoint information. + * @return section index + * @return checkpoint hash + * @return block height associated with checkpoint + */ + function GetLatestCheckpoint() + view + public + returns(uint64, bytes32, uint) { + return (sectionIndex, hash, height); + } + + // SetCheckpoint sets a new checkpoint. It accepts a list of signatures + // @_recentNumber: a recent blocknumber, for replay protection + // @_recentHash : the hash of `_recentNumber` + // @_hash : the hash to set at _sectionIndex + // @_sectionIndex : the section index to set + // @v : the list of v-values + // @r : the list or r-values + // @s : the list of s-values + function SetCheckpoint( + uint _recentNumber, + bytes32 _recentHash, + bytes32 _hash, + uint64 _sectionIndex, + uint8[] memory v, + bytes32[] memory r, + bytes32[] memory s) + public + returns (bool) + { + // Ensure the sender is authorized. + require(admins[msg.sender]); + + // These checks replay protection, so it cannot be replayed on forks, + // accidentally or intentionally + require(blockhash(_recentNumber) == _recentHash); + + // Ensure the batch of signatures are valid. + require(v.length == r.length); + require(v.length == s.length); + + // Filter out "future" checkpoint. + if (block.number < (_sectionIndex+1)*sectionSize+processConfirms) { + return false; + } + // Filter out "old" announcement + if (_sectionIndex < sectionIndex) { + return false; + } + // Filter out "stale" announcement + if (_sectionIndex == sectionIndex && (_sectionIndex != 0 || height != 0)) { + return false; + } + // Filter out "invalid" announcement + if (_hash == ""){ + return false; + } + + // EIP 191 style signatures + // + // Arguments when calculating hash to validate + // 1: byte(0x19) - the initial 0x19 byte + // 2: byte(0) - the version byte (data with intended validator) + // 3: this - the validator address + // -- Application specific data + // 4 : checkpoint section_index(uint64) + // 5 : checkpoint hash (bytes32) + // hash = keccak256(checkpoint_index, section_head, cht_root, bloom_root) + bytes32 signedHash = keccak256(abi.encodePacked(byte(0x19), byte(0), this, _sectionIndex, _hash)); + + address lastVoter = address(0); + + // In order for us not to have to maintain a mapping of who has already + // voted, and we don't want to count a vote twice, the signatures must + // be submitted in strict ordering. + for (uint idx = 0; idx < v.length; idx++){ + address signer = ecrecover(signedHash, v[idx], r[idx], s[idx]); + require(admins[signer]); + require(uint256(signer) > uint256(lastVoter)); + lastVoter = signer; + emit NewCheckpointVote(_sectionIndex, _hash, v[idx], r[idx], s[idx]); + + // Sufficient signatures present, update latest checkpoint. + if (idx+1 >= threshold){ + hash = _hash; + height = block.number; + sectionIndex = _sectionIndex; + return true; + } + } + // We shouldn't wind up here, reverting un-emits the events + revert(); + } + + /** + * @dev Get all admin addresses + * @return address list + */ + function GetAllAdmin() + public + view + returns(address[] memory) + { + address[] memory ret = new address[](adminList.length); + for (uint i = 0; i < adminList.length; i++) { + ret[i] = adminList[i]; + } + return ret; + } + + /* + Fields + */ + // A map of admin users who have the permission to update CHT and bloom Trie root + mapping(address => bool) admins; + + // A list of admin users so that we can obtain all admin users. + address[] adminList; + + // Latest stored section id + uint64 sectionIndex; + + // The block height associated with latest registered checkpoint. + uint height; + + // The hash of latest registered checkpoint. + bytes32 hash; + + // The frequency for creating a checkpoint + // + // The default value should be the same as the checkpoint size(32768) in the ethereum. + uint sectionSize; + + // The number of confirmations needed before a checkpoint can be registered. + // We have to make sure the checkpoint registered will not be invalid due to + // chain reorg. + // + // The default value should be the same as the checkpoint process confirmations(256) + // in the ethereum. + uint processConfirms; + + // The required signatures to finalize a stable checkpoint. + uint threshold; +} diff --git a/contracts/checkpointoracle/oracle.go b/contracts/checkpointoracle/oracle.go new file mode 100644 index 0000000000..702e27d959 --- /dev/null +++ b/contracts/checkpointoracle/oracle.go @@ -0,0 +1,91 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +// Package checkpointoracle is a an on-chain light client checkpoint oracle. +package checkpointoracle + +//go:generate abigen --sol contract/oracle.sol --pkg contract --out contract/oracle.go + +import ( + "crypto/ecdsa" + "errors" + "math/big" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/contracts/checkpointoracle/contract" + "github.com/ethereum/go-ethereum/core/types" +) + +// CheckpointOracle is a Go wrapper around an on-chain light client checkpoint oracle. +type CheckpointOracle struct { + contract *contract.CheckpointOracle +} + +// NewCheckpointOracle binds checkpoint contract and returns a registrar instance. +func NewCheckpointOracle(contractAddr common.Address, backend bind.ContractBackend) (*CheckpointOracle, error) { + c, err := contract.NewCheckpointOracle(contractAddr, backend) + if err != nil { + return nil, err + } + return &CheckpointOracle{contract: c}, nil +} + +// Contract returns the underlying contract instance. +func (oracle *CheckpointOracle) Contract() *contract.CheckpointOracle { + return oracle.contract +} + +// LookupCheckpointEvents searches checkpoint event for specific section in the +// given log batches. +func (oracle *CheckpointOracle) LookupCheckpointEvents(blockLogs [][]*types.Log, section uint64, hash common.Hash) []*contract.CheckpointOracleNewCheckpointVote { + var votes []*contract.CheckpointOracleNewCheckpointVote + + for _, logs := range blockLogs { + for _, log := range logs { + event, err := oracle.contract.ParseNewCheckpointVote(*log) + if err != nil { + continue + } + if event.Index == section && common.Hash(event.CheckpointHash) == hash { + votes = append(votes, event) + } + } + } + return votes +} + +// RegisterCheckpoint registers the checkpoint with a batch of associated signatures +// that are collected off-chain and sorted by lexicographical order. +// +// Notably all signatures given should be transformed to "ethereum style" which transforms +// v from 0/1 to 27/28 according to the yellow paper. +func (oracle *CheckpointOracle) RegisterCheckpoint(key *ecdsa.PrivateKey, index uint64, hash []byte, rnum *big.Int, rhash [32]byte, sigs [][]byte) (*types.Transaction, error) { + var ( + r [][32]byte + s [][32]byte + v []uint8 + ) + for i := 0; i < len(sigs); i++ { + if len(sigs[i]) != 65 { + return nil, errors.New("invalid signature") + } + r = append(r, common.BytesToHash(sigs[i][:32])) + s = append(s, common.BytesToHash(sigs[i][32:64])) + v = append(v, sigs[i][64]) + } + return oracle.contract.SetCheckpoint(bind.NewKeyedTransactor(key), rnum, rhash, common.BytesToHash(hash), index, v, r, s) +} diff --git a/contracts/checkpointoracle/oracle_test.go b/contracts/checkpointoracle/oracle_test.go new file mode 100644 index 0000000000..8c123a3b41 --- /dev/null +++ b/contracts/checkpointoracle/oracle_test.go @@ -0,0 +1,333 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package checkpointoracle + +import ( + "bytes" + "crypto/ecdsa" + "encoding/binary" + "errors" + "math/big" + "reflect" + "sort" + "testing" + "time" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/contracts/checkpointoracle/contract" + "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/params" +) + +var ( + emptyHash = [32]byte{} + + checkpoint0 = params.TrustedCheckpoint{ + SectionIndex: 0, + SectionHead: common.HexToHash("0x7fa3c32f996c2bfb41a1a65b3d8ea3e0a33a1674cde43678ad6f4235e764d17d"), + CHTRoot: common.HexToHash("0x98fc5d3de23a0fecebad236f6655533c157d26a1aedcd0852a514dc1169e6350"), + BloomRoot: common.HexToHash("0x99b5adb52b337fe25e74c1c6d3835b896bd638611b3aebddb2317cce27a3f9fa"), + } + checkpoint1 = params.TrustedCheckpoint{ + SectionIndex: 1, + SectionHead: common.HexToHash("0x2d4dee68102125e59b0cc61b176bd89f0d12b3b91cfaf52ef8c2c82fb920c2d2"), + CHTRoot: common.HexToHash("0x7d428008ece3b4c4ef5439f071930aad0bb75108d381308df73beadcd01ded95"), + BloomRoot: common.HexToHash("0x652571f7736de17e7bbb427ac881474da684c6988a88bf51b10cca9a2ee148f4"), + } + checkpoint2 = params.TrustedCheckpoint{ + SectionIndex: 2, + SectionHead: common.HexToHash("0x61c0de578c0115b1dff8ef39aa600588c7c6ecb8a2f102003d7cf4c4146e9291"), + CHTRoot: common.HexToHash("0x407a08a407a2bc3838b74ca3eb206903c9c8a186ccf5ef14af07794efff1970b"), + BloomRoot: common.HexToHash("0x058b4161f558ce295a92925efc57f34f9210d5a30088d7475c183e0d3e58f5ac"), + } +) + +var ( + // The block frequency for creating checkpoint(only used in test) + sectionSize = big.NewInt(512) + + // The number of confirmations needed to generate a checkpoint(only used in test). + processConfirms = big.NewInt(4) +) + +// validateOperation executes the operation, watches and delivers all events fired by the backend and ensures the +// correctness by assert function. +func validateOperation(t *testing.T, c *contract.CheckpointOracle, backend *backends.SimulatedBackend, operation func(), + assert func(<-chan *contract.CheckpointOracleNewCheckpointVote) error, opName string) { + // Watch all events and deliver them to assert function + var ( + sink = make(chan *contract.CheckpointOracleNewCheckpointVote) + sub, _ = c.WatchNewCheckpointVote(nil, sink, nil) + ) + defer func() { + // Close all subscribers + sub.Unsubscribe() + }() + operation() + + // flush pending block + backend.Commit() + if err := assert(sink); err != nil { + t.Errorf("operation {%s} failed, err %s", opName, err) + } +} + +// validateEvents checks that the correct number of contract events +// fired by contract backend. +func validateEvents(target int, sink interface{}) (bool, []reflect.Value) { + chanval := reflect.ValueOf(sink) + chantyp := chanval.Type() + if chantyp.Kind() != reflect.Chan || chantyp.ChanDir()&reflect.RecvDir == 0 { + return false, nil + } + count := 0 + var recv []reflect.Value + timeout := time.After(1 * time.Second) + cases := []reflect.SelectCase{{Chan: chanval, Dir: reflect.SelectRecv}, {Chan: reflect.ValueOf(timeout), Dir: reflect.SelectRecv}} + for { + chose, v, _ := reflect.Select(cases) + if chose == 1 { + // Not enough event received + return false, nil + } + count += 1 + recv = append(recv, v) + if count == target { + break + } + } + done := time.After(50 * time.Millisecond) + cases = cases[:1] + cases = append(cases, reflect.SelectCase{Chan: reflect.ValueOf(done), Dir: reflect.SelectRecv}) + chose, _, _ := reflect.Select(cases) + // If chose equal 0, it means receiving redundant events. + return chose == 1, recv +} + +func signCheckpoint(addr common.Address, privateKey *ecdsa.PrivateKey, index uint64, hash common.Hash) []byte { + // EIP 191 style signatures + // + // Arguments when calculating hash to validate + // 1: byte(0x19) - the initial 0x19 byte + // 2: byte(0) - the version byte (data with intended validator) + // 3: this - the validator address + // -- Application specific data + // 4 : checkpoint section_index(uint64) + // 5 : checkpoint hash (bytes32) + // hash = keccak256(checkpoint_index, section_head, cht_root, bloom_root) + buf := make([]byte, 8) + binary.BigEndian.PutUint64(buf, index) + data := append([]byte{0x19, 0x00}, append(addr.Bytes(), append(buf, hash.Bytes()...)...)...) + sig, _ := crypto.Sign(crypto.Keccak256(data), privateKey) + sig[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper + return sig +} + +// assertSignature verifies whether the recovered signers are equal with expected. +func assertSignature(addr common.Address, index uint64, hash [32]byte, r, s [32]byte, v uint8, expect common.Address) bool { + buf := make([]byte, 8) + binary.BigEndian.PutUint64(buf, index) + data := append([]byte{0x19, 0x00}, append(addr.Bytes(), append(buf, hash[:]...)...)...) + pubkey, err := crypto.Ecrecover(crypto.Keccak256(data), append(r[:], append(s[:], v-27)...)) + if err != nil { + return false + } + var signer common.Address + copy(signer[:], crypto.Keccak256(pubkey[1:])[12:]) + return bytes.Equal(signer.Bytes(), expect.Bytes()) +} + +type Account struct { + key *ecdsa.PrivateKey + addr common.Address +} +type Accounts []Account + +func (a Accounts) Len() int { return len(a) } +func (a Accounts) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a Accounts) Less(i, j int) bool { return bytes.Compare(a[i].addr.Bytes(), a[j].addr.Bytes()) < 0 } + +func TestCheckpointRegister(t *testing.T) { + // Initialize test accounts + var accounts Accounts + for i := 0; i < 3; i++ { + key, _ := crypto.GenerateKey() + addr := crypto.PubkeyToAddress(key.PublicKey) + accounts = append(accounts, Account{key: key, addr: addr}) + } + sort.Sort(accounts) + + // Deploy registrar contract + transactOpts := bind.NewKeyedTransactor(accounts[0].key) + contractBackend := backends.NewSimulatedBackend(core.GenesisAlloc{accounts[0].addr: {Balance: big.NewInt(1000000000)}, accounts[1].addr: {Balance: big.NewInt(1000000000)}, accounts[2].addr: {Balance: big.NewInt(1000000000)}}, 10000000) + // 3 trusted signers, threshold 2 + contractAddr, _, c, err := contract.DeployCheckpointOracle(transactOpts, contractBackend, []common.Address{accounts[0].addr, accounts[1].addr, accounts[2].addr}, sectionSize, processConfirms, big.NewInt(2)) + if err != nil { + t.Error("Failed to deploy registrar contract", err) + } + contractBackend.Commit() + + // getRecent returns block height and hash of the head parent. + getRecent := func() (*big.Int, common.Hash) { + parentNumber := new(big.Int).Sub(contractBackend.Blockchain().CurrentHeader().Number, big.NewInt(1)) + parentHash := contractBackend.Blockchain().CurrentHeader().ParentHash + return parentNumber, parentHash + } + // collectSig generates specified number signatures. + collectSig := func(index uint64, hash common.Hash, n int, unauthorized *ecdsa.PrivateKey) (v []uint8, r [][32]byte, s [][32]byte) { + for i := 0; i < n; i++ { + sig := signCheckpoint(contractAddr, accounts[i].key, index, hash) + if unauthorized != nil { + sig = signCheckpoint(contractAddr, unauthorized, index, hash) + } + r = append(r, common.BytesToHash(sig[:32])) + s = append(s, common.BytesToHash(sig[32:64])) + v = append(v, sig[64]) + } + return v, r, s + } + // insertEmptyBlocks inserts a batch of empty blocks to blockchain. + insertEmptyBlocks := func(number int) { + for i := 0; i < number; i++ { + contractBackend.Commit() + } + } + // assert checks whether the current contract status is same with + // the expected. + assert := func(index uint64, hash [32]byte, height *big.Int) error { + lindex, lhash, lheight, err := c.GetLatestCheckpoint(nil) + if err != nil { + return err + } + if lindex != index { + return errors.New("latest checkpoint index mismatch") + } + if !bytes.Equal(lhash[:], hash[:]) { + return errors.New("latest checkpoint hash mismatch") + } + if lheight.Cmp(height) != 0 { + return errors.New("latest checkpoint height mismatch") + } + return nil + } + + // Test future checkpoint registration + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + v, r, s := collectSig(0, checkpoint0.Hash(), 2, nil) + c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + return assert(0, emptyHash, big.NewInt(0)) + }, "test future checkpoint registration") + + insertEmptyBlocks(int(sectionSize.Uint64() + processConfirms.Uint64())) + + // Test transaction replay protection + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + v, r, s := collectSig(0, checkpoint0.Hash(), 2, nil) + hash = common.HexToHash("deadbeef") + c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + return assert(0, emptyHash, big.NewInt(0)) + }, "test transaction replay protection") + + // Test unauthorized signature checking + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + u, _ := crypto.GenerateKey() + v, r, s := collectSig(0, checkpoint0.Hash(), 2, u) + c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + return assert(0, emptyHash, big.NewInt(0)) + }, "test unauthorized signature checking") + + // Test un-multi-signature checkpoint registration + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + v, r, s := collectSig(0, checkpoint0.Hash(), 1, nil) + c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + return assert(0, emptyHash, big.NewInt(0)) + }, "test un-multi-signature checkpoint registration") + + // Test valid checkpoint registration + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + v, r, s := collectSig(0, checkpoint0.Hash(), 2, nil) + c.SetCheckpoint(transactOpts, number, hash, checkpoint0.Hash(), 0, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + if valid, recv := validateEvents(2, events); !valid { + return errors.New("receive incorrect number of events") + } else { + for i := 0; i < len(recv); i++ { + event := recv[i].Interface().(*contract.CheckpointOracleNewCheckpointVote) + if !assertSignature(contractAddr, event.Index, event.CheckpointHash, event.R, event.S, event.V, accounts[i].addr) { + return errors.New("recover signer failed") + } + } + } + number, _ := getRecent() + return assert(0, checkpoint0.Hash(), number.Add(number, big.NewInt(1))) + }, "test valid checkpoint registration") + + distance := 3*sectionSize.Uint64() + processConfirms.Uint64() - contractBackend.Blockchain().CurrentHeader().Number.Uint64() + insertEmptyBlocks(int(distance)) + + // Test uncontinuous checkpoint registration + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + v, r, s := collectSig(2, checkpoint2.Hash(), 2, nil) + c.SetCheckpoint(transactOpts, number, hash, checkpoint2.Hash(), 2, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + if valid, recv := validateEvents(2, events); !valid { + return errors.New("receive incorrect number of events") + } else { + for i := 0; i < len(recv); i++ { + event := recv[i].Interface().(*contract.CheckpointOracleNewCheckpointVote) + if !assertSignature(contractAddr, event.Index, event.CheckpointHash, event.R, event.S, event.V, accounts[i].addr) { + return errors.New("recover signer failed") + } + } + } + number, _ := getRecent() + return assert(2, checkpoint2.Hash(), number.Add(number, big.NewInt(1))) + }, "test uncontinuous checkpoint registration") + + // Test old checkpoint registration + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + v, r, s := collectSig(1, checkpoint1.Hash(), 2, nil) + c.SetCheckpoint(transactOpts, number, hash, checkpoint1.Hash(), 1, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + number, _ := getRecent() + return assert(2, checkpoint2.Hash(), number) + }, "test uncontinuous checkpoint registration") + + // Test stale checkpoint registration + validateOperation(t, c, contractBackend, func() { + number, hash := getRecent() + v, r, s := collectSig(2, checkpoint2.Hash(), 2, nil) + c.SetCheckpoint(transactOpts, number, hash, checkpoint2.Hash(), 2, v, r, s) + }, func(events <-chan *contract.CheckpointOracleNewCheckpointVote) error { + number, _ := getRecent() + return assert(2, checkpoint2.Hash(), number.Sub(number, big.NewInt(1))) + }, "test stale checkpoint registration") +} diff --git a/core/chain_indexer.go b/core/chain_indexer.go index 26538260cc..80062714a8 100644 --- a/core/chain_indexer.go +++ b/core/chain_indexer.go @@ -128,12 +128,13 @@ func (c *ChainIndexer) AddCheckpoint(section uint64, shead common.Hash) { c.lock.Lock() defer c.lock.Unlock() + // Short circuit if the given checkpoint is below than local's. + if c.checkpointSections >= section+1 || section < c.storedSections { + return + } c.checkpointSections = section + 1 c.checkpointHead = shead - if section < c.storedSections { - return - } c.setSectionHead(section, shead) c.setValidSections(section + 1) } diff --git a/eth/backend.go b/eth/backend.go index 52ec40f5ae..9f6b5a0026 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -26,6 +26,7 @@ import ( "sync/atomic" "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/consensus" @@ -57,6 +58,7 @@ type LesServer interface { APIs() []rpc.API Protocols() []p2p.Protocol SetBloomBitsIndexer(bbIndexer *core.ChainIndexer) + SetContractBackend(bind.ContractBackend) } // Ethereum implements the Ethereum full node service. @@ -99,6 +101,14 @@ func (s *Ethereum) AddLesServer(ls LesServer) { ls.SetBloomBitsIndexer(s.bloomIndexer) } +// SetClient sets a rpc client which connecting to our local node. +func (s *Ethereum) SetContractBackend(backend bind.ContractBackend) { + // Pass the rpc client to les server if it is enabled. + if s.lesServer != nil { + s.lesServer.SetContractBackend(backend) + } +} + // New creates a new Ethereum object (including the // initialisation of the common Ethereum object) func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { @@ -192,7 +202,11 @@ func New(ctx *node.ServiceContext, config *Config) (*Ethereum, error) { // Permit the downloader to use the trie cache allowance during fast sync cacheLimit := cacheConfig.TrieCleanLimit + cacheConfig.TrieDirtyLimit - if eth.protocolManager, err = NewProtocolManager(chainConfig, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb, cacheLimit, config.Whitelist); err != nil { + checkpoint := config.Checkpoint + if checkpoint == nil { + checkpoint = params.TrustedCheckpoints[genesisHash] + } + if eth.protocolManager, err = NewProtocolManager(chainConfig, checkpoint, config.SyncMode, config.NetworkId, eth.eventMux, eth.txPool, eth.engine, eth.blockchain, chainDb, cacheLimit, config.Whitelist); err != nil { return nil, err } eth.miner = miner.New(eth, &config.Miner, chainConfig, eth.EventMux(), eth.engine, eth.isLocalBlock) @@ -268,6 +282,11 @@ func (s *Ethereum) APIs() []rpc.API { // Append any APIs exposed explicitly by the consensus engine apis = append(apis, s.engine.APIs(s.BlockChain())...) + // Append any APIs exposed explicitly by the les server + if s.lesServer != nil { + apis = append(apis, s.lesServer.APIs()...) + } + // Append all the local APIs and return return append(apis, []rpc.API{ { diff --git a/eth/config.go b/eth/config.go index ccd5674a74..eb61f1d5dc 100644 --- a/eth/config.go +++ b/eth/config.go @@ -149,4 +149,10 @@ type Config struct { // RPCGasCap is the global gas cap for eth-call variants. RPCGasCap *big.Int `toml:",omitempty"` + + // Checkpoint is a hardcoded checkpoint which can be nil. + Checkpoint *params.TrustedCheckpoint + + // CheckpointOracle is the configuration for checkpoint oracle. + CheckpointOracle *params.CheckpointOracleConfig } diff --git a/eth/gen_config.go b/eth/gen_config.go index 178faf7cb7..77b28d025b 100644 --- a/eth/gen_config.go +++ b/eth/gen_config.go @@ -12,6 +12,7 @@ import ( "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/eth/gasprice" "github.com/ethereum/go-ethereum/miner" + "github.com/ethereum/go-ethereum/params" ) // MarshalTOML marshals as TOML. @@ -32,6 +33,7 @@ func (c Config) MarshalTOML() (interface{}, error) { SkipBcVersionCheck bool `toml:"-"` DatabaseHandles int `toml:"-"` DatabaseCache int + DatabaseFreezer string TrieCleanCache int TrieDirtyCache int TrieTimeout time.Duration @@ -45,6 +47,8 @@ func (c Config) MarshalTOML() (interface{}, error) { EVMInterpreter string ConstantinopleOverride *big.Int RPCGasCap *big.Int `toml:",omitempty"` + Checkpoint *params.TrustedCheckpoint + CheckpointOracle *params.CheckpointOracleConfig } var enc Config enc.Genesis = c.Genesis @@ -62,6 +66,7 @@ func (c Config) MarshalTOML() (interface{}, error) { enc.SkipBcVersionCheck = c.SkipBcVersionCheck enc.DatabaseHandles = c.DatabaseHandles enc.DatabaseCache = c.DatabaseCache + enc.DatabaseFreezer = c.DatabaseFreezer enc.TrieCleanCache = c.TrieCleanCache enc.TrieDirtyCache = c.TrieDirtyCache enc.TrieTimeout = c.TrieTimeout @@ -75,6 +80,8 @@ func (c Config) MarshalTOML() (interface{}, error) { enc.EVMInterpreter = c.EVMInterpreter enc.ConstantinopleOverride = c.ConstantinopleOverride enc.RPCGasCap = c.RPCGasCap + enc.Checkpoint = c.Checkpoint + enc.CheckpointOracle = c.CheckpointOracle return &enc, nil } @@ -96,6 +103,7 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { SkipBcVersionCheck *bool `toml:"-"` DatabaseHandles *int `toml:"-"` DatabaseCache *int + DatabaseFreezer *string TrieCleanCache *int TrieDirtyCache *int TrieTimeout *time.Duration @@ -109,6 +117,8 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { EVMInterpreter *string ConstantinopleOverride *big.Int RPCGasCap *big.Int `toml:",omitempty"` + Checkpoint *params.TrustedCheckpoint + CheckpointOracle *params.CheckpointOracleConfig } var dec Config if err := unmarshal(&dec); err != nil { @@ -159,6 +169,9 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { if dec.DatabaseCache != nil { c.DatabaseCache = *dec.DatabaseCache } + if dec.DatabaseFreezer != nil { + c.DatabaseFreezer = *dec.DatabaseFreezer + } if dec.TrieCleanCache != nil { c.TrieCleanCache = *dec.TrieCleanCache } @@ -198,5 +211,11 @@ func (c *Config) UnmarshalTOML(unmarshal func(interface{}) error) error { if dec.RPCGasCap != nil { c.RPCGasCap = dec.RPCGasCap } + if dec.Checkpoint != nil { + c.Checkpoint = dec.Checkpoint + } + if dec.CheckpointOracle != nil { + c.CheckpointOracle = dec.CheckpointOracle + } return nil } diff --git a/eth/handler.go b/eth/handler.go index 58add2eafc..db6901a23a 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -106,7 +106,7 @@ type ProtocolManager struct { // NewProtocolManager returns a new Ethereum sub protocol manager. The Ethereum sub protocol manages peers capable // with the Ethereum network. -func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database, cacheLimit int, whitelist map[uint64]common.Hash) (*ProtocolManager, error) { +func NewProtocolManager(config *params.ChainConfig, checkpoint *params.TrustedCheckpoint, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database, cacheLimit int, whitelist map[uint64]common.Hash) (*ProtocolManager, error) { // Create the protocol manager with the base fields manager := &ProtocolManager{ networkID: networkID, @@ -121,12 +121,31 @@ func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, ne txsyncCh: make(chan *txsync), quitSync: make(chan struct{}), } - // If fast sync was requested and our database is empty, grant it - if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() == 0 { - manager.fastSync = uint32(1) + if mode == downloader.FullSync { + // The database seems empty as the current block is the genesis. Yet the fast + // block is ahead, so fast sync was enabled for this node at a certain point. + // The scenarios where this can happen is + // * if the user manually (or via a bad block) rolled back a fast sync node + // below the sync point. + // * the last fast sync is not finished while user specifies a full sync this + // time. But we don't have any recent state for full sync. + // In these cases however it's safe to reenable fast sync. + fullBlock, fastBlock := blockchain.CurrentBlock(), blockchain.CurrentFastBlock() + if fullBlock.NumberU64() == 0 && fastBlock.NumberU64() > 0 { + manager.fastSync = uint32(1) + log.Warn("Switch sync mode from full sync to fast sync") + } + } else { + if blockchain.CurrentBlock().NumberU64() > 0 { + // Print warning log if database is not empty to run fast sync. + log.Warn("Switch sync mode from fast sync to full sync") + } else { + // If fast sync was requested and our database is empty, grant it + manager.fastSync = uint32(1) + } } // If we have trusted checkpoints, enforce them on the chain - if checkpoint, ok := params.TrustedCheckpoints[blockchain.Genesis().Hash()]; ok { + if checkpoint != nil { manager.checkpointNumber = (checkpoint.SectionIndex+1)*params.CHTFrequency - 1 manager.checkpointHash = checkpoint.SectionHead } diff --git a/eth/handler_test.go b/eth/handler_test.go index 04831e4dc6..445d52afca 100644 --- a/eth/handler_test.go +++ b/eth/handler_test.go @@ -468,27 +468,22 @@ func TestCheckpointChallenge(t *testing.T) { // If checkpointing is not enabled locally, don't challenge and don't drop {downloader.FullSync, false, false, false, false, false}, {downloader.FastSync, false, false, false, false, false}, - {downloader.LightSync, false, false, false, false, false}, // If checkpointing is enabled locally and remote response is empty, only drop during fast sync {downloader.FullSync, true, false, true, false, false}, {downloader.FastSync, true, false, true, false, true}, // Special case, fast sync, unsynced peer - {downloader.LightSync, true, false, true, false, false}, // If checkpointing is enabled locally and remote response mismatches, always drop {downloader.FullSync, true, false, false, false, true}, {downloader.FastSync, true, false, false, false, true}, - {downloader.LightSync, true, false, false, false, true}, // If checkpointing is enabled locally and remote response matches, never drop {downloader.FullSync, true, false, false, true, false}, {downloader.FastSync, true, false, false, true, false}, - {downloader.LightSync, true, false, false, true, false}, // If checkpointing is enabled locally and remote times out, always drop {downloader.FullSync, true, true, false, true, true}, {downloader.FastSync, true, true, false, true, true}, - {downloader.LightSync, true, true, false, true, true}, } for _, tt := range tests { t.Run(fmt.Sprintf("sync %v checkpoint %v timeout %v empty %v match %v", tt.syncmode, tt.checkpoint, tt.timeout, tt.empty, tt.match), func(t *testing.T) { @@ -504,31 +499,30 @@ func testCheckpointChallenge(t *testing.T, syncmode downloader.SyncMode, checkpo // Initialize a chain and generate a fake CHT if checkpointing is enabled var ( - db = rawdb.NewMemoryDatabase() - config = new(params.ChainConfig) - genesis = (&core.Genesis{Config: config}).MustCommit(db) + db = rawdb.NewMemoryDatabase() + config = new(params.ChainConfig) ) + (&core.Genesis{Config: config}).MustCommit(db) // Commit genesis block // If checkpointing is enabled, create and inject a fake CHT and the corresponding // chllenge response. var response *types.Header + var cht *params.TrustedCheckpoint if checkpoint { index := uint64(rand.Intn(500)) number := (index+1)*params.CHTFrequency - 1 response = &types.Header{Number: big.NewInt(int64(number)), Extra: []byte("valid")} - cht := ¶ms.TrustedCheckpoint{ + cht = ¶ms.TrustedCheckpoint{ SectionIndex: index, SectionHead: response.Hash(), } - params.TrustedCheckpoints[genesis.Hash()] = cht - defer delete(params.TrustedCheckpoints, genesis.Hash()) } // Create a checkpoint aware protocol manager blockchain, err := core.NewBlockChain(db, nil, config, ethash.NewFaker(), vm.Config{}, nil) if err != nil { t.Fatalf("failed to create new blockchain: %v", err) } - pm, err := NewProtocolManager(config, syncmode, DefaultConfig.NetworkId, new(event.TypeMux), new(testTxPool), ethash.NewFaker(), blockchain, db, 1, nil) + pm, err := NewProtocolManager(config, cht, syncmode, DefaultConfig.NetworkId, new(event.TypeMux), new(testTxPool), ethash.NewFaker(), blockchain, db, 1, nil) if err != nil { t.Fatalf("failed to start test protocol manager: %v", err) } @@ -615,7 +609,7 @@ func testBroadcastBlock(t *testing.T, totalPeers, broadcastExpected int) { if err != nil { t.Fatalf("failed to create new blockchain: %v", err) } - pm, err := NewProtocolManager(config, downloader.FullSync, DefaultConfig.NetworkId, evmux, new(testTxPool), pow, blockchain, db, 1, nil) + pm, err := NewProtocolManager(config, nil, downloader.FullSync, DefaultConfig.NetworkId, evmux, new(testTxPool), pow, blockchain, db, 1, nil) if err != nil { t.Fatalf("failed to start test protocol manager: %v", err) } diff --git a/eth/helper_test.go b/eth/helper_test.go index 27e7189ed9..1482e99c4e 100644 --- a/eth/helper_test.go +++ b/eth/helper_test.go @@ -66,7 +66,7 @@ func newTestProtocolManager(mode downloader.SyncMode, blocks int, generator func if _, err := blockchain.InsertChain(chain); err != nil { panic(err) } - pm, err := NewProtocolManager(gspec.Config, mode, DefaultConfig.NetworkId, evmux, &testTxPool{added: newtx}, engine, blockchain, db, 1, nil) + pm, err := NewProtocolManager(gspec.Config, nil, mode, DefaultConfig.NetworkId, evmux, &testTxPool{added: newtx}, engine, blockchain, db, 1, nil) if err != nil { return nil, nil, err } diff --git a/eth/sync.go b/eth/sync.go index e303ef8d4e..9e180ee200 100644 --- a/eth/sync.go +++ b/eth/sync.go @@ -179,14 +179,6 @@ func (pm *ProtocolManager) synchronise(peer *peer) { if atomic.LoadUint32(&pm.fastSync) == 1 { // Fast sync was explicitly requested, and explicitly granted mode = downloader.FastSync - } else if currentBlock.NumberU64() == 0 && pm.blockchain.CurrentFastBlock().NumberU64() > 0 { - // The database seems empty as the current block is the genesis. Yet the fast - // block is ahead, so fast sync was enabled for this node at a certain point. - // The only scenario where this can happen is if the user manually (or via a - // bad block) rolled back a fast sync node below the sync point. In this case - // however it's safe to reenable fast sync. - atomic.StoreUint32(&pm.fastSync, 1) - mode = downloader.FastSync } if mode == downloader.FastSync { // Make sure the peer's total difficulty we are synchronizing is higher. diff --git a/internal/web3ext/web3ext.go b/internal/web3ext/web3ext.go index 31c0c57ec0..0abcd5a8a5 100644 --- a/internal/web3ext/web3ext.go +++ b/internal/web3ext/web3ext.go @@ -32,6 +32,7 @@ var Modules = map[string]string{ "shh": ShhJs, "swarmfs": SwarmfsJs, "txpool": TxpoolJs, + "les": LESJs, } const ChequebookJs = ` @@ -760,3 +761,28 @@ web3._extend({ ] }); ` + +const LESJs = ` +web3._extend({ + property: 'les', + methods: + [ + new web3._extend.Method({ + name: 'getCheckpoint', + call: 'les_getCheckpoint', + params: 1 + }), + ], + properties: + [ + new web3._extend.Property({ + name: 'latestCheckpoint', + getter: 'les_latestCheckpoint' + }), + new web3._extend.Property({ + name: 'checkpointContractAddress', + getter: 'les_getCheckpointContractAddress' + }), + ] +}); +` diff --git a/les/api.go b/les/api.go index 3a8d49ca5e..b53512196f 100644 --- a/les/api.go +++ b/les/api.go @@ -34,6 +34,8 @@ var ( ErrMinCap = errors.New("capacity too small") ErrTotalCap = errors.New("total capacity exceeded") ErrUnknownBenchmarkType = errors.New("unknown benchmark type") + ErrNoCheckpoint = errors.New("no local checkpoint provided") + ErrNotActivated = errors.New("checkpoint registrar is not activated") dropCapacityDelay = time.Second // delay applied to decreasing capacity changes ) @@ -470,3 +472,59 @@ func (api *PrivateLightServerAPI) Benchmark(setups []map[string]interface{}, pas } return result, nil } + +// PrivateLightAPI provides an API to access the LES light server or light client. +type PrivateLightAPI struct { + backend *lesCommons + reg *checkpointOracle +} + +// NewPrivateLightAPI creates a new LES service API. +func NewPrivateLightAPI(backend *lesCommons, reg *checkpointOracle) *PrivateLightAPI { + return &PrivateLightAPI{ + backend: backend, + reg: reg, + } +} + +// LatestCheckpoint returns the latest local checkpoint package. +// +// The checkpoint package consists of 4 strings: +// result[0], hex encoded latest section index +// result[1], 32 bytes hex encoded latest section head hash +// result[2], 32 bytes hex encoded latest section canonical hash trie root hash +// result[3], 32 bytes hex encoded latest section bloom trie root hash +func (api *PrivateLightAPI) LatestCheckpoint() ([4]string, error) { + var res [4]string + cp := api.backend.latestLocalCheckpoint() + if cp.Empty() { + return res, ErrNoCheckpoint + } + res[0] = hexutil.EncodeUint64(cp.SectionIndex) + res[1], res[2], res[3] = cp.SectionHead.Hex(), cp.CHTRoot.Hex(), cp.BloomRoot.Hex() + return res, nil +} + +// GetLocalCheckpoint returns the specific local checkpoint package. +// +// The checkpoint package consists of 3 strings: +// result[0], 32 bytes hex encoded latest section head hash +// result[1], 32 bytes hex encoded latest section canonical hash trie root hash +// result[2], 32 bytes hex encoded latest section bloom trie root hash +func (api *PrivateLightAPI) GetCheckpoint(index uint64) ([3]string, error) { + var res [3]string + cp := api.backend.getLocalCheckpoint(index) + if cp.Empty() { + return res, ErrNoCheckpoint + } + res[0], res[1], res[2] = cp.SectionHead.Hex(), cp.CHTRoot.Hex(), cp.BloomRoot.Hex() + return res, nil +} + +// GetCheckpointContractAddress returns the contract contract address in hex format. +func (api *PrivateLightAPI) GetCheckpointContractAddress() (string, error) { + if api.reg == nil { + return "", ErrNotActivated + } + return api.reg.config.Address.Hex(), nil +} diff --git a/les/backend.go b/les/backend.go index ed0f45057f..69aa4e6e23 100644 --- a/les/backend.go +++ b/les/backend.go @@ -23,6 +23,7 @@ import ( "time" "github.com/ethereum/go-ethereum/accounts" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/mclock" @@ -43,14 +44,13 @@ import ( "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/discv5" "github.com/ethereum/go-ethereum/params" - rpc "github.com/ethereum/go-ethereum/rpc" + "github.com/ethereum/go-ethereum/rpc" ) type LightEthereum struct { lesCommons odr *LesOdr - relay *LesTxRelay chainConfig *params.ChainConfig // Channel for shutting down the service shutdownChan chan bool @@ -62,6 +62,7 @@ type LightEthereum struct { serverPool *serverPool reqDist *requestDistributor retriever *retrieveManager + relay *lesTxRelay bloomRequests chan chan *bloombits.Retrieval // Channel receiving bloom data retrieval requests bloomIndexer *core.ChainIndexer @@ -116,16 +117,20 @@ func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) { } leth.serverPool = newServerPool(chainDb, quitSync, &leth.wg, trustedNodes) leth.retriever = newRetrieveManager(peers, leth.reqDist, leth.serverPool) - leth.relay = NewLesTxRelay(peers, leth.retriever) + leth.relay = newLesTxRelay(peers, leth.retriever) leth.odr = NewLesOdr(chainDb, light.DefaultClientIndexerConfig, leth.retriever) leth.chtIndexer = light.NewChtIndexer(chainDb, leth.odr, params.CHTFrequency, params.HelperTrieConfirmations) leth.bloomTrieIndexer = light.NewBloomTrieIndexer(chainDb, leth.odr, params.BloomBitsBlocksClient, params.BloomTrieFrequency) leth.odr.SetIndexers(leth.chtIndexer, leth.bloomTrieIndexer, leth.bloomIndexer) + checkpoint := config.Checkpoint + if checkpoint == nil { + checkpoint = params.TrustedCheckpoints[genesisHash] + } // Note: NewLightChain adds the trusted checkpoint so it needs an ODR with // indexers already set but not started yet - if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine); err != nil { + if leth.blockchain, err = light.NewLightChain(leth.odr, leth.chainConfig, leth.engine, checkpoint); err != nil { return nil, err } // Note: AddChildIndexer starts the update process for the child @@ -141,32 +146,6 @@ func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) { } leth.txPool = light.NewTxPool(leth.chainConfig, leth.blockchain, leth.relay) - - if leth.protocolManager, err = NewProtocolManager( - leth.chainConfig, - light.DefaultClientIndexerConfig, - true, - config.NetworkId, - leth.eventMux, - leth.engine, - leth.peers, - leth.blockchain, - nil, - chainDb, - leth.odr, - leth.relay, - leth.serverPool, - quitSync, - &leth.wg, - config.ULC, - nil); err != nil { - return nil, err - } - - if leth.protocolManager.isULCEnabled() { - log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.protocolManager.ulc.trustedKeys), "minTrustedFraction", leth.protocolManager.ulc.minTrustedFraction) - leth.blockchain.DisableCheckFreq() - } leth.ApiBackend = &LesApiBackend{ctx.ExtRPCEnabled(), leth, nil} gpoParams := config.GPO @@ -174,6 +153,19 @@ func New(ctx *node.ServiceContext, config *eth.Config) (*LightEthereum, error) { gpoParams.Default = config.Miner.GasPrice } leth.ApiBackend.gpo = gasprice.NewOracle(leth.ApiBackend, gpoParams) + + oracle := config.CheckpointOracle + if oracle == nil { + oracle = params.CheckpointOracles[genesisHash] + } + registrar := newCheckpointOracle(oracle, leth.getLocalCheckpoint) + if leth.protocolManager, err = NewProtocolManager(leth.chainConfig, checkpoint, light.DefaultClientIndexerConfig, config.ULC, true, config.NetworkId, leth.eventMux, leth.peers, leth.blockchain, nil, chainDb, leth.odr, leth.serverPool, registrar, quitSync, &leth.wg, nil); err != nil { + return nil, err + } + if leth.protocolManager.isULCEnabled() { + log.Warn("Ultra light client is enabled", "trustedNodes", len(leth.protocolManager.ulc.trustedKeys), "minTrustedFraction", leth.protocolManager.ulc.minTrustedFraction) + leth.blockchain.DisableCheckFreq() + } return leth, nil } @@ -234,6 +226,11 @@ func (s *LightEthereum) APIs() []rpc.API { Version: "1.0", Service: s.netRPCService, Public: true, + }, { + Namespace: "les", + Version: "1.0", + Service: NewPrivateLightAPI(&s.lesCommons, s.protocolManager.reg), + Public: false, }, }...) } @@ -288,3 +285,12 @@ func (s *LightEthereum) Stop() error { return nil } + +// SetClient sets the rpc client and binds the registrar contract. +func (s *LightEthereum) SetContractBackend(backend bind.ContractBackend) { + // Short circuit if registrar is nil + if s.protocolManager.reg == nil { + return + } + s.protocolManager.reg.start(backend) +} diff --git a/les/checkpointoracle.go b/les/checkpointoracle.go new file mode 100644 index 0000000000..4695fbc16c --- /dev/null +++ b/les/checkpointoracle.go @@ -0,0 +1,158 @@ +// Copyright 2019 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package les + +import ( + "encoding/binary" + "sync/atomic" + + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/contracts/checkpointoracle" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/log" + "github.com/ethereum/go-ethereum/params" +) + +// checkpointOracle is responsible for offering the latest stable checkpoint +// generated and announced by the contract admins on-chain. The checkpoint is +// verified by clients locally during the checkpoint syncing. +type checkpointOracle struct { + config *params.CheckpointOracleConfig + contract *checkpointoracle.CheckpointOracle + + // Whether the contract backend is set. + running int32 + + getLocal func(uint64) params.TrustedCheckpoint // Function used to retrieve local checkpoint + syncDoneHook func() // Function used to notify that light syncing has completed. +} + +// newCheckpointOracle returns a checkpoint registrar handler. +func newCheckpointOracle(config *params.CheckpointOracleConfig, getLocal func(uint64) params.TrustedCheckpoint) *checkpointOracle { + if config == nil { + log.Info("Checkpoint registrar is not enabled") + return nil + } + if config.Address == (common.Address{}) || uint64(len(config.Signers)) < config.Threshold { + log.Warn("Invalid checkpoint registrar config") + return nil + } + log.Info("Configured checkpoint registrar", "address", config.Address, "signers", len(config.Signers), "threshold", config.Threshold) + + return &checkpointOracle{ + config: config, + getLocal: getLocal, + } +} + +// start binds the registrar contract and start listening to the +// newCheckpointEvent for the server side. +func (reg *checkpointOracle) start(backend bind.ContractBackend) { + contract, err := checkpointoracle.NewCheckpointOracle(reg.config.Address, backend) + if err != nil { + log.Error("Oracle contract binding failed", "err", err) + return + } + if !atomic.CompareAndSwapInt32(®.running, 0, 1) { + log.Error("Already bound and listening to registrar") + return + } + reg.contract = contract +} + +// isRunning returns an indicator whether the registrar is running. +func (reg *checkpointOracle) isRunning() bool { + return atomic.LoadInt32(®.running) == 1 +} + +// stableCheckpoint returns the stable checkpoint which was generated by local +// indexers and announced by trusted signers. +func (reg *checkpointOracle) stableCheckpoint() (*params.TrustedCheckpoint, uint64) { + // Retrieve the latest checkpoint from the contract, abort if empty + latest, hash, height, err := reg.contract.Contract().GetLatestCheckpoint(nil) + if err != nil || (latest == 0 && hash == [32]byte{}) { + return nil, 0 + } + local := reg.getLocal(latest) + + // The following scenarios may occur: + // + // * local node is out of sync so that it doesn't have the + // checkpoint which registered in the contract. + // * local checkpoint doesn't match with the registered one. + // + // In both cases, server won't send the **stable** checkpoint + // to the client(no worry, client can use hardcoded one instead). + if local.HashEqual(common.Hash(hash)) { + return &local, height.Uint64() + } + return nil, 0 +} + +// verifySigners recovers the signer addresses according to the signature and +// checks whether there are enough approvals to finalize the checkpoint. +func (reg *checkpointOracle) verifySigners(index uint64, hash [32]byte, signatures [][]byte) (bool, []common.Address) { + // Short circuit if the given signatures doesn't reach the threshold. + if len(signatures) < int(reg.config.Threshold) { + return false, nil + } + var ( + signers []common.Address + checked = make(map[common.Address]struct{}) + ) + for i := 0; i < len(signatures); i++ { + if len(signatures[i]) != 65 { + continue + } + // EIP 191 style signatures + // + // Arguments when calculating hash to validate + // 1: byte(0x19) - the initial 0x19 byte + // 2: byte(0) - the version byte (data with intended validator) + // 3: this - the validator address + // -- Application specific data + // 4 : checkpoint section_index (uint64) + // 5 : checkpoint hash (bytes32) + // hash = keccak256(checkpoint_index, section_head, cht_root, bloom_root) + buf := make([]byte, 8) + binary.BigEndian.PutUint64(buf, index) + data := append([]byte{0x19, 0x00}, append(reg.config.Address.Bytes(), append(buf, hash[:]...)...)...) + signatures[i][64] -= 27 // Transform V from 27/28 to 0/1 according to the yellow paper for verification. + pubkey, err := crypto.Ecrecover(crypto.Keccak256(data), signatures[i]) + if err != nil { + return false, nil + } + var signer common.Address + copy(signer[:], crypto.Keccak256(pubkey[1:])[12:]) + if _, exist := checked[signer]; exist { + continue + } + for _, s := range reg.config.Signers { + if s == signer { + signers = append(signers, signer) + checked[signer] = struct{}{} + } + } + } + threshold := reg.config.Threshold + if uint64(len(signers)) < threshold { + log.Warn("Not enough signers to approve checkpoint", "signers", len(signers), "threshold", threshold) + return false, nil + } + return true, signers +} diff --git a/les/commons.go b/les/commons.go index d46479976c..7eaf39c843 100644 --- a/les/commons.go +++ b/les/commons.go @@ -76,24 +76,6 @@ func (c *lesCommons) makeProtocols(versions []uint) []p2p.Protocol { // nodeInfo retrieves some protocol metadata about the running host node. func (c *lesCommons) nodeInfo() interface{} { - var cht params.TrustedCheckpoint - sections, _, _ := c.chtIndexer.Sections() - sections2, _, _ := c.bloomTrieIndexer.Sections() - - if sections2 < sections { - sections = sections2 - } - if sections > 0 { - sectionIndex := sections - 1 - sectionHead := c.bloomTrieIndexer.SectionHead(sectionIndex) - cht = params.TrustedCheckpoint{ - SectionIndex: sectionIndex, - SectionHead: sectionHead, - CHTRoot: light.GetChtRoot(c.chainDb, sectionIndex, sectionHead), - BloomRoot: light.GetBloomTrieRoot(c.chainDb, sectionIndex, sectionHead), - } - } - chain := c.protocolManager.blockchain head := chain.CurrentHeader() hash := head.Hash() @@ -103,6 +85,38 @@ func (c *lesCommons) nodeInfo() interface{} { Genesis: chain.Genesis().Hash(), Config: chain.Config(), Head: chain.CurrentHeader().Hash(), - CHT: cht, + CHT: c.latestLocalCheckpoint(), + } +} + +// latestLocalCheckpoint finds the common stored section index and returns a set of +// post-processed trie roots (CHT and BloomTrie) associated with +// the appropriate section index and head hash as a local checkpoint package. +func (c *lesCommons) latestLocalCheckpoint() params.TrustedCheckpoint { + sections, _, _ := c.chtIndexer.Sections() + sections2, _, _ := c.bloomTrieIndexer.Sections() + // Cap the section index if the two sections are not consistent. + if sections > sections2 { + sections = sections2 + } + if sections == 0 { + // No checkpoint information can be provided. + return params.TrustedCheckpoint{} + } + return c.getLocalCheckpoint(sections - 1) +} + +// getLocalCheckpoint returns a set of post-processed trie roots (CHT and BloomTrie) +// associated with the appropriate head hash by specific section index. +// +// The returned checkpoint is only the checkpoint generated by the local indexers, +// not the stable checkpoint registered in the registrar contract. +func (c *lesCommons) getLocalCheckpoint(index uint64) params.TrustedCheckpoint { + sectionHead := c.chtIndexer.SectionHead(index) + return params.TrustedCheckpoint{ + SectionIndex: index, + SectionHead: sectionHead, + CHTRoot: light.GetChtRoot(c.chainDb, index, sectionHead), + BloomRoot: light.GetBloomTrieRoot(c.chainDb, index, sectionHead), } } diff --git a/les/handler.go b/les/handler.go index c7bd231033..c902db65ac 100644 --- a/les/handler.go +++ b/les/handler.go @@ -27,7 +27,6 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/consensus" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/state" @@ -101,7 +100,7 @@ type ProtocolManager struct { networkId uint64 // The identity of network. txpool txPool - txrelay *LesTxRelay + txrelay *lesTxRelay blockchain BlockChain chainDb ethdb.Database odr *LesOdr @@ -115,6 +114,8 @@ type ProtocolManager struct { fetcher *lightFetcher ulc *ulc peers *peerSet + checkpoint *params.TrustedCheckpoint + reg *checkpointOracle // If reg == nil, it means the checkpoint registrar is not activated // channels for fetcher, syncer, txsyncLoop newPeerCh chan *peer @@ -131,23 +132,7 @@ type ProtocolManager struct { // NewProtocolManager returns a new ethereum sub protocol manager. The Ethereum sub protocol manages peers capable // with the ethereum network. -func NewProtocolManager( - chainConfig *params.ChainConfig, - indexerConfig *light.IndexerConfig, - client bool, - networkId uint64, - mux *event.TypeMux, - engine consensus.Engine, - peers *peerSet, - blockchain BlockChain, - txpool txPool, - chainDb ethdb.Database, - odr *LesOdr, - txrelay *LesTxRelay, - serverPool *serverPool, - quitSync chan struct{}, - wg *sync.WaitGroup, - ulcConfig *eth.ULCConfig, synced func() bool) (*ProtocolManager, error) { +func NewProtocolManager(chainConfig *params.ChainConfig, checkpoint *params.TrustedCheckpoint, indexerConfig *light.IndexerConfig, ulcConfig *eth.ULCConfig, client bool, networkId uint64, mux *event.TypeMux, peers *peerSet, blockchain BlockChain, txpool txPool, chainDb ethdb.Database, odr *LesOdr, serverPool *serverPool, registrar *checkpointOracle, quitSync chan struct{}, wg *sync.WaitGroup, synced func() bool) (*ProtocolManager, error) { // Create the protocol manager with the base fields manager := &ProtocolManager{ client: client, @@ -159,13 +144,14 @@ func NewProtocolManager( odr: odr, networkId: networkId, txpool: txpool, - txrelay: txrelay, serverPool: serverPool, + reg: registrar, peers: peers, newPeerCh: make(chan *peer), quitSync: quitSync, wg: wg, noMorePeers: make(chan struct{}), + checkpoint: checkpoint, synced: synced, } if odr != nil { @@ -182,11 +168,11 @@ func NewProtocolManager( removePeer = func(id string) {} } if client { - var checkpoint uint64 - if cht, ok := params.TrustedCheckpoints[blockchain.Genesis().Hash()]; ok { - checkpoint = (cht.SectionIndex+1)*params.CHTFrequency - 1 + var checkpointNumber uint64 + if checkpoint != nil { + checkpointNumber = (checkpoint.SectionIndex+1)*params.CHTFrequency - 1 } - manager.downloader = downloader.New(checkpoint, chainDb, nil, manager.eventMux, nil, blockchain, removePeer) + manager.downloader = downloader.New(checkpointNumber, chainDb, nil, manager.eventMux, nil, blockchain, removePeer) manager.peers.notify((*downloaderPeerNotify)(manager)) manager.fetcher = newLightFetcher(manager) } diff --git a/les/handler_test.go b/les/handler_test.go index c3608ebddf..e48db216a3 100644 --- a/les/handler_test.go +++ b/les/handler_test.go @@ -159,7 +159,7 @@ func testGetBlockHeaders(t *testing.T, protocol int) { var reqID uint64 for i, tt := range tests { // Collect the headers to expect in the response - headers := []*types.Header{} + var headers []*types.Header for _, hash := range tt.expect { headers = append(headers, bc.GetHeaderByHash(hash)) } @@ -212,8 +212,9 @@ func testGetBlockBodies(t *testing.T, protocol int) { var reqID uint64 for i, tt := range tests { // Collect the hashes to request, and the response to expect - hashes, seen := []common.Hash{}, make(map[int64]bool) - bodies := []*types.Body{} + var hashes []common.Hash + seen := make(map[int64]bool) + var bodies []*types.Body for j := 0; j < tt.random; j++ { for { @@ -258,7 +259,6 @@ func testGetCode(t *testing.T, protocol int) { var codereqs []*CodeReq var codes [][]byte - for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ { header := bc.GetHeaderByNumber(i) req := &CodeReq{ @@ -313,7 +313,8 @@ func testGetReceipt(t *testing.T, protocol int) { bc := server.pm.blockchain.(*core.BlockChain) // Collect the hashes to request, and the response to expect - hashes, receipts := []common.Hash{}, []types.Receipts{} + var receipts []types.Receipts + var hashes []common.Hash for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ { block := bc.GetBlockByNumber(i) @@ -340,11 +341,10 @@ func testGetProofs(t *testing.T, protocol int) { var proofreqs []ProofReq proofsV2 := light.NewNodeSet() - accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr, {}} + accounts := []common.Address{bankAddr, userAddr1, userAddr2, {}} for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ { header := bc.GetHeaderByNumber(i) - root := header.Root - trie, _ := trie.New(root, trie.NewDatabase(server.db)) + trie, _ := trie.New(header.Root, trie.NewDatabase(server.db)) for _, acc := range accounts { req := ProofReq{ @@ -375,7 +375,7 @@ func testGetStaleProof(t *testing.T, protocol int) { check := func(number uint64, wantOK bool) { var ( header = bc.GetHeaderByNumber(number) - account = crypto.Keccak256(testBankAddress.Bytes()) + account = crypto.Keccak256(userAddr1.Bytes()) ) req := &ProofReq{ BHash: header.Hash(), @@ -388,7 +388,7 @@ func testGetStaleProof(t *testing.T, protocol int) { if wantOK { proofsV2 := light.NewNodeSet() t, _ := trie.New(header.Root, trie.NewDatabase(server.db)) - t.Prove(crypto.Keccak256(account), 0, proofsV2) + t.Prove(account, 0, proofsV2) expected = proofsV2.NodeList() } if err := expectResponse(server.tPeer.app, ProofsV2Msg, 42, testBufLimit, expected); err != nil { @@ -494,14 +494,15 @@ func TestGetBloombitsProofs(t *testing.T) { } func TestTransactionStatusLes2(t *testing.T) { - db := rawdb.NewMemoryDatabase() - pm := newTestProtocolManagerMust(t, false, 0, nil, nil, nil, db, nil) - chain := pm.blockchain.(*core.BlockChain) + server, tearDown := newServerEnv(t, 0, 2, nil) + defer tearDown() + + chain := server.pm.blockchain.(*core.BlockChain) config := core.DefaultTxPoolConfig config.Journal = "" txpool := core.NewTxPool(config, params.TestChainConfig, chain) - pm.txpool = txpool - peer, _ := newTestPeer(t, "peer", 2, pm, true, 0) + server.pm.txpool = txpool + peer, _ := newTestPeer(t, "peer", 2, server.pm, true, 0) defer peer.close() var reqID uint64 @@ -509,13 +510,13 @@ func TestTransactionStatusLes2(t *testing.T) { test := func(tx *types.Transaction, send bool, expStatus light.TxStatus) { reqID++ if send { - cost := peer.GetRequestCost(SendTxV2Msg, 1) - sendRequest(peer.app, SendTxV2Msg, reqID, cost, types.Transactions{tx}) + cost := server.tPeer.GetRequestCost(SendTxV2Msg, 1) + sendRequest(server.tPeer.app, SendTxV2Msg, reqID, cost, types.Transactions{tx}) } else { - cost := peer.GetRequestCost(GetTxStatusMsg, 1) - sendRequest(peer.app, GetTxStatusMsg, reqID, cost, []common.Hash{tx.Hash()}) + cost := server.tPeer.GetRequestCost(GetTxStatusMsg, 1) + sendRequest(server.tPeer.app, GetTxStatusMsg, reqID, cost, []common.Hash{tx.Hash()}) } - if err := expectResponse(peer.app, TxStatusMsg, reqID, testBufLimit, []light.TxStatus{expStatus}); err != nil { + if err := expectResponse(server.tPeer.app, TxStatusMsg, reqID, testBufLimit, []light.TxStatus{expStatus}); err != nil { t.Errorf("transaction status mismatch") } } @@ -523,16 +524,16 @@ func TestTransactionStatusLes2(t *testing.T) { signer := types.HomesteadSigner{} // test error status by sending an underpriced transaction - tx0, _ := types.SignTx(types.NewTransaction(0, acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) + tx0, _ := types.SignTx(types.NewTransaction(0, userAddr1, big.NewInt(10000), params.TxGas, nil, nil), signer, bankKey) test(tx0, true, light.TxStatus{Status: core.TxStatusUnknown, Error: core.ErrUnderpriced.Error()}) - tx1, _ := types.SignTx(types.NewTransaction(0, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey) + tx1, _ := types.SignTx(types.NewTransaction(0, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey) test(tx1, false, light.TxStatus{Status: core.TxStatusUnknown}) // query before sending, should be unknown test(tx1, true, light.TxStatus{Status: core.TxStatusPending}) // send valid processable tx, should return pending test(tx1, true, light.TxStatus{Status: core.TxStatusPending}) // adding it again should not return an error - tx2, _ := types.SignTx(types.NewTransaction(1, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey) - tx3, _ := types.SignTx(types.NewTransaction(2, acc1Addr, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, testBankKey) + tx2, _ := types.SignTx(types.NewTransaction(1, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey) + tx3, _ := types.SignTx(types.NewTransaction(2, userAddr1, big.NewInt(10000), params.TxGas, big.NewInt(100000000000), nil), signer, bankKey) // send transactions in the wrong order, tx3 should be queued test(tx3, true, light.TxStatus{Status: core.TxStatusQueued}) test(tx2, true, light.TxStatus{Status: core.TxStatusPending}) @@ -540,7 +541,7 @@ func TestTransactionStatusLes2(t *testing.T) { test(tx3, false, light.TxStatus{Status: core.TxStatusPending}) // generate and add a block with tx1 and tx2 included - gchain, _ := core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), db, 1, func(i int, block *core.BlockGen) { + gchain, _ := core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), server.db, 1, func(i int, block *core.BlockGen) { block.AddTx(tx1) block.AddTx(tx2) }) @@ -559,12 +560,12 @@ func TestTransactionStatusLes2(t *testing.T) { } // check if their status is included now - block1hash := rawdb.ReadCanonicalHash(db, 1) + block1hash := rawdb.ReadCanonicalHash(server.db, 1) test(tx1, false, light.TxStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 0}}) test(tx2, false, light.TxStatus{Status: core.TxStatusIncluded, Lookup: &rawdb.LegacyTxLookupEntry{BlockHash: block1hash, BlockIndex: 1, Index: 1}}) // create a reorg that rolls them back - gchain, _ = core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), db, 2, func(i int, block *core.BlockGen) {}) + gchain, _ = core.GenerateChain(params.TestChainConfig, chain.GetBlockByNumber(0), ethash.NewFaker(), server.db, 2, func(i int, block *core.BlockGen) {}) if _, err := chain.InsertChain(gchain); err != nil { panic(err) } @@ -587,7 +588,7 @@ func TestStopResumeLes3(t *testing.T) { db := rawdb.NewMemoryDatabase() clock := &mclock.Simulated{} testCost := testBufLimit / 10 - pm, err := newTestProtocolManager(false, 0, nil, nil, nil, db, nil, testCost, clock) + pm, _, err := newTestProtocolManager(false, 0, nil, nil, nil, db, nil, testCost, clock) if err != nil { t.Fatalf("Failed to create protocol manager: %v", err) } diff --git a/les/helper_test.go b/les/helper_test.go index dbb0813444..035865b08d 100644 --- a/les/helper_test.go +++ b/les/helper_test.go @@ -20,19 +20,22 @@ package les import ( + "context" "crypto/rand" "math/big" "sync" "testing" "time" + "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/accounts/abi/bind/backends" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/mclock" "github.com/ethereum/go-ethereum/consensus/ethash" + "github.com/ethereum/go-ethereum/contracts/checkpointoracle/contract" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/ethdb" @@ -45,14 +48,14 @@ import ( ) var ( - testBankKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey) - testBankFunds = big.NewInt(1000000000000000000) + bankKey, _ = crypto.GenerateKey() + bankAddr = crypto.PubkeyToAddress(bankKey.PublicKey) + bankFunds = big.NewInt(1000000000000000000) - acc1Key, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") - acc2Key, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee") - acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey) - acc2Addr = crypto.PubkeyToAddress(acc2Key.PublicKey) + userKey1, _ = crypto.GenerateKey() + userKey2, _ = crypto.GenerateKey() + userAddr1 = crypto.PubkeyToAddress(userKey1.PublicKey) + userAddr2 = crypto.PubkeyToAddress(userKey2.PublicKey) testContractCode = common.Hex2Bytes("606060405260cc8060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806360cd2685146041578063c16431b914606b57603f565b005b6055600480803590602001909190505060a9565b6040518082815260200191505060405180910390f35b60886004808035906020019091908035906020019091905050608a565b005b80600060005083606481101560025790900160005b50819055505b5050565b6000600060005082606481101560025790900160005b5054905060c7565b91905056") testContractAddr common.Address @@ -60,8 +63,21 @@ var ( testContractDeployed = uint64(2) testEventEmitterCode = common.Hex2Bytes("60606040523415600e57600080fd5b7f57050ab73f6b9ebdd9f76b8d4997793f48cf956e965ee070551b9ca0bb71584e60405160405180910390a160358060476000396000f3006060604052600080fd00a165627a7a723058203f727efcad8b5811f8cb1fc2620ce5e8c63570d697aef968172de296ea3994140029") - testEventEmitterAddr common.Address + // Checkpoint registrar relative + registrarAddr common.Address + signerKey, _ = crypto.GenerateKey() + signerAddr = crypto.PubkeyToAddress(signerKey.PublicKey) +) + +var ( + // The block frequency for creating checkpoint(only used in test) + sectionSize = big.NewInt(512) + + // The number of confirmations needed to generate a checkpoint(only used in test). + processConfirms = big.NewInt(4) + + // testBufLimit = uint64(1000000) testBufRecharge = uint64(1000) ) @@ -81,102 +97,139 @@ contract test { } */ -func testChainGen(i int, block *core.BlockGen) { - signer := types.HomesteadSigner{} +// prepareTestchain pre-commits specified number customized blocks into chain. +func prepareTestchain(n int, backend *backends.SimulatedBackend) { + var ( + ctx = context.Background() + signer = types.HomesteadSigner{} + ) + for i := 0; i < n; i++ { + switch i { + case 0: + // deploy checkpoint contract + registrarAddr, _, _, _ = contract.DeployCheckpointOracle(bind.NewKeyedTransactor(bankKey), backend, []common.Address{signerAddr}, sectionSize, processConfirms, big.NewInt(1)) + // bankUser transfers some ether to user1 + nonce, _ := backend.PendingNonceAt(ctx, bankAddr) + tx, _ := types.SignTx(types.NewTransaction(nonce, userAddr1, big.NewInt(10000), params.TxGas, nil, nil), signer, bankKey) + backend.SendTransaction(ctx, tx) + case 1: + bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) + userNonce1, _ := backend.PendingNonceAt(ctx, userAddr1) - switch i { - case 0: - // In block 1, the test bank sends account #1 some ether. - tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), signer, testBankKey) - block.AddTx(tx) - case 1: - // In block 2, the test bank sends some more ether to account #1. - // acc1Addr passes it on to account #2. - // acc1Addr creates a test contract. - // acc1Addr creates a test event. - nonce := block.TxNonce(acc1Addr) + // bankUser transfers more ether to user1 + tx1, _ := types.SignTx(types.NewTransaction(bankNonce, userAddr1, big.NewInt(1000), params.TxGas, nil, nil), signer, bankKey) + backend.SendTransaction(ctx, tx1) - tx1, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, testBankKey) - tx2, _ := types.SignTx(types.NewTransaction(nonce, acc2Addr, big.NewInt(1000), params.TxGas, nil, nil), signer, acc1Key) - tx3, _ := types.SignTx(types.NewContractCreation(nonce+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, acc1Key) - testContractAddr = crypto.CreateAddress(acc1Addr, nonce+1) - tx4, _ := types.SignTx(types.NewContractCreation(nonce+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, acc1Key) - testEventEmitterAddr = crypto.CreateAddress(acc1Addr, nonce+2) - block.AddTx(tx1) - block.AddTx(tx2) - block.AddTx(tx3) - block.AddTx(tx4) - case 2: - // Block 3 is empty but was mined by account #2. - block.SetCoinbase(acc2Addr) - block.SetExtra([]byte("yeehaw")) - data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") - tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) - block.AddTx(tx) - case 3: - // Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data). - b2 := block.PrevBlock(1).Header() - b2.Extra = []byte("foo") - block.AddUncle(b2) - b3 := block.PrevBlock(2).Header() - b3.Extra = []byte("foo") - block.AddUncle(b3) - data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") - tx, _ := types.SignTx(types.NewTransaction(block.TxNonce(testBankAddress), testContractAddr, big.NewInt(0), 100000, nil, data), signer, testBankKey) - block.AddTx(tx) + // user1 relays ether to user2 + tx2, _ := types.SignTx(types.NewTransaction(userNonce1, userAddr2, big.NewInt(1000), params.TxGas, nil, nil), signer, userKey1) + backend.SendTransaction(ctx, tx2) + + // user1 deploys a test contract + tx3, _ := types.SignTx(types.NewContractCreation(userNonce1+1, big.NewInt(0), 200000, big.NewInt(0), testContractCode), signer, userKey1) + backend.SendTransaction(ctx, tx3) + testContractAddr = crypto.CreateAddress(userAddr1, userNonce1+1) + + // user1 deploys a event contract + tx4, _ := types.SignTx(types.NewContractCreation(userNonce1+2, big.NewInt(0), 200000, big.NewInt(0), testEventEmitterCode), signer, userKey1) + backend.SendTransaction(ctx, tx4) + case 2: + // bankUser transfer some ether to signer + bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) + tx1, _ := types.SignTx(types.NewTransaction(bankNonce, signerAddr, big.NewInt(1000000000), params.TxGas, nil, nil), signer, bankKey) + backend.SendTransaction(ctx, tx1) + + // invoke test contract + data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001") + tx2, _ := types.SignTx(types.NewTransaction(bankNonce+1, testContractAddr, big.NewInt(0), 100000, nil, data), signer, bankKey) + backend.SendTransaction(ctx, tx2) + case 3: + // invoke test contract + bankNonce, _ := backend.PendingNonceAt(ctx, bankAddr) + data := common.Hex2Bytes("C16431B900000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002") + tx, _ := types.SignTx(types.NewTransaction(bankNonce, testContractAddr, big.NewInt(0), 100000, nil, data), signer, bankKey) + backend.SendTransaction(ctx, tx) + } + backend.Commit() } } // testIndexers creates a set of indexers with specified params for testing purpose. -func testIndexers(db ethdb.Database, odr light.OdrBackend, iConfig *light.IndexerConfig) (*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer) { - chtIndexer := light.NewChtIndexer(db, odr, iConfig.ChtSize, iConfig.ChtConfirms) - bloomIndexer := eth.NewBloomIndexer(db, iConfig.BloomSize, iConfig.BloomConfirms) - bloomTrieIndexer := light.NewBloomTrieIndexer(db, odr, iConfig.BloomSize, iConfig.BloomTrieSize) - bloomIndexer.AddChildIndexer(bloomTrieIndexer) - return chtIndexer, bloomIndexer, bloomTrieIndexer +func testIndexers(db ethdb.Database, odr light.OdrBackend, config *light.IndexerConfig) []*core.ChainIndexer { + var indexers [3]*core.ChainIndexer + indexers[0] = light.NewChtIndexer(db, odr, config.ChtSize, config.ChtConfirms) + indexers[1] = eth.NewBloomIndexer(db, config.BloomSize, config.BloomConfirms) + indexers[2] = light.NewBloomTrieIndexer(db, odr, config.BloomSize, config.BloomTrieSize) + // make bloomTrieIndexer as a child indexer of bloom indexer. + indexers[1].AddChildIndexer(indexers[2]) + return indexers[:] } // newTestProtocolManager creates a new protocol manager for testing purposes, // with the given number of blocks already known, potential notification // channels for different events and relative chain indexers array. -func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *core.BlockGen), odr *LesOdr, peers *peerSet, db ethdb.Database, ulcConfig *eth.ULCConfig, testCost uint64, clock mclock.Clock) (*ProtocolManager, error) { +func newTestProtocolManager(lightSync bool, blocks int, odr *LesOdr, indexers []*core.ChainIndexer, peers *peerSet, db ethdb.Database, ulcConfig *eth.ULCConfig, testCost uint64, clock mclock.Clock) (*ProtocolManager, *backends.SimulatedBackend, error) { var ( evmux = new(event.TypeMux) engine = ethash.NewFaker() gspec = core.Genesis{ - Config: params.TestChainConfig, - Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}}, + Config: params.AllEthashProtocolChanges, + Alloc: core.GenesisAlloc{bankAddr: {Balance: bankFunds}}, } - genesis = gspec.MustCommit(db) - chain BlockChain - pool txPool + pool txPool + chain BlockChain + exitCh = make(chan struct{}) ) + gspec.MustCommit(db) if peers == nil { peers = newPeerSet() } + // create a simulation backend and pre-commit several customized block to the database. + simulation := backends.NewSimulatedBackendWithDatabase(db, gspec.Alloc, 100000000) + prepareTestchain(blocks, simulation) + // initialize empty chain for light client or pre-committed chain for server. if lightSync { - chain, _ = light.NewLightChain(odr, gspec.Config, engine) + chain, _ = light.NewLightChain(odr, gspec.Config, engine, nil) } else { - blockchain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{}, nil) - gchain, _ := core.GenerateChain(gspec.Config, genesis, ethash.NewFaker(), db, blocks, generator) - if _, err := blockchain.InsertChain(gchain); err != nil { - panic(err) - } - chain = blockchain - pool = core.NewTxPool(core.DefaultTxPoolConfig, gspec.Config, blockchain) + chain = simulation.Blockchain() + pool = core.NewTxPool(core.DefaultTxPoolConfig, gspec.Config, simulation.Blockchain()) } + // Create contract registrar indexConfig := light.TestServerIndexerConfig if lightSync { indexConfig = light.TestClientIndexerConfig } - pm, err := NewProtocolManager(gspec.Config, indexConfig, lightSync, NetworkId, evmux, engine, peers, chain, pool, db, odr, nil, nil, make(chan struct{}), new(sync.WaitGroup), ulcConfig, func() bool { return true }) - if err != nil { - return nil, err + config := ¶ms.CheckpointOracleConfig{ + Address: crypto.CreateAddress(bankAddr, 0), + Signers: []common.Address{signerAddr}, + Threshold: 1, } + var reg *checkpointOracle + if indexers != nil { + getLocal := func(index uint64) params.TrustedCheckpoint { + chtIndexer := indexers[0] + sectionHead := chtIndexer.SectionHead(index) + return params.TrustedCheckpoint{ + SectionIndex: index, + SectionHead: sectionHead, + CHTRoot: light.GetChtRoot(db, index, sectionHead), + BloomRoot: light.GetBloomTrieRoot(db, index, sectionHead), + } + } + reg = newCheckpointOracle(config, getLocal) + } + pm, err := NewProtocolManager(gspec.Config, nil, indexConfig, ulcConfig, lightSync, NetworkId, evmux, peers, chain, pool, db, odr, nil, reg, exitCh, new(sync.WaitGroup), func() bool { return true }) + if err != nil { + return nil, nil, err + } + // Registrar initialization could failed if checkpoint contract is not specified. + if pm.reg != nil { + pm.reg.start(simulation) + } + // Set up les server stuff. if !lightSync { - srv := &LesServer{lesCommons: lesCommons{protocolManager: pm}} + srv := &LesServer{lesCommons: lesCommons{protocolManager: pm, chainDb: db}} pm.server = srv pm.servingQueue = newServingQueue(int64(time.Millisecond*10), 1, nil) pm.servingQueue.setThreads(4) @@ -189,19 +242,19 @@ func newTestProtocolManager(lightSync bool, blocks int, generator func(int, *cor srv.fcManager = flowcontrol.NewClientManager(nil, clock) } pm.Start(1000) - return pm, nil + return pm, simulation, nil } // newTestProtocolManagerMust creates a new protocol manager for testing purposes, -// with the given number of blocks already known, potential notification -// channels for different events and relative chain indexers array. In case of an error, the constructor force- -// fails the test. -func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, generator func(int, *core.BlockGen), odr *LesOdr, peers *peerSet, db ethdb.Database, ulcConfig *eth.ULCConfig) *ProtocolManager { - pm, err := newTestProtocolManager(lightSync, blocks, generator, odr, peers, db, ulcConfig, 0, &mclock.System{}) +// with the given number of blocks already known, potential notification channels +// for different events and relative chain indexers array. In case of an error, the +// constructor force-fails the test. +func newTestProtocolManagerMust(t *testing.T, lightSync bool, blocks int, odr *LesOdr, indexers []*core.ChainIndexer, peers *peerSet, db ethdb.Database, ulcConfig *eth.ULCConfig) (*ProtocolManager, *backends.SimulatedBackend) { + pm, backend, err := newTestProtocolManager(lightSync, blocks, odr, indexers, peers, db, ulcConfig, 0, &mclock.System{}) if err != nil { t.Fatalf("Failed to create protocol manager: %v", err) } - return pm + return pm, backend } // testPeer is a simulated peer to allow testing direct network calls. @@ -324,11 +377,13 @@ func (p *testPeer) close() { // TestEntity represents a network entity for testing with necessary auxiliary fields. type TestEntity struct { - db ethdb.Database - rPeer *peer - tPeer *testPeer - peers *peerSet - pm *ProtocolManager + db ethdb.Database + rPeer *peer + tPeer *testPeer + peers *peerSet + pm *ProtocolManager + backend *backends.SimulatedBackend + // Indexers chtIndexer *core.ChainIndexer bloomIndexer *core.ChainIndexer @@ -338,11 +393,12 @@ type TestEntity struct { // newServerEnv creates a server testing environment with a connected test peer for testing purpose. func newServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*core.ChainIndexer, *core.ChainIndexer, *core.ChainIndexer)) (*TestEntity, func()) { db := rawdb.NewMemoryDatabase() - cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig) + indexers := testIndexers(db, nil, light.TestServerIndexerConfig) - pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, nil, db, nil) + pm, b := newTestProtocolManagerMust(t, false, blocks, nil, indexers, nil, db, nil) peer, _ := newTestPeer(t, "peer", protocol, pm, true, 0) + cIndexer, bIndexer, btIndexer := indexers[0], indexers[1], indexers[2] cIndexer.Start(pm.blockchain.(*core.BlockChain)) bIndexer.Start(pm.blockchain.(*core.BlockChain)) @@ -355,6 +411,7 @@ func newServerEnv(t *testing.T, blocks int, protocol int, waitIndexers func(*cor db: db, tPeer: peer, pm: pm, + backend: b, chtIndexer: cIndexer, bloomIndexer: bIndexer, bloomTrieIndexer: btIndexer, @@ -376,12 +433,16 @@ func newClientServerEnv(t *testing.T, blocks int, protocol int, waitIndexers fun rm := newRetrieveManager(lPeers, dist, nil) odr := NewLesOdr(ldb, light.TestClientIndexerConfig, rm) - cIndexer, bIndexer, btIndexer := testIndexers(db, nil, light.TestServerIndexerConfig) - lcIndexer, lbIndexer, lbtIndexer := testIndexers(ldb, odr, light.TestClientIndexerConfig) + indexers := testIndexers(db, nil, light.TestServerIndexerConfig) + lIndexers := testIndexers(ldb, odr, light.TestClientIndexerConfig) + + cIndexer, bIndexer, btIndexer := indexers[0], indexers[1], indexers[2] + lcIndexer, lbIndexer, lbtIndexer := lIndexers[0], lIndexers[1], lIndexers[2] + odr.SetIndexers(lcIndexer, lbtIndexer, lbIndexer) - pm := newTestProtocolManagerMust(t, false, blocks, testChainGen, nil, peers, db, nil) - lpm := newTestProtocolManagerMust(t, true, 0, nil, odr, lPeers, ldb, nil) + pm, b := newTestProtocolManagerMust(t, false, blocks, nil, indexers, peers, db, nil) + lpm, lb := newTestProtocolManagerMust(t, true, 0, odr, lIndexers, lPeers, ldb, nil) startIndexers := func(clientMode bool, pm *ProtocolManager) { if clientMode { @@ -421,6 +482,7 @@ func newClientServerEnv(t *testing.T, blocks int, protocol int, waitIndexers fun pm: pm, rPeer: peer, peers: peers, + backend: b, chtIndexer: cIndexer, bloomIndexer: bIndexer, bloomTrieIndexer: btIndexer, @@ -429,6 +491,7 @@ func newClientServerEnv(t *testing.T, blocks int, protocol int, waitIndexers fun pm: lpm, rPeer: lPeer, peers: lPeers, + backend: lb, chtIndexer: lcIndexer, bloomIndexer: lbIndexer, bloomTrieIndexer: lbtIndexer, diff --git a/les/odr_requests.go b/les/odr_requests.go index 89c6091777..3c4dd7090f 100644 --- a/les/odr_requests.go +++ b/les/odr_requests.go @@ -166,11 +166,13 @@ func (r *ReceiptsRequest) Validate(db ethdb.Database, msg *Msg) error { receipt := receipts[0] // Retrieve our stored header and validate receipt content against it - header := rawdb.ReadHeader(db, r.Hash, r.Number) - if header == nil { + if r.Header == nil { + r.Header = rawdb.ReadHeader(db, r.Hash, r.Number) + } + if r.Header == nil { return errHeaderUnavailable } - if header.ReceiptHash != types.DeriveSha(receipt) { + if r.Header.ReceiptHash != types.DeriveSha(receipt) { return errReceiptHashMismatch } // Validations passed, store and return @@ -323,7 +325,11 @@ func (r *ChtRequest) CanSend(peer *peer) bool { peer.lock.RLock() defer peer.lock.RUnlock() - return peer.headInfo.Number >= r.Config.ChtConfirms && r.ChtNum <= (peer.headInfo.Number-r.Config.ChtConfirms)/r.Config.ChtSize + if r.Untrusted { + return peer.headInfo.Number >= r.BlockNum && peer.id == r.PeerId + } else { + return peer.headInfo.Number >= r.Config.ChtConfirms && r.ChtNum <= (peer.headInfo.Number-r.Config.ChtConfirms)/r.Config.ChtSize + } } // Request sends an ODR request to the LES network (implementation of LesOdrRequest) @@ -364,32 +370,37 @@ func (r *ChtRequest) Validate(db ethdb.Database, msg *Msg) error { } // Verify the CHT - var encNumber [8]byte - binary.BigEndian.PutUint64(encNumber[:], r.BlockNum) - - reads := &readTraceDB{db: nodeSet} - value, _, err := trie.VerifyProof(r.ChtRoot, encNumber[:], reads) - if err != nil { - return fmt.Errorf("merkle proof verification failed: %v", err) - } - if len(reads.reads) != nodeSet.KeyCount() { - return errUselessNodes - } - + // Note: For untrusted CHT request, there is no proof response but + // header data. var node light.ChtNode - if err := rlp.DecodeBytes(value, &node); err != nil { - return err - } - if node.Hash != header.Hash() { - return errCHTHashMismatch - } - if r.BlockNum != header.Number.Uint64() { - return errCHTNumberMismatch + if !r.Untrusted { + var encNumber [8]byte + binary.BigEndian.PutUint64(encNumber[:], r.BlockNum) + + reads := &readTraceDB{db: nodeSet} + value, _, err := trie.VerifyProof(r.ChtRoot, encNumber[:], reads) + if err != nil { + return fmt.Errorf("merkle proof verification failed: %v", err) + } + if len(reads.reads) != nodeSet.KeyCount() { + return errUselessNodes + } + + if err := rlp.DecodeBytes(value, &node); err != nil { + return err + } + if node.Hash != header.Hash() { + return errCHTHashMismatch + } + if r.BlockNum != header.Number.Uint64() { + return errCHTNumberMismatch + } } // Verifications passed, store and return r.Header = header r.Proof = nodeSet - r.Td = node.Td + r.Td = node.Td // For untrusted request, td here is nil, todo improve the les/2 protocol + return nil } diff --git a/les/odr_test.go b/les/odr_test.go index a1d5479563..1e8a5f8b46 100644 --- a/les/odr_test.go +++ b/les/odr_test.go @@ -78,7 +78,7 @@ func TestOdrAccountsLes2(t *testing.T) { testOdr(t, 2, 1, true, odrAccounts) } func odrAccounts(ctx context.Context, db ethdb.Database, config *params.ChainConfig, bc *core.BlockChain, lc *light.LightChain, bhash common.Hash) []byte { dummyAddr := common.HexToAddress("1234567812345678123456781234567812345678") - acc := []common.Address{testBankAddress, acc1Addr, acc2Addr, dummyAddr} + acc := []common.Address{bankAddr, userAddr1, userAddr2, dummyAddr} var ( res []byte @@ -121,7 +121,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai statedb, err := state.New(header.Root, state.NewDatabase(db)) if err == nil { - from := statedb.GetOrNewStateObject(testBankAddress) + from := statedb.GetOrNewStateObject(bankAddr) from.SetBalance(math.MaxBig256) msg := callmsg{types.NewMessage(from.Address(), &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)} @@ -137,8 +137,8 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai } else { header := lc.GetHeaderByHash(bhash) state := light.NewState(ctx, header, lc.Odr()) - state.SetBalance(testBankAddress, math.MaxBig256) - msg := callmsg{types.NewMessage(testBankAddress, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)} + state.SetBalance(bankAddr, math.MaxBig256) + msg := callmsg{types.NewMessage(bankAddr, &testContractAddr, 0, new(big.Int), 100000, new(big.Int), data, false)} context := core.NewEVMContext(msg, header, lc, nil) vmenv := vm.NewEVM(context, state, config, vm.Config{}) gp := new(core.GasPool).AddGas(math.MaxUint64) diff --git a/les/peer.go b/les/peer.go index a615c9b731..76900410e9 100644 --- a/les/peer.go +++ b/les/peer.go @@ -33,6 +33,7 @@ import ( "github.com/ethereum/go-ethereum/les/flowcontrol" "github.com/ethereum/go-ethereum/light" "github.com/ethereum/go-ethereum/p2p" + "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rlp" ) @@ -79,6 +80,10 @@ type peer struct { announceType uint64 + // Checkpoint relative fields + checkpoint params.TrustedCheckpoint + checkpointNumber uint64 + id string headInfo *announceData @@ -575,6 +580,14 @@ func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis send = send.add("flowControl/MRC", costList) p.fcCosts = costList.decode(ProtocolLengths[uint(p.version)]) p.fcParams = server.defParams + + if server.protocolManager != nil && server.protocolManager.reg != nil && server.protocolManager.reg.isRunning() { + cp, height := server.protocolManager.reg.stableCheckpoint() + if cp != nil { + send = send.add("checkpoint/value", cp) + send = send.add("checkpoint/registerHeight", height) + } + } } else { //on client node p.announceType = announceTypeSimple @@ -658,20 +671,24 @@ func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis return errResp(ErrUselessPeer, "peer cannot serve requests") } - var params flowcontrol.ServerParams - if err := recv.get("flowControl/BL", ¶ms.BufLimit); err != nil { + var sParams flowcontrol.ServerParams + if err := recv.get("flowControl/BL", &sParams.BufLimit); err != nil { return err } - if err := recv.get("flowControl/MRR", ¶ms.MinRecharge); err != nil { + if err := recv.get("flowControl/MRR", &sParams.MinRecharge); err != nil { return err } var MRC RequestCostList if err := recv.get("flowControl/MRC", &MRC); err != nil { return err } - p.fcParams = params - p.fcServer = flowcontrol.NewServerNode(params, &mclock.System{}) + p.fcParams = sParams + p.fcServer = flowcontrol.NewServerNode(sParams, &mclock.System{}) p.fcCosts = MRC.decode(ProtocolLengths[uint(p.version)]) + + recv.get("checkpoint/value", &p.checkpoint) + recv.get("checkpoint/registerHeight", &p.checkpointNumber) + if !p.isOnlyAnnounce { for msgCode := range reqAvgTimeCost { if p.fcCosts[msgCode] == nil { diff --git a/les/request_test.go b/les/request_test.go index e0d00d18c5..42a63c351e 100644 --- a/les/request_test.go +++ b/les/request_test.go @@ -28,7 +28,7 @@ import ( "github.com/ethereum/go-ethereum/light" ) -var testBankSecureTrieKey = secAddr(testBankAddress) +var testBankSecureTrieKey = secAddr(bankAddr) func secAddr(addr common.Address) []byte { return crypto.Keccak256(addr[:]) diff --git a/les/server.go b/les/server.go index fbdf6cf1ee..08d9734165 100644 --- a/les/server.go +++ b/les/server.go @@ -21,6 +21,7 @@ import ( "sync" "time" + "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/mclock" "github.com/ethereum/go-ethereum/core" @@ -72,68 +73,38 @@ type LesServer struct { priorityClientPool *priorityClientPool } -func NewLesServer(eth *eth.Ethereum, config *eth.Config) (*LesServer, error) { +func NewLesServer(e *eth.Ethereum, config *eth.Config) (*LesServer, error) { var csvLogger *csvlogger.Logger if logFileName != "" { csvLogger = csvlogger.NewLogger(logFileName, time.Second*10, "event, peerId") } - - quitSync := make(chan struct{}) - pm, err := NewProtocolManager( - eth.BlockChain().Config(), - light.DefaultServerIndexerConfig, - false, - config.NetworkId, - eth.EventMux(), - eth.Engine(), - newPeerSet(), - eth.BlockChain(), - eth.TxPool(), - eth.ChainDb(), - nil, - nil, - nil, - quitSync, - new(sync.WaitGroup), - config.ULC, - eth.Synced) - if err != nil { - return nil, err - } - if logProtocolHandler { - pm.logger = csvLogger - } requestLogger := csvLogger if !logRequestServing { requestLogger = nil } - pm.servingQueue = newServingQueue(int64(time.Millisecond*10), float64(config.LightServ)/100, requestLogger) - lesTopics := make([]discv5.Topic, len(AdvertiseProtocolVersions)) for i, pv := range AdvertiseProtocolVersions { - lesTopics[i] = lesTopic(eth.BlockChain().Genesis().Hash(), pv) + lesTopics[i] = lesTopic(e.BlockChain().Genesis().Hash(), pv) } - + quitSync := make(chan struct{}) srv := &LesServer{ lesCommons: lesCommons{ config: config, - chainDb: eth.ChainDb(), iConfig: light.DefaultServerIndexerConfig, - chtIndexer: light.NewChtIndexer(eth.ChainDb(), nil, params.CHTFrequency, params.HelperTrieProcessConfirmations), - bloomTrieIndexer: light.NewBloomTrieIndexer(eth.ChainDb(), nil, params.BloomBitsBlocks, params.BloomTrieFrequency), - protocolManager: pm, + chainDb: e.ChainDb(), + chtIndexer: light.NewChtIndexer(e.ChainDb(), nil, params.CHTFrequency, params.HelperTrieProcessConfirmations), + bloomTrieIndexer: light.NewBloomTrieIndexer(e.ChainDb(), nil, params.BloomBitsBlocks, params.BloomTrieFrequency), }, - archiveMode: eth.ArchiveMode(), + archiveMode: e.ArchiveMode(), quitSync: quitSync, lesTopics: lesTopics, onlyAnnounce: config.OnlyAnnounce, csvLogger: csvLogger, logTotalCap: requestLogger.NewChannel("totalCapacity", 0.01), } - srv.costTracker, srv.minCapacity = newCostTracker(eth.ChainDb(), config, requestLogger) + srv.costTracker, srv.minCapacity = newCostTracker(e.ChainDb(), config, requestLogger) logger := log.New() - pm.server = srv srv.thcNormal = config.LightServ * 4 / 100 if srv.thcNormal < 4 { srv.thcNormal = 4 @@ -141,22 +112,31 @@ func NewLesServer(eth *eth.Ethereum, config *eth.Config) (*LesServer, error) { srv.thcBlockProcessing = config.LightServ/100 + 1 srv.fcManager = flowcontrol.NewClientManager(nil, &mclock.System{}) - chtSectionCount, _, _ := srv.chtIndexer.Sections() - if chtSectionCount != 0 { - chtLastSection := chtSectionCount - 1 - chtSectionHead := srv.chtIndexer.SectionHead(chtLastSection) - chtRoot := light.GetChtRoot(pm.chainDb, chtLastSection, chtSectionHead) - logger.Info("Loaded CHT", "section", chtLastSection, "head", chtSectionHead, "root", chtRoot) - } - bloomTrieSectionCount, _, _ := srv.bloomTrieIndexer.Sections() - if bloomTrieSectionCount != 0 { - bloomTrieLastSection := bloomTrieSectionCount - 1 - bloomTrieSectionHead := srv.bloomTrieIndexer.SectionHead(bloomTrieLastSection) - bloomTrieRoot := light.GetBloomTrieRoot(pm.chainDb, bloomTrieLastSection, bloomTrieSectionHead) - logger.Info("Loaded bloom trie", "section", bloomTrieLastSection, "head", bloomTrieSectionHead, "root", bloomTrieRoot) + checkpoint := srv.latestLocalCheckpoint() + if !checkpoint.Empty() { + logger.Info("Loaded latest checkpoint", "section", checkpoint.SectionIndex, "head", checkpoint.SectionHead, + "chtroot", checkpoint.CHTRoot, "bloomroot", checkpoint.BloomRoot) } - srv.chtIndexer.Start(eth.BlockChain()) + srv.chtIndexer.Start(e.BlockChain()) + + oracle := config.CheckpointOracle + if oracle == nil { + oracle = params.CheckpointOracles[e.BlockChain().Genesis().Hash()] + } + registrar := newCheckpointOracle(oracle, srv.getLocalCheckpoint) + // TODO(rjl493456442) Checkpoint is useless for les server, separate handler for client and server. + pm, err := NewProtocolManager(e.BlockChain().Config(), nil, light.DefaultServerIndexerConfig, config.ULC, false, config.NetworkId, e.EventMux(), newPeerSet(), e.BlockChain(), e.TxPool(), e.ChainDb(), nil, nil, registrar, quitSync, new(sync.WaitGroup), e.Synced) + if err != nil { + return nil, err + } + srv.protocolManager = pm + if logProtocolHandler { + pm.logger = csvLogger + } + pm.servingQueue = newServingQueue(int64(time.Millisecond*10), float64(config.LightServ)/100, requestLogger) + pm.server = srv + return srv, nil } @@ -168,6 +148,12 @@ func (s *LesServer) APIs() []rpc.API { Service: NewPrivateLightServerAPI(s), Public: false, }, + { + Namespace: "les", + Version: "1.0", + Service: NewPrivateLightAPI(&s.lesCommons, s.protocolManager.reg), + Public: false, + }, } } @@ -292,6 +278,13 @@ func (s *LesServer) SetBloomBitsIndexer(bloomIndexer *core.ChainIndexer) { bloomIndexer.AddChildIndexer(s.bloomTrieIndexer) } +// SetClient sets the rpc client and starts running checkpoint contract if it is not yet watched. +func (s *LesServer) SetContractBackend(backend bind.ContractBackend) { + if s.protocolManager.reg != nil { + s.protocolManager.reg.start(backend) + } +} + // Stop stops the LES service func (s *LesServer) Stop() { s.fcManager.Stop() diff --git a/les/sync.go b/les/sync.go index 1ac6455852..54fd81c2c2 100644 --- a/les/sync.go +++ b/les/sync.go @@ -18,11 +18,29 @@ package les import ( "context" + "errors" "time" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/eth/downloader" "github.com/ethereum/go-ethereum/light" + "github.com/ethereum/go-ethereum/log" +) + +var errInvalidCheckpoint = errors.New("invalid advertised checkpoint") + +const ( + // lightSync starts syncing from the current highest block. + // If the chain is empty, syncing the entire header chain. + lightSync = iota + + // legacyCheckpointSync starts syncing from a hardcoded checkpoint. + legacyCheckpointSync + + // checkpointSync starts syncing from a checkpoint signed by trusted + // signer or hardcoded checkpoint for compatibility. + checkpointSync ) // syncer is responsible for periodically synchronising with the network, both @@ -54,26 +72,141 @@ func (pm *ProtocolManager) syncer() { } } -func (pm *ProtocolManager) needToSync(peerHead blockInfo) bool { - head := pm.blockchain.CurrentHeader() - currentTd := rawdb.ReadTd(pm.chainDb, head.Hash(), head.Number.Uint64()) - return currentTd != nil && peerHead.Td.Cmp(currentTd) > 0 +// validateCheckpoint verifies the advertised checkpoint by peer is valid or not. +// +// Each network has several hard-coded checkpoint signer addresses. Only the +// checkpoint issued by the specified signer is considered valid. +// +// In addition to the checkpoint registered in the registrar contract, there are +// several legacy hardcoded checkpoints in our codebase. These checkpoints are +// also considered as valid. +func (pm *ProtocolManager) validateCheckpoint(peer *peer) error { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + // Fetch the block header corresponding to the checkpoint registration. + cp := peer.checkpoint + header, err := light.GetUntrustedHeaderByNumber(ctx, pm.odr, peer.checkpointNumber, peer.id) + if err != nil { + return err + } + // Fetch block logs associated with the block header. + logs, err := light.GetUntrustedBlockLogs(ctx, pm.odr, header) + if err != nil { + return err + } + events := pm.reg.contract.LookupCheckpointEvents(logs, cp.SectionIndex, cp.Hash()) + if len(events) == 0 { + return errInvalidCheckpoint + } + var ( + index = events[0].Index + hash = events[0].CheckpointHash + signatures [][]byte + ) + for _, event := range events { + signatures = append(signatures, append(event.R[:], append(event.S[:], event.V)...)) + } + valid, signers := pm.reg.verifySigners(index, hash, signatures) + if !valid { + return errInvalidCheckpoint + } + log.Warn("Verified advertised checkpoint", "peer", peer.id, "signers", len(signers)) + return nil } -// synchronise tries to sync up our local block chain with a remote peer. +// synchronise tries to sync up our local chain with a remote peer. func (pm *ProtocolManager) synchronise(peer *peer) { - // Short circuit if no peers are available + // Short circuit if the peer is nil. if peer == nil { return } - // Make sure the peer's TD is higher than our own. - if !pm.needToSync(peer.headBlockInfo()) { + latest := pm.blockchain.CurrentHeader() + currentTd := rawdb.ReadTd(pm.chainDb, latest.Hash(), latest.Number.Uint64()) + if currentTd != nil && peer.headBlockInfo().Td.Cmp(currentTd) < 0 { return } + // Recap the checkpoint. + // + // The light client may be connected to several different versions of the server. + // (1) Old version server which can not provide stable checkpoint in the handshake packet. + // => Use hardcoded checkpoint or empty checkpoint + // (2) New version server but simple checkpoint syncing is not enabled(e.g. mainnet, new testnet or private network) + // => Use hardcoded checkpoint or empty checkpoint + // (3) New version server but the provided stable checkpoint is even lower than the hardcoded one. + // => Use hardcoded checkpoint + // (4) New version server with valid and higher stable checkpoint + // => Use provided checkpoint + var checkpoint = &peer.checkpoint + var hardcoded bool + if pm.checkpoint != nil && pm.checkpoint.SectionIndex >= peer.checkpoint.SectionIndex { + checkpoint = pm.checkpoint // Use the hardcoded one. + hardcoded = true + } + // Determine whether we should run checkpoint syncing or normal light syncing. + // + // Here has four situations that we will disable the checkpoint syncing: + // + // 1. The checkpoint is empty + // 2. The latest head block of the local chain is above the checkpoint. + // 3. The checkpoint is hardcoded(recap with local hardcoded checkpoint) + // 4. For some networks the checkpoint syncing is not activated. + mode := checkpointSync + switch { + case checkpoint.Empty(): + mode = lightSync + log.Debug("Disable checkpoint syncing", "reason", "empty checkpoint") + case latest.Number.Uint64() >= (checkpoint.SectionIndex+1)*pm.iConfig.ChtSize-1: + mode = lightSync + log.Debug("Disable checkpoint syncing", "reason", "local chain beyond the checkpoint") + case hardcoded: + mode = legacyCheckpointSync + log.Debug("Disable checkpoint syncing", "reason", "checkpoint is hardcoded") + case pm.reg == nil || !pm.reg.isRunning(): + mode = legacyCheckpointSync + log.Debug("Disable checkpoint syncing", "reason", "checkpoint syncing is not activated") + } + // Notify testing framework if syncing has completed(for testing purpose). + defer func() { + if pm.reg != nil && pm.reg.syncDoneHook != nil { + pm.reg.syncDoneHook() + } + }() + start := time.Now() + if mode == checkpointSync || mode == legacyCheckpointSync { + // Validate the advertised checkpoint + if mode == legacyCheckpointSync { + checkpoint = pm.checkpoint + } else if mode == checkpointSync { + if err := pm.validateCheckpoint(peer); err != nil { + log.Debug("Failed to validate checkpoint", "reason", err) + pm.removePeer(peer.id) + return + } + pm.blockchain.(*light.LightChain).AddTrustedCheckpoint(checkpoint) + } + log.Debug("Checkpoint syncing start", "peer", peer.id, "checkpoint", checkpoint.SectionIndex) - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) - defer cancel() - pm.blockchain.(*light.LightChain).SyncCht(ctx) - pm.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync) + // Fetch the start point block header. + // + // For the ethash consensus engine, the start header is the block header + // of the checkpoint. + // + // For the clique consensus engine, the start header is the block header + // of the latest epoch covered by checkpoint. + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + if !checkpoint.Empty() && !pm.blockchain.(*light.LightChain).SyncCheckpoint(ctx, checkpoint) { + log.Debug("Sync checkpoint failed") + pm.removePeer(peer.id) + return + } + } + // Fetch the remaining block headers based on the current chain header. + if err := pm.downloader.Synchronise(peer.id, peer.Head(), peer.Td(), downloader.LightSync); err != nil { + log.Debug("Synchronise failed", "reason", err) + return + } + log.Debug("Synchronise finished", "elapsed", common.PrettyDuration(time.Since(start))) } diff --git a/les/sync_test.go b/les/sync_test.go new file mode 100644 index 0000000000..634be8e6d0 --- /dev/null +++ b/les/sync_test.go @@ -0,0 +1,133 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package les + +import ( + "fmt" + "math/big" + "testing" + "time" + + "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/light" + "github.com/ethereum/go-ethereum/params" +) + +// Test light syncing which will download all headers from genesis. +func TestLightSyncingLes2(t *testing.T) { testCheckpointSyncing(t, 2, 0) } +func TestLightSyncingLes3(t *testing.T) { testCheckpointSyncing(t, 3, 0) } + +// Test legacy checkpoint syncing which will download tail headers +// based on a hardcoded checkpoint. +func TestLegacyCheckpointSyncingLes2(t *testing.T) { testCheckpointSyncing(t, 2, 1) } +func TestLegacyCheckpointSyncingLes3(t *testing.T) { testCheckpointSyncing(t, 3, 1) } + +// Test checkpoint syncing which will download tail headers based +// on a verified checkpoint. +func TestCheckpointSyncingLes2(t *testing.T) { testCheckpointSyncing(t, 2, 2) } +func TestCheckpointSyncingLes3(t *testing.T) { testCheckpointSyncing(t, 3, 2) } + +func testCheckpointSyncing(t *testing.T, protocol int, syncMode int) { + config := light.TestServerIndexerConfig + + waitIndexers := func(cIndexer, bIndexer, btIndexer *core.ChainIndexer) { + for { + cs, _, _ := cIndexer.Sections() + bts, _, _ := btIndexer.Sections() + if cs >= 1 && bts >= 1 { + break + } + time.Sleep(10 * time.Millisecond) + } + } + // Generate 512+4 blocks (totally 1 CHT sections) + server, client, tearDown := newClientServerEnv(t, int(config.ChtSize+config.ChtConfirms), protocol, waitIndexers, false) + defer tearDown() + + expected := config.ChtSize + config.ChtConfirms + + // Checkpoint syncing or legacy checkpoint syncing. + if syncMode == 1 || syncMode == 2 { + // Assemble checkpoint 0 + s, _, head := server.chtIndexer.Sections() + cp := ¶ms.TrustedCheckpoint{ + SectionIndex: 0, + SectionHead: head, + CHTRoot: light.GetChtRoot(server.db, s-1, head), + BloomRoot: light.GetBloomTrieRoot(server.db, s-1, head), + } + if syncMode == 1 { + // Register the assembled checkpoint as hardcoded one. + client.pm.checkpoint = cp + client.pm.blockchain.(*light.LightChain).AddTrustedCheckpoint(cp) + } else { + // Register the assembled checkpoint into oracle. + header := server.backend.Blockchain().CurrentHeader() + + data := append([]byte{0x19, 0x00}, append(registrarAddr.Bytes(), append([]byte{0, 0, 0, 0, 0, 0, 0, 0}, cp.Hash().Bytes()...)...)...) + sig, _ := crypto.Sign(crypto.Keccak256(data), signerKey) + sig[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper + if _, err := server.pm.reg.contract.RegisterCheckpoint(signerKey, cp.SectionIndex, cp.Hash().Bytes(), new(big.Int).Sub(header.Number, big.NewInt(1)), header.ParentHash, [][]byte{sig}); err != nil { + t.Error("register checkpoint failed", err) + } + server.backend.Commit() + + // Wait for the checkpoint registration + for { + _, hash, _, err := server.pm.reg.contract.Contract().GetLatestCheckpoint(nil) + if err != nil || hash == [32]byte{} { + time.Sleep(100 * time.Millisecond) + continue + } + break + } + expected += 1 + } + } + + done := make(chan error) + client.pm.reg.syncDoneHook = func() { + header := client.pm.blockchain.CurrentHeader() + if header.Number.Uint64() == expected { + done <- nil + } else { + done <- fmt.Errorf("blockchain length mismatch, want %d, got %d", expected, header.Number) + } + } + + // Create connected peer pair. + peer, err1, lPeer, err2 := newTestPeerPair("peer", protocol, server.pm, client.pm) + select { + case <-time.After(time.Millisecond * 100): + case err := <-err1: + t.Fatalf("peer 1 handshake error: %v", err) + case err := <-err2: + t.Fatalf("peer 2 handshake error: %v", err) + } + server.rPeer, client.rPeer = peer, lPeer + + select { + case err := <-done: + if err != nil { + t.Error("sync failed", err) + } + return + case <-time.NewTimer(10 * time.Second).C: + t.Error("checkpoint syncing timeout") + } +} diff --git a/les/transactions.rlp b/les/transactions.rlp deleted file mode 100755 index e69de29bb2..0000000000 diff --git a/les/txrelay.go b/les/txrelay.go index 5ebef1c226..ffbe251fc4 100644 --- a/les/txrelay.go +++ b/les/txrelay.go @@ -30,7 +30,7 @@ type ltrInfo struct { sentTo map[*peer]struct{} } -type LesTxRelay struct { +type lesTxRelay struct { txSent map[common.Hash]*ltrInfo txPending map[common.Hash]struct{} ps *peerSet @@ -42,8 +42,8 @@ type LesTxRelay struct { retriever *retrieveManager } -func NewLesTxRelay(ps *peerSet, retriever *retrieveManager) *LesTxRelay { - r := &LesTxRelay{ +func newLesTxRelay(ps *peerSet, retriever *retrieveManager) *lesTxRelay { + r := &lesTxRelay{ txSent: make(map[common.Hash]*ltrInfo), txPending: make(map[common.Hash]struct{}), ps: ps, @@ -54,18 +54,18 @@ func NewLesTxRelay(ps *peerSet, retriever *retrieveManager) *LesTxRelay { return r } -func (self *LesTxRelay) Stop() { +func (self *lesTxRelay) Stop() { close(self.stop) } -func (self *LesTxRelay) registerPeer(p *peer) { +func (self *lesTxRelay) registerPeer(p *peer) { self.lock.Lock() defer self.lock.Unlock() self.peerList = self.ps.AllPeers() } -func (self *LesTxRelay) unregisterPeer(p *peer) { +func (self *lesTxRelay) unregisterPeer(p *peer) { self.lock.Lock() defer self.lock.Unlock() @@ -74,7 +74,7 @@ func (self *LesTxRelay) unregisterPeer(p *peer) { // send sends a list of transactions to at most a given number of peers at // once, never resending any particular transaction to the same peer twice -func (self *LesTxRelay) send(txs types.Transactions, count int) { +func (self *lesTxRelay) send(txs types.Transactions, count int) { sendTo := make(map[*peer]types.Transactions) self.peerStartPos++ // rotate the starting position of the peer list @@ -143,14 +143,14 @@ func (self *LesTxRelay) send(txs types.Transactions, count int) { } } -func (self *LesTxRelay) Send(txs types.Transactions) { +func (self *lesTxRelay) Send(txs types.Transactions) { self.lock.Lock() defer self.lock.Unlock() self.send(txs, 3) } -func (self *LesTxRelay) NewHead(head common.Hash, mined []common.Hash, rollback []common.Hash) { +func (self *lesTxRelay) NewHead(head common.Hash, mined []common.Hash, rollback []common.Hash) { self.lock.Lock() defer self.lock.Unlock() @@ -173,7 +173,7 @@ func (self *LesTxRelay) NewHead(head common.Hash, mined []common.Hash, rollback } } -func (self *LesTxRelay) Discard(hashes []common.Hash) { +func (self *lesTxRelay) Discard(hashes []common.Hash) { self.lock.Lock() defer self.lock.Unlock() diff --git a/les/ulc_test.go b/les/ulc_test.go index 38adeb95f1..3a3281a3f3 100644 --- a/les/ulc_test.go +++ b/les/ulc_test.go @@ -26,7 +26,6 @@ import ( "time" "github.com/ethereum/go-ethereum/common/mclock" - "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth" @@ -36,7 +35,7 @@ import ( ) func TestULCSyncWithOnePeer(t *testing.T) { - f := newFullPeerPair(t, 1, 4, testChainGen) + f := newFullPeerPair(t, 1, 4) ulcConfig := ð.ULCConfig{ MinTrustedFraction: 100, TrustedServers: []string{f.Node.String()}, @@ -63,7 +62,7 @@ func TestULCSyncWithOnePeer(t *testing.T) { } func TestULCReceiveAnnounce(t *testing.T) { - f := newFullPeerPair(t, 1, 4, testChainGen) + f := newFullPeerPair(t, 1, 4) ulcConfig := ð.ULCConfig{ MinTrustedFraction: 100, TrustedServers: []string{f.Node.String()}, @@ -100,8 +99,8 @@ func TestULCReceiveAnnounce(t *testing.T) { } func TestULCShouldNotSyncWithTwoPeersOneHaveEmptyChain(t *testing.T) { - f1 := newFullPeerPair(t, 1, 4, testChainGen) - f2 := newFullPeerPair(t, 2, 0, nil) + f1 := newFullPeerPair(t, 1, 4) + f2 := newFullPeerPair(t, 2, 0) ulcConf := &ulc{minTrustedFraction: 100, trustedKeys: make(map[string]struct{})} ulcConf.trustedKeys[f1.Node.ID().String()] = struct{}{} ulcConf.trustedKeys[f2.Node.ID().String()] = struct{}{} @@ -131,9 +130,9 @@ func TestULCShouldNotSyncWithTwoPeersOneHaveEmptyChain(t *testing.T) { } func TestULCShouldNotSyncWithThreePeersOneHaveEmptyChain(t *testing.T) { - f1 := newFullPeerPair(t, 1, 3, testChainGen) - f2 := newFullPeerPair(t, 2, 4, testChainGen) - f3 := newFullPeerPair(t, 3, 0, nil) + f1 := newFullPeerPair(t, 1, 3) + f2 := newFullPeerPair(t, 2, 4) + f3 := newFullPeerPair(t, 3, 0) ulcConfig := ð.ULCConfig{ MinTrustedFraction: 60, @@ -211,10 +210,10 @@ func connectPeers(full, light pairPeer, version int) (*peer, *peer, error) { } // newFullPeerPair creates node with full sync mode -func newFullPeerPair(t *testing.T, index int, numberOfblocks int, chainGen func(int, *core.BlockGen)) pairPeer { +func newFullPeerPair(t *testing.T, index int, numberOfblocks int) pairPeer { db := rawdb.NewMemoryDatabase() - pmFull := newTestProtocolManagerMust(t, false, numberOfblocks, chainGen, nil, nil, db, nil) + pmFull, _ := newTestProtocolManagerMust(t, false, numberOfblocks, nil, nil, nil, db, nil) peerPairFull := pairPeer{ Name: "full node", @@ -238,7 +237,7 @@ func newLightPeer(t *testing.T, ulcConfig *eth.ULCConfig) pairPeer { odr := NewLesOdr(ldb, light.DefaultClientIndexerConfig, rm) - pmLight := newTestProtocolManagerMust(t, true, 0, nil, odr, peers, ldb, ulcConfig) + pmLight, _ := newTestProtocolManagerMust(t, true, 0, odr, nil, peers, ldb, ulcConfig) peerPairLight := pairPeer{ Name: "ulc node", PM: pmLight, diff --git a/light/lightchain.go b/light/lightchain.go index f0beec47bb..7f64d1c28b 100644 --- a/light/lightchain.go +++ b/light/lightchain.go @@ -77,7 +77,7 @@ type LightChain struct { // NewLightChain returns a fully initialised light chain using information // available in the database. It initialises the default Ethereum header // validator. -func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine) (*LightChain, error) { +func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus.Engine, checkpoint *params.TrustedCheckpoint) (*LightChain, error) { bodyCache, _ := lru.New(bodyCacheLimit) bodyRLPCache, _ := lru.New(bodyCacheLimit) blockCache, _ := lru.New(blockCacheLimit) @@ -101,8 +101,8 @@ func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus. if bc.genesisBlock == nil { return nil, core.ErrNoGenesis } - if cp, ok := params.TrustedCheckpoints[bc.genesisBlock.Hash()]; ok { - bc.addTrustedCheckpoint(cp) + if checkpoint != nil { + bc.AddTrustedCheckpoint(checkpoint) } if err := bc.loadLastState(); err != nil { return nil, err @@ -118,8 +118,8 @@ func NewLightChain(odr OdrBackend, config *params.ChainConfig, engine consensus. return bc, nil } -// addTrustedCheckpoint adds a trusted checkpoint to the blockchain -func (lc *LightChain) addTrustedCheckpoint(cp *params.TrustedCheckpoint) { +// AddTrustedCheckpoint adds a trusted checkpoint to the blockchain +func (lc *LightChain) AddTrustedCheckpoint(cp *params.TrustedCheckpoint) { if lc.odr.ChtIndexer() != nil { StoreChtRoot(lc.chainDb, cp.SectionIndex, cp.SectionHead, cp.CHTRoot) lc.odr.ChtIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead) @@ -131,7 +131,7 @@ func (lc *LightChain) addTrustedCheckpoint(cp *params.TrustedCheckpoint) { if lc.odr.BloomIndexer() != nil { lc.odr.BloomIndexer().AddCheckpoint(cp.SectionIndex, cp.SectionHead) } - log.Info("Added trusted checkpoint", "chain", cp.Name, "block", (cp.SectionIndex+1)*lc.indexerConfig.ChtSize-1, "hash", cp.SectionHead) + log.Info("Added trusted checkpoint", "block", (cp.SectionIndex+1)*lc.indexerConfig.ChtSize-1, "hash", cp.SectionHead) } func (lc *LightChain) getProcInterrupt() bool { @@ -462,21 +462,21 @@ func (lc *LightChain) GetHeaderByNumberOdr(ctx context.Context, number uint64) ( // Config retrieves the header chain's chain configuration. func (lc *LightChain) Config() *params.ChainConfig { return lc.hc.Config() } -func (lc *LightChain) SyncCht(ctx context.Context) bool { - // If we don't have a CHT indexer, abort - if lc.odr.ChtIndexer() == nil { - return false - } - // Ensure the remote CHT head is ahead of us +// SyncCheckpoint fetches the checkpoint point block header according to +// the checkpoint provided by the remote peer. +// +// Note if we are running the clique, fetches the last epoch snapshot header +// which covered by checkpoint. +func (lc *LightChain) SyncCheckpoint(ctx context.Context, checkpoint *params.TrustedCheckpoint) bool { + // Ensure the remote checkpoint head is ahead of us head := lc.CurrentHeader().Number.Uint64() - sections, _, _ := lc.odr.ChtIndexer().Sections() - latest := sections*lc.indexerConfig.ChtSize - 1 + latest := (checkpoint.SectionIndex+1)*lc.indexerConfig.ChtSize - 1 if clique := lc.hc.Config().Clique; clique != nil { latest -= latest % clique.Epoch // epoch snapshot for clique } if head >= latest { - return false + return true } // Retrieve the latest useful header and update to it if header, err := GetHeaderByNumber(ctx, lc.odr, latest); header != nil && err == nil { diff --git a/light/lightchain_test.go b/light/lightchain_test.go index 58ea93044a..70d2e70c18 100644 --- a/light/lightchain_test.go +++ b/light/lightchain_test.go @@ -55,7 +55,7 @@ func newCanonical(n int) (ethdb.Database, *LightChain, error) { db := rawdb.NewMemoryDatabase() gspec := core.Genesis{Config: params.TestChainConfig} genesis := gspec.MustCommit(db) - blockchain, _ := NewLightChain(&dummyOdr{db: db, indexerConfig: TestClientIndexerConfig}, gspec.Config, ethash.NewFaker()) + blockchain, _ := NewLightChain(&dummyOdr{db: db, indexerConfig: TestClientIndexerConfig}, gspec.Config, ethash.NewFaker(), nil) // Create and inject the requested chain if n == 0 { @@ -75,7 +75,7 @@ func newTestLightChain() *LightChain { Config: params.TestChainConfig, } gspec.MustCommit(db) - lc, err := NewLightChain(&dummyOdr{db: db}, gspec.Config, ethash.NewFullFaker()) + lc, err := NewLightChain(&dummyOdr{db: db}, gspec.Config, ethash.NewFullFaker(), nil) if err != nil { panic(err) } @@ -344,7 +344,7 @@ func TestReorgBadHeaderHashes(t *testing.T) { defer func() { delete(core.BadHashes, headers[3].Hash()) }() // Create a new LightChain and check that it rolled back the state. - ncm, err := NewLightChain(&dummyOdr{db: bc.chainDb}, params.TestChainConfig, ethash.NewFaker()) + ncm, err := NewLightChain(&dummyOdr{db: bc.chainDb}, params.TestChainConfig, ethash.NewFaker(), nil) if err != nil { t.Fatalf("failed to create new chain manager: %v", err) } diff --git a/light/odr.go b/light/odr.go index d1185e4e07..907712ede7 100644 --- a/light/odr.go +++ b/light/odr.go @@ -122,19 +122,25 @@ func (req *BlockRequest) StoreResult(db ethdb.Database) { // ReceiptsRequest is the ODR request type for retrieving block bodies type ReceiptsRequest struct { OdrRequest - Hash common.Hash - Number uint64 - Receipts types.Receipts + Untrusted bool // Indicator whether the result retrieved is trusted or not + Hash common.Hash + Number uint64 + Header *types.Header + Receipts types.Receipts } // StoreResult stores the retrieved data in local database func (req *ReceiptsRequest) StoreResult(db ethdb.Database) { - rawdb.WriteReceipts(db, req.Hash, req.Number, req.Receipts) + if !req.Untrusted { + rawdb.WriteReceipts(db, req.Hash, req.Number, req.Receipts) + } } // ChtRequest is the ODR request type for state/storage trie entries type ChtRequest struct { OdrRequest + Untrusted bool // Indicator whether the result retrieved is trusted or not + PeerId string // The specified peer id from which to retrieve data. Config *IndexerConfig ChtNum, BlockNum uint64 ChtRoot common.Hash @@ -147,9 +153,11 @@ type ChtRequest struct { func (req *ChtRequest) StoreResult(db ethdb.Database) { hash, num := req.Header.Hash(), req.Header.Number.Uint64() - rawdb.WriteHeader(db, req.Header) - rawdb.WriteTd(db, hash, num, req.Td) - rawdb.WriteCanonicalHash(db, hash, num) + if !req.Untrusted { + rawdb.WriteHeader(db, req.Header) + rawdb.WriteTd(db, hash, num, req.Td) + rawdb.WriteCanonicalHash(db, hash, num) + } } // BloomRequest is the ODR request type for retrieving bloom filters from a CHT structure diff --git a/light/odr_test.go b/light/odr_test.go index 912a0cbdd8..debd5544c3 100644 --- a/light/odr_test.go +++ b/light/odr_test.go @@ -264,7 +264,7 @@ func testChainOdr(t *testing.T, protocol int, fn odrTestFn) { } odr := &testOdr{sdb: sdb, ldb: ldb, indexerConfig: TestClientIndexerConfig} - lightchain, err := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker()) + lightchain, err := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker(), nil) if err != nil { t.Fatal(err) } diff --git a/light/odr_util.go b/light/odr_util.go index 100bd58428..82e33bb78f 100644 --- a/light/odr_util.go +++ b/light/odr_util.go @@ -69,6 +69,16 @@ func GetHeaderByNumber(ctx context.Context, odr OdrBackend, number uint64) (*typ return r.Header, nil } +// GetUntrustedHeaderByNumber fetches specified block header without correctness checking. +// Note this function should only be used in light client checkpoint syncing. +func GetUntrustedHeaderByNumber(ctx context.Context, odr OdrBackend, number uint64, peerId string) (*types.Header, error) { + r := &ChtRequest{BlockNum: number, ChtNum: number / odr.IndexerConfig().ChtSize, Untrusted: true, PeerId: peerId, Config: odr.IndexerConfig()} + if err := odr.Retrieve(ctx, r); err != nil { + return nil, err + } + return r.Header, nil +} + func GetCanonicalHash(ctx context.Context, odr OdrBackend, number uint64) (common.Hash, error) { hash := rawdb.ReadCanonicalHash(odr.Database(), number) if (hash != common.Hash{}) { @@ -169,6 +179,30 @@ func GetBlockLogs(ctx context.Context, odr OdrBackend, hash common.Hash, number return logs, nil } +// GetUntrustedBlockLogs retrieves the logs generated by the transactions included in a +// block. The retrieved logs are regarded as untrusted and will not be stored in the +// database. This function should only be used in light client checkpoint syncing. +func GetUntrustedBlockLogs(ctx context.Context, odr OdrBackend, header *types.Header) ([][]*types.Log, error) { + // Retrieve the potentially incomplete receipts from disk or network + hash, number := header.Hash(), header.Number.Uint64() + receipts := rawdb.ReadRawReceipts(odr.Database(), hash, number) + if receipts == nil { + r := &ReceiptsRequest{Hash: hash, Number: number, Header: header, Untrusted: true} + if err := odr.Retrieve(ctx, r); err != nil { + return nil, err + } + receipts = r.Receipts + // Untrusted receipts won't be stored in the database. Therefore + // derived fields computation is unnecessary. + } + // Return the logs without deriving any computed fields on the receipts + logs := make([][]*types.Log, len(receipts)) + for i, receipt := range receipts { + logs[i] = receipt.Logs + } + return logs, nil +} + // GetBloomBits retrieves a batch of compressed bloomBits vectors belonging to the given bit index and section indexes func GetBloomBits(ctx context.Context, odr OdrBackend, bitIdx uint, sectionIdxList []uint64) ([][]byte, error) { var ( diff --git a/light/txpool_test.go b/light/txpool_test.go index 4f446c6ca2..0996bd7c9c 100644 --- a/light/txpool_test.go +++ b/light/txpool_test.go @@ -100,7 +100,7 @@ func TestTxPool(t *testing.T) { discard: make(chan int, 1), mined: make(chan int, 1), } - lightchain, _ := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker()) + lightchain, _ := NewLightChain(odr, params.TestChainConfig, ethash.NewFullFaker(), nil) txPermanent = 50 pool := NewTxPool(params.TestChainConfig, lightchain, relay) ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) diff --git a/mobile/bind.go b/mobile/bind.go index d6e621a258..90ecdf82c4 100644 --- a/mobile/bind.go +++ b/mobile/bind.go @@ -19,27 +19,30 @@ package geth import ( + "errors" "math/big" "strings" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/accounts/abi/bind" + "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/crypto" ) -// Signer is an interaface defining the callback when a contract requires a +// Signer is an interface defining the callback when a contract requires a // method to sign the transaction before submission. type Signer interface { Sign(*Address, *Transaction) (tx *Transaction, _ error) } -type signer struct { +type MobileSigner struct { sign bind.SignerFn } -func (s *signer) Sign(addr *Address, unsignedTx *Transaction) (signedTx *Transaction, _ error) { - sig, err := s.sign(types.HomesteadSigner{}, addr.address, unsignedTx.tx) +func (s *MobileSigner) Sign(addr *Address, unsignedTx *Transaction) (signedTx *Transaction, _ error) { + sig, err := s.sign(types.EIP155Signer{}, addr.address, unsignedTx.tx) if err != nil { return nil, err } @@ -73,6 +76,35 @@ type TransactOpts struct { opts bind.TransactOpts } +// NewTransactOpts creates a new option set for contract transaction. +func NewTransactOpts() *TransactOpts { + return new(TransactOpts) +} + +// NewKeyedTransactor is a utility method to easily create a transaction signer +// from a single private key. +func NewKeyedTransactOpts(keyJson []byte, passphrase string) (*TransactOpts, error) { + key, err := keystore.DecryptKey(keyJson, passphrase) + if err != nil { + return nil, err + } + keyAddr := crypto.PubkeyToAddress(key.PrivateKey.PublicKey) + opts := bind.TransactOpts{ + From: keyAddr, + Signer: func(signer types.Signer, address common.Address, tx *types.Transaction) (*types.Transaction, error) { + if address != keyAddr { + return nil, errors.New("not authorized to sign this account") + } + signature, err := crypto.Sign(signer.Hash(tx).Bytes(), key.PrivateKey) + if err != nil { + return nil, err + } + return tx.WithSignature(signer, signature) + }, + } + return &TransactOpts{opts}, nil +} + func (opts *TransactOpts) GetFrom() *Address { return &Address{opts.opts.From} } func (opts *TransactOpts) GetNonce() int64 { return opts.opts.Nonce.Int64() } func (opts *TransactOpts) GetValue() *BigInt { return &BigInt{opts.opts.Value} } diff --git a/mobile/common.go b/mobile/common.go index 047d8e1f65..d7e0457261 100644 --- a/mobile/common.go +++ b/mobile/common.go @@ -25,6 +25,7 @@ import ( "strings" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/common/hexutil" ) // Hash represents the 32 byte Keccak256 hash of arbitrary data. @@ -228,3 +229,13 @@ func (a *Addresses) Set(index int, address *Address) error { func (a *Addresses) Append(address *Address) { a.addresses = append(a.addresses, address.address) } + +// EncodeToHex encodes b as a hex string with 0x prefix. +func EncodeToHex(b []byte) string { + return hexutil.Encode(b) +} + +// DecodeFromHex decodes a hex string with 0x prefix. +func DecodeFromHex(s string) ([]byte, error) { + return hexutil.Decode(s) +} diff --git a/mobile/interface.go b/mobile/interface.go index ac0c26088a..d5200d5b1b 100644 --- a/mobile/interface.go +++ b/mobile/interface.go @@ -42,26 +42,82 @@ func NewInterface() *Interface { return new(Interface) } -func (i *Interface) SetBool(b bool) { i.object = &b } -func (i *Interface) SetBools(bs []bool) { i.object = &bs } -func (i *Interface) SetString(str string) { i.object = &str } -func (i *Interface) SetStrings(strs *Strings) { i.object = &strs.strs } -func (i *Interface) SetBinary(binary []byte) { b := common.CopyBytes(binary); i.object = &b } -func (i *Interface) SetBinaries(binaries [][]byte) { i.object = &binaries } -func (i *Interface) SetAddress(address *Address) { i.object = &address.address } -func (i *Interface) SetAddresses(addrs *Addresses) { i.object = &addrs.addresses } -func (i *Interface) SetHash(hash *Hash) { i.object = &hash.hash } -func (i *Interface) SetHashes(hashes *Hashes) { i.object = &hashes.hashes } -func (i *Interface) SetInt8(n int8) { i.object = &n } -func (i *Interface) SetInt16(n int16) { i.object = &n } -func (i *Interface) SetInt32(n int32) { i.object = &n } -func (i *Interface) SetInt64(n int64) { i.object = &n } -func (i *Interface) SetUint8(bigint *BigInt) { n := uint8(bigint.bigint.Uint64()); i.object = &n } -func (i *Interface) SetUint16(bigint *BigInt) { n := uint16(bigint.bigint.Uint64()); i.object = &n } -func (i *Interface) SetUint32(bigint *BigInt) { n := uint32(bigint.bigint.Uint64()); i.object = &n } -func (i *Interface) SetUint64(bigint *BigInt) { n := bigint.bigint.Uint64(); i.object = &n } -func (i *Interface) SetBigInt(bigint *BigInt) { i.object = &bigint.bigint } -func (i *Interface) SetBigInts(bigints *BigInts) { i.object = &bigints.bigints } +func (i *Interface) SetBool(b bool) { i.object = &b } +func (i *Interface) SetBools(bs *Bools) { i.object = &bs.bools } +func (i *Interface) SetString(str string) { i.object = &str } +func (i *Interface) SetStrings(strs *Strings) { i.object = &strs.strs } +func (i *Interface) SetBinary(binary []byte) { b := common.CopyBytes(binary); i.object = &b } +func (i *Interface) SetBinaries(binaries *Binaries) { i.object = &binaries.binaries } +func (i *Interface) SetAddress(address *Address) { i.object = &address.address } +func (i *Interface) SetAddresses(addrs *Addresses) { i.object = &addrs.addresses } +func (i *Interface) SetHash(hash *Hash) { i.object = &hash.hash } +func (i *Interface) SetHashes(hashes *Hashes) { i.object = &hashes.hashes } +func (i *Interface) SetInt8(n int8) { i.object = &n } +func (i *Interface) SetInt16(n int16) { i.object = &n } +func (i *Interface) SetInt32(n int32) { i.object = &n } +func (i *Interface) SetInt64(n int64) { i.object = &n } +func (i *Interface) SetInt8s(bigints *BigInts) { + ints := make([]int8, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, int8(bi.Int64())) + } + i.object = &ints +} +func (i *Interface) SetInt16s(bigints *BigInts) { + ints := make([]int16, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, int16(bi.Int64())) + } + i.object = &ints +} +func (i *Interface) SetInt32s(bigints *BigInts) { + ints := make([]int32, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, int32(bi.Int64())) + } + i.object = &ints +} +func (i *Interface) SetInt64s(bigints *BigInts) { + ints := make([]int64, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, bi.Int64()) + } + i.object = &ints +} +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) SetUint8s(bigints *BigInts) { + ints := make([]uint8, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, uint8(bi.Uint64())) + } + i.object = &ints +} +func (i *Interface) SetUint16s(bigints *BigInts) { + ints := make([]uint16, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, uint16(bi.Uint64())) + } + i.object = &ints +} +func (i *Interface) SetUint32s(bigints *BigInts) { + ints := make([]uint32, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, uint32(bi.Uint64())) + } + i.object = &ints +} +func (i *Interface) SetUint64s(bigints *BigInts) { + ints := make([]uint64, 0, bigints.Size()) + for _, bi := range bigints.bigints { + ints = append(ints, bi.Uint64()) + } + i.object = &ints +} +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) } @@ -74,22 +130,30 @@ 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) SetDefaultInt8s() { i.object = new([]int8) } func (i *Interface) SetDefaultInt16() { i.object = new(int16) } +func (i *Interface) SetDefaultInt16s() { i.object = new([]int16) } func (i *Interface) SetDefaultInt32() { i.object = new(int32) } +func (i *Interface) SetDefaultInt32s() { i.object = new([]int32) } func (i *Interface) SetDefaultInt64() { i.object = new(int64) } +func (i *Interface) SetDefaultInt64s() { i.object = new([]int64) } func (i *Interface) SetDefaultUint8() { i.object = new(uint8) } +func (i *Interface) SetDefaultUint8s() { i.object = new([]uint8) } func (i *Interface) SetDefaultUint16() { i.object = new(uint16) } +func (i *Interface) SetDefaultUint16s() { i.object = new([]uint16) } func (i *Interface) SetDefaultUint32() { i.object = new(uint32) } +func (i *Interface) SetDefaultUint32s() { i.object = new([]uint32) } func (i *Interface) SetDefaultUint64() { i.object = new(uint64) } +func (i *Interface) SetDefaultUint64s() { 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) GetBools() *Bools { return &Bools{*i.object.(*[]bool)} } func (i *Interface) GetString() string { return *i.object.(*string) } func (i *Interface) GetStrings() *Strings { return &Strings{*i.object.(*[]string)} } func (i *Interface) GetBinary() []byte { return *i.object.(*[]byte) } -func (i *Interface) GetBinaries() [][]byte { return *i.object.(*[][]byte) } +func (i *Interface) GetBinaries() *Binaries { return &Binaries{*i.object.(*[][]byte)} } func (i *Interface) GetAddress() *Address { return &Address{*i.object.(*common.Address)} } func (i *Interface) GetAddresses() *Addresses { return &Addresses{*i.object.(*[]common.Address)} } func (i *Interface) GetHash() *Hash { return &Hash{*i.object.(*common.Hash)} } @@ -98,6 +162,38 @@ 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) GetInt8s() *BigInts { + val := i.object.(*[]int8) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetInt64(int64(v))}) + } + return bigints +} +func (i *Interface) GetInt16s() *BigInts { + val := i.object.(*[]int16) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetInt64(int64(v))}) + } + return bigints +} +func (i *Interface) GetInt32s() *BigInts { + val := i.object.(*[]int32) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetInt64(int64(v))}) + } + return bigints +} +func (i *Interface) GetInt64s() *BigInts { + val := i.object.(*[]int64) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetInt64(v)}) + } + return bigints +} func (i *Interface) GetUint8() *BigInt { return &BigInt{new(big.Int).SetUint64(uint64(*i.object.(*uint8)))} } @@ -110,6 +206,38 @@ func (i *Interface) GetUint32() *BigInt { func (i *Interface) GetUint64() *BigInt { return &BigInt{new(big.Int).SetUint64(*i.object.(*uint64))} } +func (i *Interface) GetUint8s() *BigInts { + val := i.object.(*[]uint8) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetUint64(uint64(v))}) + } + return bigints +} +func (i *Interface) GetUint16s() *BigInts { + val := i.object.(*[]uint16) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetUint64(uint64(v))}) + } + return bigints +} +func (i *Interface) GetUint32s() *BigInts { + val := i.object.(*[]uint32) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetUint64(uint64(v))}) + } + return bigints +} +func (i *Interface) GetUint64s() *BigInts { + val := i.object.(*[]uint64) + bigints := NewBigInts(len(*val)) + for i, v := range *val { + bigints.Set(i, &BigInt{new(big.Int).SetUint64(v)}) + } + return bigints +} func (i *Interface) GetBigInt() *BigInt { return &BigInt{*i.object.(**big.Int)} } func (i *Interface) GetBigInts() *BigInts { return &BigInts{*i.object.(*[]*big.Int)} } @@ -120,9 +248,7 @@ type Interfaces struct { // NewInterfaces creates a slice of uninitialized interfaces. func NewInterfaces(size int) *Interfaces { - return &Interfaces{ - objects: make([]interface{}, size), - } + return &Interfaces{objects: make([]interface{}, size)} } // Size returns the number of interfaces in the slice. @@ -131,11 +257,13 @@ func (i *Interfaces) Size() int { } // Get returns the bigint at the given index from the slice. +// Notably the returned value can be changed without affecting the +// interfaces itself. func (i *Interfaces) Get(index int) (iface *Interface, _ error) { if index < 0 || index >= len(i.objects) { return nil, errors.New("index out of bounds") } - return &Interface{i.objects[index]}, nil + return &Interface{object: i.objects[index]}, nil } // Set sets the big int at the given index in the slice. diff --git a/mobile/interface_test.go b/mobile/interface_test.go new file mode 100644 index 0000000000..4bd1af47aa --- /dev/null +++ b/mobile/interface_test.go @@ -0,0 +1,90 @@ +// Copyright 2019 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package geth + +import ( + "fmt" + "math/big" + "reflect" + "testing" + + "github.com/ethereum/go-ethereum/common" +) + +func TestInterfaceGetSet(t *testing.T) { + var tests = []struct { + method string + input interface{} + expect interface{} + }{ + {"Bool", true, true}, + {"Bool", false, false}, + {"Bools", &Bools{[]bool{false, true}}, &Bools{[]bool{false, true}}}, + {"String", "go-ethereum", "go-ethereum"}, + {"Strings", &Strings{strs: []string{"hello", "world"}}, &Strings{strs: []string{"hello", "world"}}}, + {"Binary", []byte{0x01, 0x02}, []byte{0x01, 0x02}}, + {"Binaries", &Binaries{[][]byte{{0x01, 0x02}, {0x03, 0x04}}}, &Binaries{[][]byte{{0x01, 0x02}, {0x03, 0x04}}}}, + {"Address", &Address{common.HexToAddress("deadbeef")}, &Address{common.HexToAddress("deadbeef")}}, + {"Addresses", &Addresses{[]common.Address{common.HexToAddress("deadbeef"), common.HexToAddress("cafebabe")}}, &Addresses{[]common.Address{common.HexToAddress("deadbeef"), common.HexToAddress("cafebabe")}}}, + {"Hash", &Hash{common.HexToHash("deadbeef")}, &Hash{common.HexToHash("deadbeef")}}, + {"Hashes", &Hashes{[]common.Hash{common.HexToHash("deadbeef"), common.HexToHash("cafebabe")}}, &Hashes{[]common.Hash{common.HexToHash("deadbeef"), common.HexToHash("cafebabe")}}}, + {"Int8", int8(1), int8(1)}, + {"Int16", int16(1), int16(1)}, + {"Int32", int32(1), int32(1)}, + {"Int64", int64(1), int64(1)}, + {"Int8s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"Int16s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"Int32s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"Int64s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"Uint8", NewBigInt(1), NewBigInt(1)}, + {"Uint16", NewBigInt(1), NewBigInt(1)}, + {"Uint32", NewBigInt(1), NewBigInt(1)}, + {"Uint64", NewBigInt(1), NewBigInt(1)}, + {"Uint8s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"Uint16s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"Uint32s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"Uint64s", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + {"BigInt", NewBigInt(1), NewBigInt(1)}, + {"BigInts", &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}, &BigInts{[]*big.Int{big.NewInt(1), big.NewInt(2)}}}, + } + + args := NewInterfaces(len(tests)) + + callFn := func(receiver interface{}, method string, arg interface{}) interface{} { + rval := reflect.ValueOf(receiver) + rval.MethodByName(fmt.Sprintf("Set%s", method)).Call([]reflect.Value{reflect.ValueOf(arg)}) + res := rval.MethodByName(fmt.Sprintf("Get%s", method)).Call(nil) + if len(res) > 0 { + return res[0].Interface() + } + return nil + } + + for index, c := range tests { + // In theory the change of iface shouldn't effect the args value + iface, _ := args.Get(index) + result := callFn(iface, c.method, c.input) + if !reflect.DeepEqual(result, c.expect) { + t.Errorf("Interface get/set mismatch, want %v, got %v", c.expect, result) + } + // Check whether the underlying value in args is still zero + iface, _ = args.Get(index) + if iface.object != nil { + t.Error("Get operation is not write safe") + } + } +} diff --git a/mobile/primitives.go b/mobile/primitives.go index 5c6617fa47..7e1ab26ef0 100644 --- a/mobile/primitives.go +++ b/mobile/primitives.go @@ -21,6 +21,8 @@ package geth import ( "errors" "fmt" + + "github.com/ethereum/go-ethereum/common" ) // Strings represents s slice of strs. @@ -52,3 +54,63 @@ func (s *Strings) Set(index int, str string) error { func (s *Strings) String() string { return fmt.Sprintf("%v", s.strs) } + +// Bools represents a slice of bool. +type Bools struct{ bools []bool } + +// Size returns the number of bool in the slice. +func (bs *Bools) Size() int { + return len(bs.bools) +} + +// Get returns the bool at the given index from the slice. +func (bs *Bools) Get(index int) (b bool, _ error) { + if index < 0 || index >= len(bs.bools) { + return false, errors.New("index out of bounds") + } + return bs.bools[index], nil +} + +// Set sets the bool at the given index in the slice. +func (bs *Bools) Set(index int, b bool) error { + if index < 0 || index >= len(bs.bools) { + return errors.New("index out of bounds") + } + bs.bools[index] = b + return nil +} + +// String implements the Stringer interface. +func (bs *Bools) String() string { + return fmt.Sprintf("%v", bs.bools) +} + +// Binaries represents a slice of byte slice +type Binaries struct{ binaries [][]byte } + +// Size returns the number of byte slice in the slice. +func (bs *Binaries) Size() int { + return len(bs.binaries) +} + +// Get returns the byte slice at the given index from the slice. +func (bs *Binaries) Get(index int) (binary []byte, _ error) { + if index < 0 || index >= len(bs.binaries) { + return nil, errors.New("index out of bounds") + } + return common.CopyBytes(bs.binaries[index]), nil +} + +// Set sets the byte slice at the given index in the slice. +func (bs *Binaries) Set(index int, binary []byte) error { + if index < 0 || index >= len(bs.binaries) { + return errors.New("index out of bounds") + } + bs.binaries[index] = common.CopyBytes(binary) + return nil +} + +// String implements the Stringer interface. +func (bs *Binaries) String() string { + return fmt.Sprintf("%v", bs.binaries) +} diff --git a/node/node.go b/node/node.go index 08daeeee0f..c9c27d8262 100644 --- a/node/node.go +++ b/node/node.go @@ -247,7 +247,6 @@ func (n *Node) Start() error { n.services = services n.server = running n.stop = make(chan struct{}) - return nil } diff --git a/p2p/message.go b/p2p/message.go index ac12666e41..9e387ba9b6 100644 --- a/p2p/message.go +++ b/p2p/message.go @@ -169,7 +169,7 @@ type MsgPipeRW struct { closed *int32 } -// WriteMsg sends a messsage on the pipe. +// WriteMsg sends a message on the pipe. // It blocks until the receiver has consumed the message payload. func (p *MsgPipeRW) WriteMsg(msg Msg) error { if atomic.LoadInt32(p.closed) == 0 { diff --git a/params/config.go b/params/config.go index c59c748ac2..e79d4ffc9f 100644 --- a/params/config.go +++ b/params/config.go @@ -17,10 +17,12 @@ package params import ( + "encoding/binary" "fmt" "math/big" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" ) // Genesis hashes to enforce below configs on. @@ -40,6 +42,12 @@ var TrustedCheckpoints = map[common.Hash]*TrustedCheckpoint{ GoerliGenesisHash: GoerliTrustedCheckpoint, } +// CheckpointOracles associates each known checkpoint oracles with the genesis hash of +// the chain it belongs to. +var CheckpointOracles = map[common.Hash]*CheckpointOracleConfig{ + RinkebyGenesisHash: RinkebyCheckpointOracle, +} + var ( // MainnetChainConfig is the chain parameters to run a node on the main network. MainnetChainConfig = &ChainConfig{ @@ -59,7 +67,6 @@ var ( // MainnetTrustedCheckpoint contains the light client trusted checkpoint for the main network. MainnetTrustedCheckpoint = &TrustedCheckpoint{ - Name: "mainnet", SectionIndex: 227, SectionHead: common.HexToHash("0xa2e0b25d72c2fc6e35a7f853cdacb193b4b4f95c606accf7f8fa8415283582c7"), CHTRoot: common.HexToHash("0xf69bdd4053b95b61a27b106a0e86103d791edd8574950dc96aa351ab9b9f1aa0"), @@ -84,7 +91,6 @@ var ( // TestnetTrustedCheckpoint contains the light client trusted checkpoint for the Ropsten test network. TestnetTrustedCheckpoint = &TrustedCheckpoint{ - Name: "testnet", SectionIndex: 161, SectionHead: common.HexToHash("0x5378afa734e1feafb34bcca1534c4d96952b754579b96a4afb23d5301ecececc"), CHTRoot: common.HexToHash("0x1cf2b071e7443a62914362486b613ff30f60cea0d9c268ed8c545f876a3ee60c"), @@ -112,13 +118,24 @@ var ( // RinkebyTrustedCheckpoint contains the light client trusted checkpoint for the Rinkeby test network. RinkebyTrustedCheckpoint = &TrustedCheckpoint{ - Name: "rinkeby", SectionIndex: 125, SectionHead: common.HexToHash("0x8a738386f6bb34add15846f8f49c4c519a2f32519096e792b9f43bcb407c831c"), CHTRoot: common.HexToHash("0xa1e5720a9bad4dce794f129e4ac6744398197b652868011486a6f89c8ec84a75"), BloomRoot: common.HexToHash("0xa3048fe8b7e30f77f11bc755a88478363d7d3e71c2bdfe4e8ab9e269cd804ba2"), } + // RinkebyCheckpointOracle contains a set of configs for the Rinkeby test network oracle. + RinkebyCheckpointOracle = &CheckpointOracleConfig{ + Address: common.HexToAddress("0xebe8eFA441B9302A0d7eaECc277c09d20D684540"), + Signers: []common.Address{ + common.HexToAddress("0xd9c9cd5f6779558b6e0ed4e6acf6b1947e7fa1f3"), // Peter + common.HexToAddress("0x78d1ad571a1a09d60d9bbf25894b44e4c8859595"), // Martin + common.HexToAddress("0x286834935f4A8Cfb4FF4C77D5770C2775aE2b0E7"), // Zsolt + common.HexToAddress("0xb86e2B0Ab5A4B1373e40c51A7C712c70Ba2f9f8E"), // Gary + }, + Threshold: 2, + } + // GoerliChainConfig contains the chain parameters to run a node on the Görli test network. GoerliChainConfig = &ChainConfig{ ChainID: big.NewInt(5), @@ -139,7 +156,6 @@ var ( // GoerliTrustedCheckpoint contains the light client trusted checkpoint for the Görli test network. GoerliTrustedCheckpoint = &TrustedCheckpoint{ - Name: "goerli", SectionIndex: 9, SectionHead: common.HexToHash("0x8e223d827391eee53b07cb8ee057dbfa11c93e0b45352188c783affd7840a921"), CHTRoot: common.HexToHash("0xe0a817ac69b36c1e437c5b0cff9e764853f5115702b5f66d451b665d6afb7e78"), @@ -169,13 +185,43 @@ var ( // used to start light syncing from this checkpoint and avoid downloading the // entire header chain while still being able to securely access old headers/logs. type TrustedCheckpoint struct { - Name string `json:"-"` SectionIndex uint64 `json:"sectionIndex"` SectionHead common.Hash `json:"sectionHead"` CHTRoot common.Hash `json:"chtRoot"` BloomRoot common.Hash `json:"bloomRoot"` } +// HashEqual returns an indicator comparing the itself hash with given one. +func (c *TrustedCheckpoint) HashEqual(hash common.Hash) bool { + if c.Empty() { + return hash == common.Hash{} + } + return c.Hash() == hash +} + +// Hash returns the hash of checkpoint's four key fields(index, sectionHead, chtRoot and bloomTrieRoot). +func (c *TrustedCheckpoint) Hash() common.Hash { + buf := make([]byte, 8+3*common.HashLength) + binary.BigEndian.PutUint64(buf, c.SectionIndex) + copy(buf[8:], c.SectionHead.Bytes()) + copy(buf[8+common.HashLength:], c.CHTRoot.Bytes()) + copy(buf[8+2*common.HashLength:], c.BloomRoot.Bytes()) + return crypto.Keccak256Hash(buf) +} + +// Empty returns an indicator whether the checkpoint is regarded as empty. +func (c *TrustedCheckpoint) Empty() bool { + return c.SectionHead == (common.Hash{}) || c.CHTRoot == (common.Hash{}) || c.BloomRoot == (common.Hash{}) +} + +// CheckpointOracleConfig represents a set of checkpoint contract(which acts as an oracle) +// config which used for light client checkpoint syncing. +type CheckpointOracleConfig struct { + Address common.Address `json:"address"` + Signers []common.Address `json:"signers"` + Threshold uint64 `json:"threshold"` +} + // ChainConfig is the core config which determines the blockchain settings. // // ChainConfig is stored in the database on a per block basis. This means diff --git a/params/network_params.go b/params/network_params.go index a949b84578..bba24721c1 100644 --- a/params/network_params.go +++ b/params/network_params.go @@ -47,6 +47,12 @@ const ( // is generated HelperTrieProcessConfirmations = 256 + // CheckpointFrequency is the block frequency for creating checkpoint + CheckpointFrequency = 32768 + + // CheckpointProcessConfirmations is the number before a checkpoint is generated + CheckpointProcessConfirmations = 256 + // ImmutabilityThreshold is the number of blocks after which a chain segment is // considered immutable (i.e. soft finality). It is used by the downloader as a // hard limit against deep ancestors, by the blockchain against deep reorgs, by