diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 6286617d05..7ac7915f22 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -16,8 +16,8 @@ light/ @zsfelfoldi @rjl493456442
mobile/ @karalabe @ligi
p2p/ @fjl @zsfelfoldi
rpc/ @fjl @holiman
-p2p/simulations @zelig @nonsense @janos @justelad
-p2p/protocols @zelig @nonsense @janos @justelad
-p2p/testing @zelig @nonsense @janos @justelad
+p2p/simulations @zelig @janos @justelad
+p2p/protocols @zelig @janos @justelad
+p2p/testing @zelig @janos @justelad
signer/ @holiman
whisper/ @gballet @gluk256
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index 326bb3edfe..5b07cbbcd6 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -25,7 +25,7 @@ jobs:
echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
- name: 'Run code linters'
run: |
- GO111MODULE=off make lint
+ GO111MODULE=on make lint
unit-tests:
name: 'Unit tests in ${{ matrix.os }}'
strategy:
diff --git a/.gitignore b/.gitignore
index 90cba95547..f1fcc40fa5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,6 +15,7 @@
*/**/*dapps*
build/_vendor/pkg
.idea
+*.iml
#*
.#*
@@ -25,6 +26,7 @@ build/_vendor/pkg
# used by the Makefile
/build/_workspace/
+/build/cache/
/build/bin/
/geth*.zip
diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 0000000000..44fce8bea3
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,45 @@
+# This file configures github.com/golangci/golangci-lint.
+
+run:
+ timeout: 2m
+ tests: true
+ # default is true. Enables skipping of directories:
+ # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
+ skip-dirs-use-default: true
+
+linters:
+ disable-all: true
+ enable:
+ - deadcode
+ - goconst
+ - goimports
+ - gosimple
+ - govet
+ - ineffassign
+ - misspell
+ # - staticcheck
+ - unconvert
+ # - unused
+ - varcheck
+
+linters-settings:
+ gofmt:
+ simplify: true
+ goconst:
+ min-len: 3 # minimum length of string constant
+ min-occurrences: 6 # minimum number of occurrences
+
+issues:
+ exclude-rules:
+ - path: crypto/blake2b/
+ linters:
+ - deadcode
+ - path: crypto/bn256/cloudflare
+ linters:
+ - deadcode
+ - path: p2p/discv5/
+ linters:
+ - deadcode
+ - path: core/vm/instructions_test.go
+ linters:
+ - goconst
diff --git a/.travis.yml b/.travis.yml
index 82aa5a9943..87fb4de166 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -19,6 +19,8 @@ jobs:
os: linux
dist: xenial
go: 1.11.x
+ env:
+ - GO111MODULE=on
script:
- go run build/ci.go install
- go run build/ci.go test -coverage $TEST_PACKAGES
@@ -27,6 +29,8 @@ jobs:
os: linux
dist: xenial
go: 1.12.x
+ env:
+ - GO111MODULE=on
script:
- go run build/ci.go install
- go run build/ci.go test -coverage $TEST_PACKAGES
diff --git a/Dockerfile b/Dockerfile
index 4a8f07877a..da99963d00 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -13,6 +13,5 @@ RUN apk add --no-cache ca-certificates
COPY --from=builder /go-ethereum/build/bin/geth /usr/local/bin/
COPY --from=builder /go-ethereum/build/bin/bootnode /usr/local/bin/
-
EXPOSE 8545 8546 8547 30303 30303/udp
ENTRYPOINT ["geth"]
diff --git a/Makefile b/Makefile
index f62ca2293b..620799ff97 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,9 @@ geth:
bootnode:
build/env.sh go run build/ci.go install ./cmd/bootnode
- @echo "Done building bootnode."
+ @echo "Done building."
+ @echo "Run \"$(GOBIN)/bootnode\" to launch bootnode."
+
all:
build/env.sh go run build/ci.go install
@@ -40,7 +42,7 @@ lint: ## Run linters.
build/env.sh go run build/ci.go lint
clean:
- ./build/clean_go_build_cache.sh
+ go clean -cache
rm -fr build/_workspace/pkg/ $(GOBIN)/*
# The devtools target installs tools required for 'go generate'.
diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go
index ca19c5801c..61ab70eb83 100644
--- a/accounts/abi/abi_test.go
+++ b/accounts/abi/abi_test.go
@@ -927,7 +927,7 @@ func TestABI_MethodById(t *testing.T) {
}
b := fmt.Sprintf("%v", m2)
if a != b {
- t.Errorf("Method %v (id %v) not 'findable' by id in ABI", name, common.ToHex(m.ID()))
+ t.Errorf("Method %v (id %x) not 'findable' by id in ABI", name, m.ID())
}
}
// Also test empty
diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go
index 7bda997a61..13ac286b45 100644
--- a/accounts/abi/bind/bind.go
+++ b/accounts/abi/bind/bind.go
@@ -47,13 +47,17 @@ const (
// to be used as is in client code, but rather as an intermediate struct which
// enforces compile time type safety and naming convention opposed to having to
// manually maintain hard coded strings that break on runtime.
-func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]string, pkg string, lang Lang, libs map[string]string) (string, error) {
- // Process each individual contract requested binding
- contracts := make(map[string]*tmplContract)
+func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]string, pkg string, lang Lang, libs map[string]string, aliases map[string]string) (string, error) {
+ var (
+ // contracts is the map of each individual contract requested binding
+ contracts = make(map[string]*tmplContract)
- // Map used to flag each encountered library as such
- isLib := make(map[string]struct{})
+ // structs is the map of all reclared structs shared by passed contracts.
+ structs = make(map[string]*tmplStruct)
+ // isLib is the map used to flag each encountered library as such
+ isLib = make(map[string]struct{})
+ )
for i := 0; i < len(types); i++ {
// Parse the actual ABI to generate the binding for
evmABI, err := abi.JSON(strings.NewReader(abis[i]))
@@ -73,13 +77,29 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]
calls = make(map[string]*tmplMethod)
transacts = make(map[string]*tmplMethod)
events = make(map[string]*tmplEvent)
- structs = make(map[string]*tmplStruct)
+
+ // identifiers are used to detect duplicated identifier of function
+ // and event. For all calls, transacts and events, abigen will generate
+ // corresponding bindings. However we have to ensure there is no
+ // identifier coliision in the bindings of these categories.
+ callIdentifiers = make(map[string]bool)
+ transactIdentifiers = make(map[string]bool)
+ eventIdentifiers = make(map[string]bool)
)
for _, original := range evmABI.Methods {
// Normalize the method for capital cases and non-anonymous inputs/outputs
normalized := original
- normalized.Name = methodNormalizer[lang](original.Name)
-
+ normalizedName := methodNormalizer[lang](alias(aliases, original.Name))
+ // Ensure there is no duplicated identifier
+ var identifiers = callIdentifiers
+ if !original.Const {
+ identifiers = transactIdentifiers
+ }
+ if identifiers[normalizedName] {
+ return "", fmt.Errorf("duplicated identifier \"%s\"(normalized \"%s\"), use --alias for renaming", original.Name, normalizedName)
+ }
+ identifiers[normalizedName] = true
+ normalized.Name = normalizedName
normalized.Inputs = make([]abi.Argument, len(original.Inputs))
copy(normalized.Inputs, original.Inputs)
for j, input := range normalized.Inputs {
@@ -114,7 +134,14 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]
}
// Normalize the event for capital cases and non-anonymous outputs
normalized := original
- normalized.Name = methodNormalizer[lang](original.Name)
+
+ // Ensure there is no duplicated identifier
+ normalizedName := methodNormalizer[lang](alias(aliases, original.Name))
+ if eventIdentifiers[normalizedName] {
+ return "", fmt.Errorf("duplicated identifier \"%s\"(normalized \"%s\"), use --alias for renaming", original.Name, normalizedName)
+ }
+ eventIdentifiers[normalizedName] = true
+ normalized.Name = normalizedName
normalized.Inputs = make([]abi.Argument, len(original.Inputs))
copy(normalized.Inputs, original.Inputs)
@@ -144,7 +171,6 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]
Transacts: transacts,
Events: events,
Libraries: make(map[string]string),
- Structs: structs,
}
// Function 4-byte signatures are stored in the same sequence
// as types, if available.
@@ -176,6 +202,7 @@ func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]
Package: pkg,
Contracts: contracts,
Libraries: libs,
+ Structs: structs,
}
buffer := new(bytes.Buffer)
@@ -483,6 +510,15 @@ func namedTypeJava(javaKind string, solKind abi.Type) string {
}
}
+// alias returns an alias of the given string based on the aliasing rules
+// or returns itself if no rule is matched.
+func alias(aliases map[string]string, n string) string {
+ if alias, exist := aliases[n]; exist {
+ return alias
+ }
+ return n
+}
+
// methodNormalizer is a name transformer that modifies Solidity method names to
// conform to target language naming concentions.
var methodNormalizer = map[Lang]func(string) string{
diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go
index 1db5682833..c2934d77ed 100644
--- a/accounts/abi/bind/bind_test.go
+++ b/accounts/abi/bind/bind_test.go
@@ -38,6 +38,7 @@ var bindTests = []struct {
tester string
fsigs []map[string]string
libs map[string]string
+ aliases map[string]string
types []string
}{
// Test that the binding is available in combined and separate forms too
@@ -61,6 +62,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Test that all the official sample contracts bind correctly
{
@@ -77,6 +79,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
{
`Crowdsale`,
@@ -92,6 +95,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
{
`DAO`,
@@ -107,6 +111,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Test that named and anonymous inputs are handled correctly
{
@@ -143,6 +148,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Test that named and anonymous outputs are handled correctly
{
@@ -182,6 +188,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that named, anonymous and indexed events are handled correctly
{
@@ -250,6 +257,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Test that contract interactions (deploy, transact and call) generate working code
{
@@ -311,6 +319,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that plain values can be properly returned and deserialized
{
@@ -356,6 +365,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that tuples can be properly returned and deserialized
{
@@ -401,6 +411,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that arrays/slices can be properly returned and deserialized.
// Only addresses are tested, remainder just compiled to keep the test small.
@@ -458,6 +469,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that anonymous default methods can be correctly invoked
{
@@ -508,6 +520,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that non-existent contracts are reported as such (though only simulator test)
{
@@ -547,6 +560,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that gas estimation works for contracts with weird gas mechanics too.
{
@@ -602,6 +616,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Test that constant functions can be called from an (optional) specified address
{
@@ -655,6 +670,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that methods and returns with underscores inside work correctly.
{
@@ -734,6 +750,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
// Tests that logs can be successfully filtered and decoded.
{
@@ -955,6 +972,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
{
`DeeplyNestedArray`,
@@ -1035,6 +1053,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
{
`CallbackParam`,
@@ -1076,6 +1095,7 @@ var bindTests = []struct {
},
nil,
nil,
+ nil,
}, {
`Tuple`,
`
@@ -1219,6 +1239,7 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
},
{
`UseLibrary`,
@@ -1287,6 +1308,7 @@ var bindTests = []struct {
map[string]string{
"b98c933f0a6ececcd167bd4f9d3299b1a0": "Math",
},
+ nil,
[]string{"UseLibrary", "Math"},
}, {
"Overload",
@@ -1298,7 +1320,7 @@ var bindTests = []struct {
event bar(uint256 i);
event bar(uint256 i, uint256 j);
-
+
function foo(uint256 i) public {
emit bar(i);
}
@@ -1381,6 +1403,132 @@ var bindTests = []struct {
nil,
nil,
nil,
+ nil,
+ },
+ {
+ "IdentifierCollision",
+ `
+ pragma solidity >=0.4.19 <0.6.0;
+
+ contract IdentifierCollision {
+ uint public _myVar;
+
+ function MyVar() public view returns (uint) {
+ return _myVar;
+ }
+ }
+ `,
+ []string{"60806040523480156100115760006000fd5b50610017565b60c3806100256000396000f3fe608060405234801560105760006000fd5b506004361060365760003560e01c806301ad4d8714603c5780634ef1f0ad146058576036565b60006000fd5b60426074565b6040518082815260200191505060405180910390f35b605e607d565b6040518082815260200191505060405180910390f35b60006000505481565b60006000600050549050608b565b9056fea265627a7a7231582067c8d84688b01c4754ba40a2a871cede94ea1f28b5981593ab2a45b46ac43af664736f6c634300050c0032"},
+ []string{`[{"constant":true,"inputs":[],"name":"MyVar","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_myVar","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]`},
+ `
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/accounts/abi/bind"
+ "github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/core"
+ `,
+ `
+ // Initialize test accounts
+ key, _ := crypto.GenerateKey()
+ addr := crypto.PubkeyToAddress(key.PublicKey)
+
+ // Deploy registrar contract
+ sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(1000000000)}}, 10000000)
+ defer sim.Close()
+
+ transactOpts := bind.NewKeyedTransactor(key)
+ _, _, _, err := DeployIdentifierCollision(transactOpts, sim)
+ if err != nil {
+ t.Fatalf("failed to deploy contract: %v", err)
+ }
+ `,
+ nil,
+ nil,
+ map[string]string{"_myVar": "pubVar"}, // alias MyVar to PubVar
+ nil,
+ },
+ {
+ "MultiContracts",
+ `
+ pragma solidity ^0.5.11;
+ pragma experimental ABIEncoderV2;
+
+ library ExternalLib {
+ struct SharedStruct{
+ uint256 f1;
+ bytes32 f2;
+ }
+ }
+
+ contract ContractOne {
+ function foo(ExternalLib.SharedStruct memory s) pure public {
+ // Do stuff
+ }
+ }
+
+ contract ContractTwo {
+ function bar(ExternalLib.SharedStruct memory s) pure public {
+ // Do stuff
+ }
+ }
+ `,
+ []string{
+ `60806040523480156100115760006000fd5b50610017565b6101b5806100266000396000f3fe60806040523480156100115760006000fd5b50600436106100305760003560e01c80639d8a8ba81461003657610030565b60006000fd5b610050600480360361004b91908101906100d1565b610052565b005b5b5056610171565b6000813590506100698161013d565b92915050565b6000604082840312156100825760006000fd5b61008c60406100fb565b9050600061009c848285016100bc565b60008301525060206100b08482850161005a565b60208301525092915050565b6000813590506100cb81610157565b92915050565b6000604082840312156100e45760006000fd5b60006100f28482850161006f565b91505092915050565b6000604051905081810181811067ffffffffffffffff8211171561011f5760006000fd5b8060405250919050565b6000819050919050565b6000819050919050565b61014681610129565b811415156101545760006000fd5b50565b61016081610133565b8114151561016e5760006000fd5b50565bfea365627a7a72315820749274eb7f6c01010d5322af4e1668b0a154409eb7968bd6cae5524c7ed669bb6c6578706572696d656e74616cf564736f6c634300050c0040`,
+ `60806040523480156100115760006000fd5b50610017565b6101b5806100266000396000f3fe60806040523480156100115760006000fd5b50600436106100305760003560e01c8063db8ba08c1461003657610030565b60006000fd5b610050600480360361004b91908101906100d1565b610052565b005b5b5056610171565b6000813590506100698161013d565b92915050565b6000604082840312156100825760006000fd5b61008c60406100fb565b9050600061009c848285016100bc565b60008301525060206100b08482850161005a565b60208301525092915050565b6000813590506100cb81610157565b92915050565b6000604082840312156100e45760006000fd5b60006100f28482850161006f565b91505092915050565b6000604051905081810181811067ffffffffffffffff8211171561011f5760006000fd5b8060405250919050565b6000819050919050565b6000819050919050565b61014681610129565b811415156101545760006000fd5b50565b61016081610133565b8114151561016e5760006000fd5b50565bfea365627a7a723158209bc28ee7ea97c131a13330d77ec73b4493b5c59c648352da81dd288b021192596c6578706572696d656e74616cf564736f6c634300050c0040`,
+ `606c6026600b82828239805160001a6073141515601857fe5b30600052607381538281f350fe73000000000000000000000000000000000000000030146080604052600436106023575b60006000fdfea365627a7a72315820518f0110144f5b3de95697d05e456a064656890d08e6f9cff47f3be710cc46a36c6578706572696d656e74616cf564736f6c634300050c0040`,
+ },
+ []string{
+ `[{"constant":true,"inputs":[{"components":[{"internalType":"uint256","name":"f1","type":"uint256"},{"internalType":"bytes32","name":"f2","type":"bytes32"}],"internalType":"struct ExternalLib.SharedStruct","name":"s","type":"tuple"}],"name":"foo","outputs":[],"payable":false,"stateMutability":"pure","type":"function"}]`,
+ `[{"constant":true,"inputs":[{"components":[{"internalType":"uint256","name":"f1","type":"uint256"},{"internalType":"bytes32","name":"f2","type":"bytes32"}],"internalType":"struct ExternalLib.SharedStruct","name":"s","type":"tuple"}],"name":"bar","outputs":[],"payable":false,"stateMutability":"pure","type":"function"}]`,
+ `[]`,
+ },
+ `
+ "math/big"
+
+ "github.com/ethereum/go-ethereum/accounts/abi/bind"
+ "github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/core"
+ `,
+ `
+ key, _ := crypto.GenerateKey()
+ addr := crypto.PubkeyToAddress(key.PublicKey)
+
+ // Deploy registrar contract
+ sim := backends.NewSimulatedBackend(core.GenesisAlloc{addr: {Balance: big.NewInt(1000000000)}}, 10000000)
+ defer sim.Close()
+
+ transactOpts := bind.NewKeyedTransactor(key)
+ _, _, c1, err := DeployContractOne(transactOpts, sim)
+ if err != nil {
+ t.Fatal("Failed to deploy contract")
+ }
+ sim.Commit()
+ err = c1.Foo(nil, ExternalLibSharedStruct{
+ F1: big.NewInt(100),
+ F2: [32]byte{0x01, 0x02, 0x03},
+ })
+ if err != nil {
+ t.Fatal("Failed to invoke function")
+ }
+ _, _, c2, err := DeployContractTwo(transactOpts, sim)
+ if err != nil {
+ t.Fatal("Failed to deploy contract")
+ }
+ sim.Commit()
+ err = c2.Bar(nil, ExternalLibSharedStruct{
+ F1: big.NewInt(100),
+ F2: [32]byte{0x01, 0x02, 0x03},
+ })
+ if err != nil {
+ t.Fatal("Failed to invoke function")
+ }
+ `,
+ nil,
+ nil,
+ nil,
+ []string{"ContractOne", "ContractTwo", "ExternalLib"},
},
}
@@ -1412,7 +1560,7 @@ func TestGolangBindings(t *testing.T) {
types = []string{tt.name}
}
// Generate the binding and create a Go source file in the workspace
- bind, err := Bind(types, tt.abi, tt.bytecode, tt.fsigs, "bindtest", LangGo, tt.libs)
+ bind, err := Bind(types, tt.abi, tt.bytecode, tt.fsigs, "bindtest", LangGo, tt.libs, tt.aliases)
if err != nil {
t.Fatalf("test %d: failed to generate binding: %v", i, err)
}
@@ -1436,6 +1584,25 @@ func TestGolangBindings(t *testing.T) {
t.Fatalf("test %d: failed to write tests: %v", i, err)
}
}
+ // Convert the package to go modules and use the current source for go-ethereum
+ moder := exec.Command(gocmd, "mod", "init", "bindtest")
+ moder.Dir = pkg
+ if out, err := moder.CombinedOutput(); err != nil {
+ t.Fatalf("failed to convert binding test to modules: %v\n%s", err, out)
+ }
+ pwd, _ := os.Getwd()
+ replacer := exec.Command(gocmd, "mod", "edit", "-replace", "github.com/ethereum/go-ethereum="+filepath.Join(pwd, "..", "..", "..")) // Repo root
+ replacer.Dir = pkg
+ if out, err := replacer.CombinedOutput(); err != nil {
+ t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out)
+ }
+ // Quorum - add package github.com/jpmorganchase/quorum/crypto/secp256k1 that is defined as a standalone module
+ secp256Replacer := exec.Command(gocmd, "mod", "edit", "-replace", "github.com/ethereum/go-ethereum/crypto/secp256k1=github.com/jpmorganchase/quorum/crypto/secp256k1@v0.0.0-20200804194033-c8f07379f487") // Repo root
+ secp256Replacer.Dir = pkg
+ if out, err := secp256Replacer.CombinedOutput(); err != nil {
+ t.Fatalf("failed to replace binding test dependency to current source tree: %v\n%s", err, out)
+ }
+
// Test the entire package and report any failures
cmd := exec.Command(gocmd, "test", "-v", "-count", "1")
cmd.Dir = pkg
@@ -1835,7 +2002,7 @@ public class Test {
},
}
for i, c := range cases {
- binding, err := Bind([]string{c.name}, []string{c.abi}, []string{c.bytecode}, nil, "bindtest", LangJava, nil)
+ binding, err := Bind([]string{c.name}, []string{c.abi}, []string{c.bytecode}, nil, "bindtest", LangJava, nil, nil)
if err != nil {
t.Fatalf("test %d: failed to generate binding: %v", i, err)
}
diff --git a/accounts/abi/bind/template.go b/accounts/abi/bind/template.go
index 80040442ce..79d302b0d8 100644
--- a/accounts/abi/bind/template.go
+++ b/accounts/abi/bind/template.go
@@ -23,6 +23,7 @@ type tmplData struct {
Package string // Name of the package to place the generated file in
Contracts map[string]*tmplContract // List of contracts to generate into this file
Libraries map[string]string // Map the bytecode's link pattern to the library name
+ Structs map[string]*tmplStruct // Contract struct type definitions
}
// tmplContract contains the data needed to generate an individual contract binding.
@@ -36,8 +37,7 @@ type tmplContract struct {
Transacts map[string]*tmplMethod // Contract calls that write state data
Events map[string]*tmplEvent // Contract events accessors
Libraries map[string]string // Same as tmplData, but filtered to only keep what the contract needs
- Structs map[string]*tmplStruct // Contract struct type definitions
- Library bool
+ Library bool // Indicator whether the contract is a library
}
// tmplMethod is a wrapper around an abi.Method that contains a few preprocessed
@@ -108,8 +108,16 @@ var (
_ = event.NewSubscription
)
+{{$structs := .Structs}}
+{{range $structs}}
+ // {{.Name}} is an auto generated low-level Go binding around an user-defined struct.
+ type {{.Name}} struct {
+ {{range $field := .Fields}}
+ {{$field.Name}} {{$field.Type}}{{end}}
+ }
+{{end}}
+
{{range $contract := .Contracts}}
- {{$structs := $contract.Structs}}
// {{.Type}}ABI is the input ABI used to generate the binding from.
const {{.Type}}ABI = "{{.InputABI}}"
@@ -287,14 +295,6 @@ var (
return _{{$contract.Type}}.Contract.contract.Transact(opts, method, params...)
}
- {{range .Structs}}
- // {{.Name}} is an auto generated low-level Go binding around an user-defined struct.
- type {{.Name}} struct {
- {{range $field := .Fields}}
- {{$field.Name}} {{$field.Type}}{{end}}
- }
- {{end}}
-
{{range .Calls}}
// {{.Normalized.Name}} is a free data retrieval call binding the contract method 0x{{printf "%x" .Original.ID}}.
//
@@ -510,8 +510,8 @@ package {{.Package}};
import org.ethereum.geth.*;
import java.util.*;
+{{$structs := .Structs}}
{{range $contract := .Contracts}}
-{{$structs := $contract.Structs}}
{{if not .Library}}public {{end}}class {{.Type}} {
// ABI is the input ABI used to generate the binding from.
public final static String ABI = "{{.InputABI}}";
diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go
index 792e26762e..090b9217db 100644
--- a/accounts/abi/event_test.go
+++ b/accounts/abi/event_test.go
@@ -173,7 +173,7 @@ func TestEventTupleUnpack(t *testing.T) {
type EventTransferWithTag struct {
// this is valid because `value` is not exportable,
// so value is only unmarshalled into `Value1`.
- value *big.Int
+ value *big.Int //lint:ignore U1000 unused field is part of test
Value1 *big.Int `abi:"value"`
}
@@ -354,40 +354,6 @@ func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, ass
return a.Unpack(dest, "e", data)
}
-/*
-Taken from
-https://github.com/ethereum/go-ethereum/pull/15568
-*/
-
-type testResult struct {
- Values [2]*big.Int
- Value1 *big.Int
- Value2 *big.Int
-}
-
-type testCase struct {
- definition string
- want testResult
-}
-
-func (tc testCase) encoded(intType, arrayType Type) []byte {
- var b bytes.Buffer
- if tc.want.Value1 != nil {
- val, _ := intType.pack(reflect.ValueOf(tc.want.Value1))
- b.Write(val)
- }
-
- if !reflect.DeepEqual(tc.want.Values, [2]*big.Int{nil, nil}) {
- val, _ := arrayType.pack(reflect.ValueOf(tc.want.Values))
- b.Write(val)
- }
- if tc.want.Value2 != nil {
- val, _ := intType.pack(reflect.ValueOf(tc.want.Value2))
- b.Write(val)
- }
- return b.Bytes()
-}
-
// TestEventUnpackIndexed verifies that indexed field will be skipped by event decoder.
func TestEventUnpackIndexed(t *testing.T) {
definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8"},{"indexed": false, "name":"value2", "type":"uint8"}]}]`
diff --git a/accounts/keystore/passphrase.go b/accounts/keystore/passphrase.go
index 1ced41e997..89cdf0bfca 100644
--- a/accounts/keystore/passphrase.go
+++ b/accounts/keystore/passphrase.go
@@ -123,6 +123,7 @@ func (ks keyStorePassphrase) StoreKey(filename string, key *Key, auth string) er
"Please file a ticket at:\n\n" +
"https://github.com/ethereum/go-ethereum/issues." +
"The error was : %s"
+ //lint:ignore ST1005 This is a message for the user
return fmt.Errorf(msg, tmpName, err)
}
}
@@ -237,7 +238,7 @@ func DecryptKey(keyjson []byte, auth string) (*Key, error) {
func DecryptDataV3(cryptoJson CryptoJSON, auth string) ([]byte, error) {
if cryptoJson.Cipher != "aes-128-ctr" {
- return nil, fmt.Errorf("Cipher not supported: %v", cryptoJson.Cipher)
+ return nil, fmt.Errorf("cipher not supported: %v", cryptoJson.Cipher)
}
mac, err := hex.DecodeString(cryptoJson.MAC)
if err != nil {
@@ -273,7 +274,7 @@ func DecryptDataV3(cryptoJson CryptoJSON, auth string) ([]byte, error) {
func decryptKeyV3(keyProtected *encryptedKeyJSONV3, auth string) (keyBytes []byte, keyId []byte, err error) {
if keyProtected.Version != version {
- return nil, nil, fmt.Errorf("Version not supported: %v", keyProtected.Version)
+ return nil, nil, fmt.Errorf("version not supported: %v", keyProtected.Version)
}
keyId = uuid.Parse(keyProtected.Id)
plainText, err := DecryptDataV3(keyProtected.Crypto, auth)
@@ -335,13 +336,13 @@ func getKDFKey(cryptoJSON CryptoJSON, auth string) ([]byte, error) {
c := ensureInt(cryptoJSON.KDFParams["c"])
prf := cryptoJSON.KDFParams["prf"].(string)
if prf != "hmac-sha256" {
- return nil, fmt.Errorf("Unsupported PBKDF2 PRF: %s", prf)
+ return nil, fmt.Errorf("unsupported PBKDF2 PRF: %s", prf)
}
key := pbkdf2.Key(authArray, salt, c, dkLen, sha256.New)
return key, nil
}
- return nil, fmt.Errorf("Unsupported KDF: %s", cryptoJSON.KDF)
+ return nil, fmt.Errorf("unsupported KDF: %s", cryptoJSON.KDF)
}
// TODO: can we do without this when unmarshalling dynamic JSON?
diff --git a/build/checksums.txt b/build/checksums.txt
new file mode 100644
index 0000000000..bb814e3392
--- /dev/null
+++ b/build/checksums.txt
@@ -0,0 +1,19 @@
+# This file contains sha256 checksums of optional build dependencies.
+
+95dbeab442ee2746b9acf0934c8e2fc26414a0565c008631b04addb8c02e7624 go1.13.4.src.tar.gz
+
+1fcbc9e36f4319eeed02beb8cfd1b3d425ffc2f90ddf09a80f18d5064c51e0cb golangci-lint-1.21.0-linux-386.tar.gz
+267b4066e67139a38d29499331a002d6a29ad5be7aafc83db3b1e88f1b027f90 golangci-lint-1.21.0-linux-armv6.tar.gz
+a602c1f25f90e46e621019cff0a8cb3f4e1837011f3537f15e730d6a9ebf507b golangci-lint-1.21.0-freebsd-armv7.tar.gz
+2c861f8dc56b560474aa27cab0c075991628cc01af3451e27ac82f5d10d5106b golangci-lint-1.21.0-linux-amd64.tar.gz
+a1c39e055280e755acaa906e7abfc20b99a5c28be8af541c57fbc44abbb20dde golangci-lint-1.21.0-linux-arm64.tar.gz
+a8f8bda8c6a4136acf858091077830b1e83ad5612606cb69d5dced869ce00bd8 golangci-lint-1.21.0-linux-ppc64le.tar.gz
+0a8a8c3bc660ccbca668897ab520f7ee9878f16cc8e4dd24fe46236ceec97ba3 golangci-lint-1.21.0-freebsd-armv6.tar.gz
+699b07f45e216571f54002bcbd83b511c4801464a422162158e299587b095b18 golangci-lint-1.21.0-freebsd-amd64.tar.gz
+980fb4993942154bb5c8129ea3b86de09574fe81b24384ebb58cd7a9d2f04483 golangci-lint-1.21.0-linux-armv7.tar.gz
+f15b689088a47f20d5d3c1d945e9ee7c6238f2b84ea468b5f886cf8713dce62e golangci-lint-1.21.0-windows-386.zip
+2e40ded7adcf11e59013cb15c24438b15a86526ca241edfcfdf1abd73a5280a8 golangci-lint-1.21.0-windows-amd64.zip
+6052c7cfea4d6dc2fc722f6c12792a5ec087420198db495afffbc22052653bf7 golangci-lint-1.21.0-freebsd-386.tar.gz
+ca00b8eacf9af14a71b908b4149606c762aa5c0eac781e74ca0abedfdfdf6c8c golangci-lint-1.21.0-linux-s390x.tar.gz
+1365455940c342f95718159d89d66ad2eef19f0846c3e87023e915a3527b929f golangci-lint-1.21.0-darwin-386.tar.gz
+2b2713ec5007e67883aa501eebb81f22abfab0cf0909134ba90f60a066db3760 golangci-lint-1.21.0-darwin-amd64.tar.gz
diff --git a/build/ci.go b/build/ci.go
index 434e6d1fb9..73d1efa0dd 100644
--- a/build/ci.go
+++ b/build/ci.go
@@ -58,7 +58,7 @@ import (
"strings"
"time"
- "github.com/ethereum/go-ethereum/common/hexutil"
+ "github.com/cespare/cp"
"github.com/ethereum/go-ethereum/internal/build"
"github.com/ethereum/go-ethereum/params"
)
@@ -229,6 +229,9 @@ func doInstall(cmdline []string) {
if *arch == "" || *arch == runtime.GOARCH {
goinstall := goTool("install", buildFlags(env)...)
+ if runtime.GOARCH == "arm64" {
+ goinstall.Args = append(goinstall.Args, "-p", "1")
+ }
goinstall.Args = append(goinstall.Args, "-v")
goinstall.Args = append(goinstall.Args, packages...)
build.MustRun(goinstall)
@@ -241,6 +244,7 @@ func doInstall(cmdline []string) {
os.RemoveAll(filepath.Join(path, "pkg", runtime.GOOS+"_arm"))
}
}
+
// Seems we are cross compiling, work around forbidden GOBIN
goinstall := goToolArch(*arch, *cc, "install", buildFlags(env)...)
goinstall.Args = append(goinstall.Args, "-v")
@@ -315,6 +319,7 @@ func goToolArch(arch string, cc string, subcmd string, args ...string) *exec.Cmd
func doTest(cmdline []string) {
coverage := flag.Bool("coverage", false, "Whether to record code coverage")
+ verbose := flag.Bool("v", false, "Whether to log verbosely")
flag.CommandLine.Parse(cmdline)
env := build.Env()
@@ -335,44 +340,46 @@ func doTest(cmdline []string) {
if *coverage {
gotest.Args = append(gotest.Args, "-covermode=atomic", "-cover")
}
+ if *verbose {
+ gotest.Args = append(gotest.Args, "-v")
+ }
gotest.Args = append(gotest.Args, packages...)
build.MustRun(gotest)
}
-// runs gometalinter on requested packages
+// doLint runs golangci-lint on requested packages.
func doLint(cmdline []string) {
+ var (
+ cachedir = flag.String("cachedir", "./build/cache", "directory for caching golangci-lint binary.")
+ )
flag.CommandLine.Parse(cmdline)
-
packages := []string{"./..."}
if len(flag.CommandLine.Args()) > 0 {
packages = flag.CommandLine.Args()
}
- // Get metalinter and install all supported linters
- build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
- build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")
-
- // Run fast linters batched together
- configs := []string{
- "--vendor",
- "--tests",
- "--deadline=2m",
- "--disable-all",
- "--enable=goimports",
- "--enable=varcheck",
- "--enable=vet",
- "--enable=gofmt",
- "--enable=misspell",
- "--enable=goconst",
- "--min-occurrences=6", // for goconst
- }
- build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
-
- // Run slow linters one by one
- for _, linter := range []string{"unconvert", "gosimple"} {
- configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
- build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
+
+ linter := downloadLinter(*cachedir)
+ lflags := []string{"run", "--config", ".golangci.yml"}
+ build.MustRunCommand(linter, append(lflags, packages...)...)
+ fmt.Println("You have achieved perfection.")
+}
+
+// downloadLinter downloads and unpacks golangci-lint.
+func downloadLinter(cachedir string) string {
+ const version = "1.21.0"
+
+ csdb := build.MustLoadChecksums("build/checksums.txt")
+ base := fmt.Sprintf("golangci-lint-%s-%s-%s", version, runtime.GOOS, runtime.GOARCH)
+ url := fmt.Sprintf("https://github.com/golangci/golangci-lint/releases/download/v%s/%s.tar.gz", version, base)
+ archivePath := filepath.Join(cachedir, base+".tar.gz")
+ if err := csdb.DownloadFile(url, archivePath); err != nil {
+ log.Fatal(err)
+ }
+ if err := build.ExtractTarballArchive(archivePath, cachedir); err != nil {
+ log.Fatal(err)
}
+ return filepath.Join(cachedir, base, "golangci-lint")
}
// Release Packaging
@@ -476,8 +483,7 @@ func maybeSkipArchive(env build.Environment) {
func doDebianSource(cmdline []string) {
var (
goversion = flag.String("goversion", "", `Go version to build with (will be included in the source package)`)
- gobundle = flag.String("gobundle", "/tmp/go.tar.gz", `Filesystem path to cache the downloaded Go bundles at`)
- gohash = flag.String("gohash", "", `SHA256 checksum of the Go sources requested to build with`)
+ cachedir = flag.String("cachedir", "./build/cache", `Filesystem path to cache the downloaded Go bundles at`)
signer = flag.String("signer", "", `Signing key name, also used as package author`)
upload = flag.String("upload", "", `Where to upload the source package (usually "ethereum/ethereum")`)
sshUser = flag.String("sftp-user", "", `Username for SFTP upload (usually "geth-ci")`)
@@ -495,26 +501,40 @@ func doDebianSource(cmdline []string) {
gpg.Stdin = bytes.NewReader(key)
build.MustRun(gpg)
}
- // Download and verify the Go source package
- if err := build.EnsureGoSources(*goversion, hexutil.MustDecode("0x"+*gohash), *gobundle); err != nil {
- log.Fatalf("Failed to ensure Go source package: %v", err)
- }
- // Create Debian packages and upload them
+
+ // Download and verify the Go source package.
+ gobundle := downloadGoSources(*goversion, *cachedir)
+
+ // Download all the dependencies needed to build the sources and run the ci script
+ srcdepfetch := goTool("install", "-n", "./...")
+ srcdepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
+ build.MustRun(srcdepfetch)
+
+ cidepfetch := goTool("run", "./build/ci.go")
+ cidepfetch.Env = append(os.Environ(), "GOPATH="+filepath.Join(*workdir, "modgopath"))
+ cidepfetch.Run() // Command fails, don't care, we only need the deps to start it
+
+ // Create Debian packages and upload them.
for _, pkg := range debPackages {
for distro, goboot := range debDistroGoBoots {
- // Prepare the debian package with the go-ethereum sources
+ // Prepare the debian package with the go-ethereum sources.
meta := newDebMetadata(distro, goboot, *signer, env, now, pkg.Name, pkg.Version, pkg.Executables)
pkgdir := stageDebianSource(*workdir, meta)
- // Ship the Go sources along so we have a proper thing to build with
- if err := build.ExtractTarballArchive(*gobundle, pkgdir); err != nil {
+ // Add Go source code
+ if err := build.ExtractTarballArchive(gobundle, pkgdir); err != nil {
log.Fatalf("Failed to extract Go sources: %v", err)
}
if err := os.Rename(filepath.Join(pkgdir, "go"), filepath.Join(pkgdir, ".go")); err != nil {
log.Fatalf("Failed to rename Go source folder: %v", err)
}
+ // Add all dependency modules in compressed form
+ os.MkdirAll(filepath.Join(pkgdir, ".mod", "cache"), 0755)
+ if err := cp.CopyAll(filepath.Join(pkgdir, ".mod", "cache", "download"), filepath.Join(*workdir, "modgopath", "pkg", "mod", "cache", "download")); err != nil {
+ log.Fatalf("Failed to copy Go module dependencies: %v", err)
+ }
// Run the packaging and upload to the PPA
- debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz")
+ debuild := exec.Command("debuild", "-S", "-sa", "-us", "-uc", "-d", "-Zxz", "-nc")
debuild.Dir = pkgdir
build.MustRun(debuild)
@@ -534,6 +554,17 @@ func doDebianSource(cmdline []string) {
}
}
+func downloadGoSources(version string, cachedir string) string {
+ csdb := build.MustLoadChecksums("build/checksums.txt")
+ file := fmt.Sprintf("go%s.src.tar.gz", version)
+ url := "https://dl.google.com/go/" + file
+ dst := filepath.Join(cachedir, file)
+ if err := csdb.DownloadFile(url, dst); err != nil {
+ log.Fatal(err)
+ }
+ return dst
+}
+
func ppaUpload(workdir, ppa, sshUser string, files []string) {
p := strings.Split(ppa, "/")
if len(p) != 2 {
@@ -767,9 +798,12 @@ func doWindowsInstaller(cmdline []string) {
build.Render("build/nsis.uninstall.nsh", filepath.Join(*workdir, "uninstall.nsh"), 0644, allTools)
build.Render("build/nsis.pathupdate.nsh", filepath.Join(*workdir, "PathUpdate.nsh"), 0644, nil)
build.Render("build/nsis.envvarupdate.nsh", filepath.Join(*workdir, "EnvVarUpdate.nsh"), 0644, nil)
- build.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll", 0755)
- build.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING", 0755)
-
+ if err := cp.CopyFile(filepath.Join(*workdir, "SimpleFC.dll"), "build/nsis.simplefc.dll"); err != nil {
+ log.Fatal("Failed to copy SimpleFC.dll: %v", err)
+ }
+ if err := cp.CopyFile(filepath.Join(*workdir, "COPYING"), "COPYING"); err != nil {
+ log.Fatal("Failed to copy copyright note: %v", err)
+ }
// Build the installer. This assumes that all the needed files have been previously
// built (don't mix building and packaging to keep cross compilation complexity to a
// minimum).
@@ -786,7 +820,6 @@ func doWindowsInstaller(cmdline []string) {
"/DARCH="+*arch,
filepath.Join(*workdir, "geth.nsi"),
)
-
// Sign and publish installer.
if err := archiveUpload(installer, *upload, *signer); err != nil {
log.Fatal(err)
@@ -1047,16 +1080,11 @@ func doXgo(cmdline []string) {
func xgoTool(args []string) *exec.Cmd {
cmd := exec.Command(filepath.Join(GOBIN, "xgo"), args...)
- cmd.Env = []string{
+ cmd.Env = os.Environ()
+ cmd.Env = append(cmd.Env, []string{
"GOPATH=" + build.GOPATH(),
"GOBIN=" + GOBIN,
- }
- for _, e := range os.Environ() {
- if strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
- continue
- }
- cmd.Env = append(cmd.Env, e)
- }
+ }...)
return cmd
}
diff --git a/build/clean_go_build_cache.sh b/build/clean_go_build_cache.sh
deleted file mode 100755
index 1666381d98..0000000000
--- a/build/clean_go_build_cache.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/sh
-
-# Cleaning the Go cache only makes sense if we actually have Go installed... or
-# if Go is actually callable. This does not hold true during deb packaging, so
-# we need an explicit check to avoid build failures.
-if ! command -v go > /dev/null; then
- exit
-fi
-
-version_gt() {
- test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"
-}
-
-golang_version=$(go version |cut -d' ' -f3 |sed 's/go//')
-
-# Clean go build cache when go version is greater than or equal to 1.10
-if !(version_gt 1.10 $golang_version); then
- go clean -cache
-fi
diff --git a/build/deb/ethereum/deb.rules b/build/deb/ethereum/deb.rules
index 1370a52f1e..983b87af16 100644
--- a/build/deb/ethereum/deb.rules
+++ b/build/deb/ethereum/deb.rules
@@ -4,13 +4,25 @@
# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
-# Launchpad rejects Go's access to $HOME/.cache, use custom folder
+# Launchpad rejects Go's access to $HOME, use custom folders
export GOCACHE=/tmp/go-build
export GOROOT_BOOTSTRAP={{.GoBootPath}}
+override_dh_auto_clean:
+ # Don't try to be smart Launchpad, we know our build rules better than you
+
override_dh_auto_build:
- (cd .go/src && ./make.bash)
- build/env.sh .go/bin/go run build/ci.go install -git-commit={{.Env.Commit}} -git-branch={{.Env.Branch}} -git-tag={{.Env.Tag}} -buildnum={{.Env.Buildnum}} -pull-request={{.Env.IsPullRequest}}
+ # We can't download a fresh Go within Launchpad, so we're shipping and building
+ # one on the fly. However, we can't build it inside the go-ethereum folder as
+ # bootstrapping clashes with go modules, so build in a sibling folder.
+ (mv .go ../ && cd ../.go/src && ./make.bash)
+
+ # We can't download external go modules within Launchpad, so we're shipping the
+ # entire dependency source cache with go-ethereum.
+ (mkdir -p build/_workspace/pkg/mod && mv .mod/* build/_workspace/pkg/mod)
+
+ # A fresh Go was built, all dependency downloads faked, hope build works now
+ build/env.sh ../.go/bin/go run build/ci.go install -git-commit={{.Env.Commit}} -git-branch={{.Env.Branch}} -git-tag={{.Env.Tag}} -buildnum={{.Env.Buildnum}} -pull-request={{.Env.IsPullRequest}}
override_dh_auto_test:
diff --git a/cmd/abigen/main.go b/cmd/abigen/main.go
index 7698115008..659cf1b4c5 100644
--- a/cmd/abigen/main.go
+++ b/cmd/abigen/main.go
@@ -21,6 +21,7 @@ import (
"fmt"
"io/ioutil"
"os"
+ "regexp"
"strings"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
@@ -103,6 +104,10 @@ var (
Usage: "Destination language for the bindings (go, java, objc)",
Value: "go",
}
+ aliasFlag = cli.StringFlag{
+ Name: "alias",
+ Usage: "Comma separated aliases for function and event renaming, e.g. foo=bar",
+ }
)
func init() {
@@ -120,6 +125,7 @@ func init() {
pkgFlag,
outFlag,
langFlag,
+ aliasFlag,
}
app.Action = utils.MigrateFlags(abigen)
cli.CommandHelpTemplate = commandHelperTemplate
@@ -144,11 +150,12 @@ func abigen(c *cli.Context) error {
}
// If the entire solidity code was specified, build and bind based on that
var (
- abis []string
- bins []string
- types []string
- sigs []map[string]string
- libs = make(map[string]string)
+ abis []string
+ bins []string
+ types []string
+ sigs []map[string]string
+ libs = make(map[string]string)
+ aliases = make(map[string]string)
)
if c.GlobalString(abiFlag.Name) != "" {
// Load up the ABI, optional bytecode and type name from the parameters
@@ -232,8 +239,20 @@ func abigen(c *cli.Context) error {
libs[libPattern] = nameParts[len(nameParts)-1]
}
}
+ // Extract all aliases from the flags
+ if c.GlobalIsSet(aliasFlag.Name) {
+ // We support multi-versions for aliasing
+ // e.g.
+ // foo=bar,foo2=bar2
+ // foo:bar,foo2:bar2
+ re := regexp.MustCompile(`(?:(\w+)[:=](\w+))`)
+ submatches := re.FindAllStringSubmatch(c.GlobalString(aliasFlag.Name), -1)
+ for _, match := range submatches {
+ aliases[match[1]] = match[2]
+ }
+ }
// Generate the contract binding
- code, err := bind.Bind(types, abis, bins, sigs, c.GlobalString(pkgFlag.Name), lang, libs)
+ code, err := bind.Bind(types, abis, bins, sigs, c.GlobalString(pkgFlag.Name), lang, libs, aliases)
if err != nil {
utils.Fatalf("Failed to generate ABI binding: %v", err)
}
diff --git a/cmd/clef/main.go b/cmd/clef/main.go
index 326e3ed0a2..d81aae6007 100644
--- a/cmd/clef/main.go
+++ b/cmd/clef/main.go
@@ -403,7 +403,7 @@ func initialize(c *cli.Context) error {
if c.GlobalBool(stdiouiFlag.Name) {
logOutput = os.Stderr
// If using the stdioui, we can't do the 'confirm'-flow
- fmt.Fprintf(logOutput, legalWarning)
+ fmt.Fprint(logOutput, legalWarning)
} else {
if !confirm(legalWarning) {
return fmt.Errorf("aborted by user")
@@ -645,7 +645,7 @@ func signer(c *cli.Context) error {
},
})
- abortChan := make(chan os.Signal)
+ abortChan := make(chan os.Signal, 1)
signal.Notify(abortChan, os.Interrupt)
sig := <-abortChan
@@ -802,7 +802,7 @@ func checkFile(filename string) error {
// confirm displays a text and asks for user confirmation
func confirm(text string) bool {
- fmt.Printf(text)
+ fmt.Print(text)
fmt.Printf("\nEnter 'ok' to proceed:\n> ")
text, err := bufio.NewReader(os.Stdin).ReadString('\n')
@@ -868,21 +868,19 @@ func testExternalUI(api *core.SignerAPI) {
api.UI.ShowInfo("Please approve the next request for signing a clique header")
time.Sleep(delay)
cliqueHeader := types.Header{
- common.HexToHash("0000H45H"),
- common.HexToHash("0000H45H"),
- common.HexToAddress("0000H45H"),
- common.HexToHash("0000H00H"),
- common.HexToHash("0000H45H"),
- common.HexToHash("0000H45H"),
- types.Bloom{},
- big.NewInt(1337),
- big.NewInt(1337),
- 1338,
- 1338,
- 1338,
- []byte("Extra data Extra data Extra data Extra data Extra data Extra data Extra data Extra data"),
- common.HexToHash("0x0000H45H"),
- types.BlockNonce{},
+ ParentHash: common.HexToHash("0000H45H"),
+ UncleHash: common.HexToHash("0000H45H"),
+ Coinbase: common.HexToAddress("0000H45H"),
+ Root: common.HexToHash("0000H00H"),
+ TxHash: common.HexToHash("0000H45H"),
+ ReceiptHash: common.HexToHash("0000H45H"),
+ Difficulty: big.NewInt(1337),
+ Number: big.NewInt(1337),
+ GasLimit: 1338,
+ GasUsed: 1338,
+ Time: 1338,
+ Extra: []byte("Extra data Extra data Extra data Extra data Extra data Extra data Extra data Extra data"),
+ MixDigest: common.HexToHash("0x0000H45H"),
}
cliqueRlp, err := rlp.EncodeToBytes(cliqueHeader)
if err != nil {
@@ -1035,7 +1033,7 @@ func GenDoc(ctx *cli.Context) {
if data, err := json.MarshalIndent(v, "", " "); err == nil {
output = append(output, fmt.Sprintf("### %s\n\n%s\n\nExample:\n```json\n%s\n```", name, desc, data))
} else {
- log.Error("Error generating output", "err", err)
+ log.Error("Error generating output", err)
}
}
)
@@ -1046,7 +1044,7 @@ func GenDoc(ctx *cli.Context) {
"of the work in canonicalizing and making sense of the data, and it's up to the UI to present" +
"the user with the contents of the `message`"
sighash, msg := accounts.TextAndHash([]byte("hello world"))
- messages := []*core.NameValueType{{"message", msg, accounts.MimetypeTextPlain}}
+ messages := []*core.NameValueType{{Name: "message", Value: msg, Typ: accounts.MimetypeTextPlain}}
add("SignDataRequest", desc, &core.SignDataRequest{
Address: common.NewMixedcaseAddress(a),
@@ -1077,8 +1075,8 @@ func GenDoc(ctx *cli.Context) {
add("SignTxRequest", desc, &core.SignTxRequest{
Meta: meta,
Callinfo: []core.ValidationInfo{
- {"Warning", "Something looks odd, show this message as a warning"},
- {"Info", "User should see this aswell"},
+ {Typ: "Warning", Message: "Something looks odd, show this message as a warning"},
+ {Typ: "Info", Message: "User should see this as well"},
},
Transaction: core.SendTxArgs{
Data: &data,
@@ -1144,16 +1142,21 @@ func GenDoc(ctx *cli.Context) {
&core.ListRequest{
Meta: meta,
Accounts: []accounts.Account{
- {a, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/a"}},
- {b, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}},
+ {Address: a, URL: accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/a"}},
+ {Address: b, URL: accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}},
})
add("ListResponse", "Response to list request. The response contains a list of all addresses to show to the caller. "+
"Note: the UI is free to respond with any address the caller, regardless of whether it exists or not",
&core.ListResponse{
Accounts: []accounts.Account{
- {common.HexToAddress("0xcowbeef000000cowbeef00000000000000000c0w"), accounts.URL{Path: ".. ignored .."}},
- {common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff"), accounts.URL{}},
+ {
+ Address: common.HexToAddress("0xcowbeef000000cowbeef00000000000000000c0w"),
+ URL: accounts.URL{Path: ".. ignored .."},
+ },
+ {
+ Address: common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff"),
+ },
}})
}
diff --git a/cmd/ethkey/changepassword.go b/cmd/ethkey/changepassword.go
index 5689c26618..32fde4ed6d 100644
--- a/cmd/ethkey/changepassword.go
+++ b/cmd/ethkey/changepassword.go
@@ -77,7 +77,7 @@ Change the password of a keyfile.`,
}
// Then write the new keyfile in place of the old one.
- if err := ioutil.WriteFile(keyfilepath, newJson, 600); err != nil {
+ if err := ioutil.WriteFile(keyfilepath, newJson, 0600); err != nil {
utils.Fatalf("Error writing new keyfile to disk: %v", err)
}
diff --git a/cmd/evm/main.go b/cmd/evm/main.go
index a5159c6b7e..5b8b950ab0 100644
--- a/cmd/evm/main.go
+++ b/cmd/evm/main.go
@@ -79,6 +79,10 @@ var (
Name: "input",
Usage: "input for the EVM",
}
+ InputFileFlag = cli.StringFlag{
+ Name: "inputfile",
+ Usage: "file containing input for the EVM",
+ }
VerbosityFlag = cli.IntFlag{
Name: "verbosity",
Usage: "sets the verbosity level",
@@ -130,6 +134,7 @@ func init() {
ValueFlag,
DumpFlag,
InputFlag,
+ InputFileFlag,
MemProfileFlag,
CPUProfileFlag,
StatDumpFlag,
diff --git a/cmd/evm/runner.go b/cmd/evm/runner.go
index 3cbdcad017..cecbf36063 100644
--- a/cmd/evm/runner.go
+++ b/cmd/evm/runner.go
@@ -205,14 +205,24 @@ func runCmd(ctx *cli.Context) error {
}
tstart := time.Now()
var leftOverGas uint64
+ var hexInput []byte
+ if inputFileFlag := ctx.GlobalString(InputFileFlag.Name); inputFileFlag != "" {
+ if hexInput, err = ioutil.ReadFile(inputFileFlag); err != nil {
+ fmt.Printf("could not load input from file: %v\n", err)
+ os.Exit(1)
+ }
+ } else {
+ hexInput = []byte(ctx.GlobalString(InputFlag.Name))
+ }
+ input := common.FromHex(string(bytes.TrimSpace(hexInput)))
if ctx.GlobalBool(CreateFlag.Name) {
- input := append(code, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name))...)
+ input = append(code, input...)
ret, _, leftOverGas, err = runtime.Create(input, &runtimeConfig)
} else {
if len(code) > 0 {
statedb.SetCode(receiver, code)
}
- ret, leftOverGas, err = runtime.Call(receiver, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)), &runtimeConfig)
+ ret, leftOverGas, err = runtime.Call(receiver, input, &runtimeConfig)
}
execTime := time.Since(tstart)
diff --git a/cmd/faucet/faucet.go b/cmd/faucet/faucet.go
index 6786849816..27b87f22f1 100644
--- a/cmd/faucet/faucet.go
+++ b/cmd/faucet/faucet.go
@@ -60,7 +60,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/ethereum/go-ethereum/params"
- "golang.org/x/net/websocket"
+ "github.com/gorilla/websocket"
)
var (
@@ -298,8 +298,7 @@ func (f *faucet) listenAndServe(port int) error {
go f.loop()
http.HandleFunc("/", f.webHandler)
- http.Handle("/api", websocket.Handler(f.apiHandler))
-
+ http.HandleFunc("/api", f.apiHandler)
return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
@@ -310,7 +309,13 @@ func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
}
// apiHandler handles requests for Ether grants and transaction statuses.
-func (f *faucet) apiHandler(conn *websocket.Conn) {
+func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
+ upgrader := websocket.Upgrader{}
+ conn, err := upgrader.Upgrade(w, r, nil)
+ if err != nil {
+ return
+ }
+
// Start tracking the connection and drop at the end
defer conn.Close()
@@ -333,7 +338,6 @@ func (f *faucet) apiHandler(conn *websocket.Conn) {
head *types.Header
balance *big.Int
nonce uint64
- err error
)
for head == nil || balance == nil {
// Retrieve the current stats cached by the faucet
@@ -378,7 +382,7 @@ func (f *faucet) apiHandler(conn *websocket.Conn) {
Tier uint `json:"tier"`
Captcha string `json:"captcha"`
}
- if err = websocket.JSON.Receive(conn, &msg); err != nil {
+ if err = conn.ReadJSON(&msg); err != nil {
return
}
if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") &&
@@ -659,7 +663,7 @@ func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error
timeout = 60 * time.Second
}
conn.SetWriteDeadline(time.Now().Add(timeout))
- return websocket.JSON.Send(conn, value)
+ return conn.WriteJSON(value)
}
// sendError transmits an error to the remote end of the websocket, also setting
diff --git a/cmd/geth/config.go b/cmd/geth/config.go
index be7d7cfc49..c0ffa0817b 100644
--- a/cmd/geth/config.go
+++ b/cmd/geth/config.go
@@ -26,7 +26,6 @@ import (
"unicode"
"github.com/ethereum/go-ethereum/cmd/utils"
- "github.com/ethereum/go-ethereum/dashboard"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node"
@@ -77,11 +76,10 @@ type ethstatsConfig struct {
}
type gethConfig struct {
- Eth eth.Config
- Shh whisper.Config
- Node node.Config
- Ethstats ethstatsConfig
- Dashboard dashboard.Config
+ Eth eth.Config
+ Shh whisper.Config
+ Node node.Config
+ Ethstats ethstatsConfig
}
func loadConfig(file string, cfg *gethConfig) error {
@@ -112,10 +110,9 @@ func defaultNodeConfig() node.Config {
func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
// Load defaults.
cfg := gethConfig{
- Eth: eth.DefaultConfig,
- Shh: whisper.DefaultConfig,
- Node: defaultNodeConfig(),
- Dashboard: dashboard.DefaultConfig,
+ Eth: eth.DefaultConfig,
+ Shh: whisper.DefaultConfig,
+ Node: defaultNodeConfig(),
}
// Load config file.
@@ -136,7 +133,6 @@ func makeConfigNode(ctx *cli.Context) (*node.Node, gethConfig) {
cfg.Ethstats.URL = ctx.GlobalString(utils.EthStatsURLFlag.Name)
}
utils.SetShhConfig(ctx, stack, &cfg.Shh)
- utils.SetDashboardConfig(ctx, &cfg.Dashboard)
return stack, cfg
}
@@ -173,10 +169,6 @@ func makeFullNode(ctx *cli.Context) *node.Node {
utils.RegisterRaftService(stack, ctx, &cfg.Node, ethChan)
}
- if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
- utils.RegisterDashboardService(stack, &cfg.Dashboard, gitCommit)
- }
-
ipcPath := quorumGetPrivateTransactionManager()
if ipcPath != "" {
utils.RegisterExtensionService(stack, ethChan)
diff --git a/cmd/geth/consolecmd.go b/cmd/geth/consolecmd.go
index c2f50e661b..4d4cb13162 100644
--- a/cmd/geth/consolecmd.go
+++ b/cmd/geth/consolecmd.go
@@ -279,12 +279,12 @@ func dialRPC(endpoint string, ctx *cli.Context) (*rpc.Client, error) {
Transport: http.DefaultTransport,
}
customHttpClient.Transport.(*http.Transport).TLSClientConfig = tlsConfig
- client, err = rpc.DialHTTPWithClient(endpoint, customHttpClient)
+ client, _ = rpc.DialHTTPWithClient(endpoint, customHttpClient)
case "wss":
- client, err = rpc.DialWebsocketWithCustomTLS(dialCtx, endpoint, "", tlsConfig)
+ client, _ = rpc.DialWebsocketWithCustomTLS(dialCtx, endpoint, "", tlsConfig)
default:
log.Warn("unsupported scheme for custom TLS which is only for HTTPS/WSS", "scheme", u.Scheme)
- client, err = rpc.DialContext(dialCtx, endpoint)
+ client, _ = rpc.DialContext(dialCtx, endpoint)
}
} else {
client, err = rpc.DialContext(dialCtx, endpoint)
diff --git a/cmd/geth/main.go b/cmd/geth/main.go
index fe8fd1d2d9..29219f3695 100644
--- a/cmd/geth/main.go
+++ b/cmd/geth/main.go
@@ -46,7 +46,7 @@ import (
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/permission"
"github.com/ethereum/go-ethereum/plugin"
- "gopkg.in/urfave/cli.v1"
+ cli "gopkg.in/urfave/cli.v1"
)
const (
@@ -74,10 +74,6 @@ var (
utils.NoUSBFlag,
utils.SmartCardDaemonPathFlag,
utils.OverrideIstanbulFlag,
- utils.DashboardEnabledFlag,
- utils.DashboardAddrFlag,
- utils.DashboardPortFlag,
- utils.DashboardRefreshFlag,
utils.EthashCacheDirFlag,
utils.EthashCachesInMemoryFlag,
utils.EthashCachesOnDiskFlag,
@@ -259,16 +255,8 @@ func init() {
app.Flags = append(app.Flags, metricsFlags...)
app.Before = func(ctx *cli.Context) error {
- logdir := ""
- if ctx.GlobalBool(utils.DashboardEnabledFlag.Name) {
- logdir = (&node.Config{DataDir: utils.MakeDataDir(ctx)}).ResolvePath("logs")
- }
- if err := debug.Setup(ctx, logdir); err != nil {
- return err
- }
- return nil
+ return debug.Setup(ctx, "")
}
-
app.After = func(ctx *cli.Context) error {
debug.Exit()
console.Stdin.Close() // Resets terminal mode.
diff --git a/cmd/geth/retesteth.go b/cmd/geth/retesteth.go
index 4f2ed71bf4..078e2c3e85 100644
--- a/cmd/geth/retesteth.go
+++ b/cmd/geth/retesteth.go
@@ -644,7 +644,7 @@ func (api *RetestethAPI) AccountRange(ctx context.Context,
var err error
if parentHeader == nil || int(txIndex) >= len(block.Transactions()) {
root = header.Root
- statedb, pvtst, err = api.blockchain.StateAt(root)
+ statedb, _, err = api.blockchain.StateAt(root)
if err != nil {
return AccountRangeResult{}, err
}
@@ -757,7 +757,7 @@ func (api *RetestethAPI) StorageRangeAt(ctx context.Context,
var err error
if parentHeader == nil || int(txIndex) >= len(block.Transactions()) {
root = header.Root
- statedb, pvtstdb, err = api.blockchain.StateAt(root)
+ statedb, _, err = api.blockchain.StateAt(root)
if err != nil {
return StorageRangeResult{}, err
}
diff --git a/cmd/geth/usage.go b/cmd/geth/usage.go
index 04af6b1b57..33278d1245 100644
--- a/cmd/geth/usage.go
+++ b/cmd/geth/usage.go
@@ -21,7 +21,6 @@ package main
import (
"io"
"sort"
- "strings"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/internal/debug"
@@ -117,16 +116,6 @@ var AppHelpFlagGroups = []flagGroup{
utils.EthashDatasetsOnDiskFlag,
},
},
- //{
- // Name: "DASHBOARD",
- // Flags: []cli.Flag{
- // utils.DashboardEnabledFlag,
- // utils.DashboardAddrFlag,
- // utils.DashboardPortFlag,
- // utils.DashboardRefreshFlag,
- // utils.DashboardAssetsFlag,
- // },
- //},
{
Name: "TRANSACTION POOL",
Flags: []cli.Flag{
@@ -370,9 +359,6 @@ func init() {
var uncategorized []cli.Flag
for _, flag := range data.(*cli.App).Flags {
if _, ok := categorized[flag.String()]; !ok {
- if strings.HasPrefix(flag.GetName(), "dashboard") {
- continue
- }
uncategorized = append(uncategorized, flag)
}
}
diff --git a/cmd/puppeth/genesis.go b/cmd/puppeth/genesis.go
index 44ad6c4cd4..b3e1709dbf 100644
--- a/cmd/puppeth/genesis.go
+++ b/cmd/puppeth/genesis.go
@@ -17,7 +17,6 @@
package main
import (
- "encoding/binary"
"errors"
"math"
"math/big"
@@ -28,6 +27,7 @@ import (
math2 "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
)
@@ -60,14 +60,14 @@ type alethGenesisSpec struct {
} `json:"params"`
Genesis struct {
- Nonce hexutil.Bytes `json:"nonce"`
- Difficulty *hexutil.Big `json:"difficulty"`
- MixHash common.Hash `json:"mixHash"`
- Author common.Address `json:"author"`
- Timestamp hexutil.Uint64 `json:"timestamp"`
- ParentHash common.Hash `json:"parentHash"`
- ExtraData hexutil.Bytes `json:"extraData"`
- GasLimit hexutil.Uint64 `json:"gasLimit"`
+ Nonce types.BlockNonce `json:"nonce"`
+ Difficulty *hexutil.Big `json:"difficulty"`
+ MixHash common.Hash `json:"mixHash"`
+ Author common.Address `json:"author"`
+ Timestamp hexutil.Uint64 `json:"timestamp"`
+ ParentHash common.Hash `json:"parentHash"`
+ ExtraData hexutil.Bytes `json:"extraData"`
+ GasLimit hexutil.Uint64 `json:"gasLimit"`
} `json:"genesis"`
Accounts map[common.UnprefixedAddress]*alethGenesisSpecAccount `json:"accounts"`
@@ -146,9 +146,7 @@ func newAlethGenesisSpec(network string, genesis *core.Genesis) (*alethGenesisSp
spec.Params.DurationLimit = (*math2.HexOrDecimal256)(params.DurationLimit)
spec.Params.BlockReward = (*hexutil.Big)(ethash.FrontierBlockReward)
- spec.Genesis.Nonce = (hexutil.Bytes)(make([]byte, 8))
- binary.LittleEndian.PutUint64(spec.Genesis.Nonce[:], genesis.Nonce)
-
+ spec.Genesis.Nonce = types.EncodeNonce(genesis.Nonce)
spec.Genesis.MixHash = genesis.Mixhash
spec.Genesis.Difficulty = (*hexutil.Big)(genesis.Difficulty)
spec.Genesis.Author = genesis.Coinbase
@@ -278,8 +276,8 @@ type parityChainSpec struct {
Genesis struct {
Seal struct {
Ethereum struct {
- Nonce hexutil.Bytes `json:"nonce"`
- MixHash hexutil.Bytes `json:"mixHash"`
+ Nonce types.BlockNonce `json:"nonce"`
+ MixHash hexutil.Bytes `json:"mixHash"`
} `json:"ethereum"`
} `json:"seal"`
@@ -305,19 +303,20 @@ type parityChainSpecAccount struct {
// parityChainSpecBuiltin is the precompiled contract definition.
type parityChainSpecBuiltin struct {
- Name string `json:"name"` // Each builtin should has it own name
- Pricing *parityChainSpecPricing `json:"pricing"` // Each builtin should has it own price strategy
- ActivateAt *hexutil.Big `json:"activate_at,omitempty"` // ActivateAt can't be omitted if empty, default means no fork
- EIP1108Transition *hexutil.Big `json:"eip1108_transition,omitempty"` // EIP1108Transition can't be omitted if empty, default means no fork
+ Name string `json:"name"` // Each builtin should has it own name
+ Pricing interface{} `json:"pricing"` // Each builtin should has it own price strategy
+ ActivateAt *hexutil.Big `json:"activate_at,omitempty"` // ActivateAt can't be omitted if empty, default means no fork
}
// parityChainSpecPricing represents the different pricing models that builtin
// contracts might advertise using.
type parityChainSpecPricing struct {
- Linear *parityChainSpecLinearPricing `json:"linear,omitempty"`
- ModExp *parityChainSpecModExpPricing `json:"modexp,omitempty"`
- AltBnPairing *parityChainSpecAltBnPairingPricing `json:"alt_bn128_pairing,omitempty"`
- AltBnConstOperation *parityChainSpecAltBnConstOperationPricing `json:"alt_bn128_const_operations,omitempty"`
+ Linear *parityChainSpecLinearPricing `json:"linear,omitempty"`
+ ModExp *parityChainSpecModExpPricing `json:"modexp,omitempty"`
+
+ // Before the https://github.com/paritytech/parity-ethereum/pull/11039,
+ // Parity uses this format to config bn pairing price policy.
+ AltBnPairing *parityChainSepcAltBnPairingPricing `json:"alt_bn128_pairing,omitempty"`
// Blake2F is the price per round of Blake2 compression
Blake2F *parityChainSpecBlakePricing `json:"blake2_f,omitempty"`
@@ -332,22 +331,36 @@ type parityChainSpecModExpPricing struct {
Divisor uint64 `json:"divisor"`
}
+// parityChainSpecAltBnConstOperationPricing defines the price
+// policy for bn const operation(used after istanbul)
type parityChainSpecAltBnConstOperationPricing struct {
- Price uint64 `json:"price"`
- EIP1108TransitionPrice uint64 `json:"eip1108_transition_price,omitempty"` // Before Istanbul fork, this field is nil
+ Price uint64 `json:"price"`
}
-type parityChainSpecAltBnPairingPricing struct {
- Base uint64 `json:"base"`
- Pair uint64 `json:"pair"`
- EIP1108TransitionBase uint64 `json:"eip1108_transition_base,omitempty"` // Before Istanbul fork, this field is nil
- EIP1108TransitionPair uint64 `json:"eip1108_transition_pair,omitempty"` // Before Istanbul fork, this field is nil
+// parityChainSepcAltBnPairingPricing defines the price policy
+// for bn pairing.
+type parityChainSepcAltBnPairingPricing struct {
+ Base uint64 `json:"base"`
+ Pair uint64 `json:"pair"`
}
+// parityChainSpecBlakePricing defines the price policy for blake2 f
+// compression.
type parityChainSpecBlakePricing struct {
GasPerRound uint64 `json:"gas_per_round"`
}
+type parityChainSpecAlternativePrice struct {
+ AltBnConstOperationPrice *parityChainSpecAltBnConstOperationPricing `json:"alt_bn128_const_operations,omitempty"`
+ AltBnPairingPrice *parityChainSepcAltBnPairingPricing `json:"alt_bn128_pairing,omitempty"`
+}
+
+// parityChainSpecVersionedPricing represents a single version price policy.
+type parityChainSpecVersionedPricing struct {
+ Price *parityChainSpecAlternativePrice `json:"price,omitempty"`
+ Info string `json:"info,omitempty"`
+}
+
// newParityChainSpec converts a go-ethereum genesis block into a Parity specific
// chain specification format.
func newParityChainSpec(network string, genesis *core.Genesis, bootnodes []string) (*parityChainSpec, error) {
@@ -411,10 +424,8 @@ func newParityChainSpec(network string, genesis *core.Genesis, bootnodes []strin
// Disable this one
spec.Params.EIP98Transition = math.MaxInt64
- spec.Genesis.Seal.Ethereum.Nonce = (hexutil.Bytes)(make([]byte, 8))
- binary.LittleEndian.PutUint64(spec.Genesis.Seal.Ethereum.Nonce[:], genesis.Nonce)
-
- spec.Genesis.Seal.Ethereum.MixHash = (hexutil.Bytes)(genesis.Mixhash[:])
+ spec.Genesis.Seal.Ethereum.Nonce = types.EncodeNonce(genesis.Nonce)
+ spec.Genesis.Seal.Ethereum.MixHash = (genesis.Mixhash[:])
spec.Genesis.Difficulty = (*hexutil.Big)(genesis.Difficulty)
spec.Genesis.Author = genesis.Coinbase
spec.Genesis.Timestamp = (hexutil.Uint64)(genesis.Timestamp)
@@ -445,16 +456,32 @@ func newParityChainSpec(network string, genesis *core.Genesis, bootnodes []strin
})
if genesis.Config.ByzantiumBlock != nil {
spec.setPrecompile(5, &parityChainSpecBuiltin{
- Name: "modexp", ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock), Pricing: &parityChainSpecPricing{ModExp: &parityChainSpecModExpPricing{Divisor: 20}},
+ Name: "modexp",
+ ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock),
+ Pricing: &parityChainSpecPricing{
+ ModExp: &parityChainSpecModExpPricing{Divisor: 20},
+ },
})
spec.setPrecompile(6, &parityChainSpecBuiltin{
- Name: "alt_bn128_add", ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock), Pricing: &parityChainSpecPricing{AltBnConstOperation: &parityChainSpecAltBnConstOperationPricing{Price: 500}},
+ Name: "alt_bn128_add",
+ ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock),
+ Pricing: &parityChainSpecPricing{
+ Linear: &parityChainSpecLinearPricing{Base: 500, Word: 0},
+ },
})
spec.setPrecompile(7, &parityChainSpecBuiltin{
- Name: "alt_bn128_mul", ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock), Pricing: &parityChainSpecPricing{AltBnConstOperation: &parityChainSpecAltBnConstOperationPricing{Price: 40000}},
+ Name: "alt_bn128_mul",
+ ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock),
+ Pricing: &parityChainSpecPricing{
+ Linear: &parityChainSpecLinearPricing{Base: 40000, Word: 0},
+ },
})
spec.setPrecompile(8, &parityChainSpecBuiltin{
- Name: "alt_bn128_pairing", ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock), Pricing: &parityChainSpecPricing{AltBnPairing: &parityChainSpecAltBnPairingPricing{Base: 100000, Pair: 80000}},
+ Name: "alt_bn128_pairing",
+ ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock),
+ Pricing: &parityChainSpecPricing{
+ AltBnPairing: &parityChainSepcAltBnPairingPricing{Base: 100000, Pair: 80000},
+ },
})
}
if genesis.Config.IstanbulBlock != nil {
@@ -462,16 +489,59 @@ func newParityChainSpec(network string, genesis *core.Genesis, bootnodes []strin
return nil, errors.New("invalid genesis, istanbul fork is enabled while byzantium is not")
}
spec.setPrecompile(6, &parityChainSpecBuiltin{
- Name: "alt_bn128_add", ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock), EIP1108Transition: (*hexutil.Big)(genesis.Config.IstanbulBlock), Pricing: &parityChainSpecPricing{AltBnConstOperation: &parityChainSpecAltBnConstOperationPricing{Price: 500, EIP1108TransitionPrice: 150}},
+ Name: "alt_bn128_add",
+ ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock),
+ Pricing: map[*hexutil.Big]*parityChainSpecVersionedPricing{
+ (*hexutil.Big)(big.NewInt(0)): {
+ Price: &parityChainSpecAlternativePrice{
+ AltBnConstOperationPrice: &parityChainSpecAltBnConstOperationPricing{Price: 500},
+ },
+ },
+ (*hexutil.Big)(genesis.Config.IstanbulBlock): {
+ Price: &parityChainSpecAlternativePrice{
+ AltBnConstOperationPrice: &parityChainSpecAltBnConstOperationPricing{Price: 150},
+ },
+ },
+ },
})
spec.setPrecompile(7, &parityChainSpecBuiltin{
- Name: "alt_bn128_mul", ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock), EIP1108Transition: (*hexutil.Big)(genesis.Config.IstanbulBlock), Pricing: &parityChainSpecPricing{AltBnConstOperation: &parityChainSpecAltBnConstOperationPricing{Price: 40000, EIP1108TransitionPrice: 6000}},
+ Name: "alt_bn128_mul",
+ ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock),
+ Pricing: map[*hexutil.Big]*parityChainSpecVersionedPricing{
+ (*hexutil.Big)(big.NewInt(0)): {
+ Price: &parityChainSpecAlternativePrice{
+ AltBnConstOperationPrice: &parityChainSpecAltBnConstOperationPricing{Price: 40000},
+ },
+ },
+ (*hexutil.Big)(genesis.Config.IstanbulBlock): {
+ Price: &parityChainSpecAlternativePrice{
+ AltBnConstOperationPrice: &parityChainSpecAltBnConstOperationPricing{Price: 6000},
+ },
+ },
+ },
})
spec.setPrecompile(8, &parityChainSpecBuiltin{
- Name: "alt_bn128_pairing", ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock), EIP1108Transition: (*hexutil.Big)(genesis.Config.IstanbulBlock), Pricing: &parityChainSpecPricing{AltBnPairing: &parityChainSpecAltBnPairingPricing{Base: 100000, Pair: 80000, EIP1108TransitionBase: 45000, EIP1108TransitionPair: 34000}},
+ Name: "alt_bn128_pairing",
+ ActivateAt: (*hexutil.Big)(genesis.Config.ByzantiumBlock),
+ Pricing: map[*hexutil.Big]*parityChainSpecVersionedPricing{
+ (*hexutil.Big)(big.NewInt(0)): {
+ Price: &parityChainSpecAlternativePrice{
+ AltBnPairingPrice: &parityChainSepcAltBnPairingPricing{Base: 100000, Pair: 80000},
+ },
+ },
+ (*hexutil.Big)(genesis.Config.IstanbulBlock): {
+ Price: &parityChainSpecAlternativePrice{
+ AltBnPairingPrice: &parityChainSepcAltBnPairingPricing{Base: 45000, Pair: 34000},
+ },
+ },
+ },
})
spec.setPrecompile(9, &parityChainSpecBuiltin{
- Name: "blake2_f", ActivateAt: (*hexutil.Big)(genesis.Config.IstanbulBlock), Pricing: &parityChainSpecPricing{Blake2F: &parityChainSpecBlakePricing{GasPerRound: 1}},
+ Name: "blake2_f",
+ ActivateAt: (*hexutil.Big)(genesis.Config.IstanbulBlock),
+ Pricing: &parityChainSpecPricing{
+ Blake2F: &parityChainSpecBlakePricing{GasPerRound: 1},
+ },
})
}
return spec, nil
@@ -514,8 +584,6 @@ func (spec *parityChainSpec) setConstantinopleFix(num *big.Int) {
}
func (spec *parityChainSpec) setIstanbul(num *big.Int) {
- // spec.Params.EIP152Transition = hexutil.Uint64(num.Uint64())
- // spec.Params.EIP1108Transition = hexutil.Uint64(num.Uint64())
spec.Params.EIP1344Transition = hexutil.Uint64(num.Uint64())
spec.Params.EIP1884Transition = hexutil.Uint64(num.Uint64())
spec.Params.EIP2028Transition = hexutil.Uint64(num.Uint64())
@@ -525,7 +593,7 @@ func (spec *parityChainSpec) setIstanbul(num *big.Int) {
// pyEthereumGenesisSpec represents the genesis specification format used by the
// Python Ethereum implementation.
type pyEthereumGenesisSpec struct {
- Nonce hexutil.Bytes `json:"nonce"`
+ Nonce types.BlockNonce `json:"nonce"`
Timestamp hexutil.Uint64 `json:"timestamp"`
ExtraData hexutil.Bytes `json:"extraData"`
GasLimit hexutil.Uint64 `json:"gasLimit"`
@@ -544,6 +612,7 @@ func newPyEthereumGenesisSpec(network string, genesis *core.Genesis) (*pyEthereu
return nil, errors.New("unsupported consensus engine")
}
spec := &pyEthereumGenesisSpec{
+ Nonce: types.EncodeNonce(genesis.Nonce),
Timestamp: (hexutil.Uint64)(genesis.Timestamp),
ExtraData: genesis.ExtraData,
GasLimit: (hexutil.Uint64)(genesis.GasLimit),
@@ -553,8 +622,5 @@ func newPyEthereumGenesisSpec(network string, genesis *core.Genesis) (*pyEthereu
Alloc: genesis.Alloc,
ParentHash: genesis.ParentHash,
}
- spec.Nonce = (hexutil.Bytes)(make([]byte, 8))
- binary.LittleEndian.PutUint64(spec.Nonce[:], genesis.Nonce)
-
return spec, nil
}
diff --git a/cmd/puppeth/genesis_test.go b/cmd/puppeth/genesis_test.go
index 3bbebe1929..45937d06d3 100644
--- a/cmd/puppeth/genesis_test.go
+++ b/cmd/puppeth/genesis_test.go
@@ -17,6 +17,7 @@
package main
import (
+ "bytes"
"encoding/json"
"io/ioutil"
"reflect"
@@ -88,29 +89,15 @@ func TestParitySturebyConverter(t *testing.T) {
if err != nil {
t.Fatalf("failed creating chainspec: %v", err)
}
-
+ enc, err := json.MarshalIndent(spec, "", " ")
+ if err != nil {
+ t.Fatalf("failed encoding chainspec: %v", err)
+ }
expBlob, err := ioutil.ReadFile("testdata/stureby_parity.json")
if err != nil {
t.Fatalf("could not read file: %v", err)
}
- expspec := &parityChainSpec{}
- if err := json.Unmarshal(expBlob, expspec); err != nil {
- t.Fatalf("failed parsing genesis: %v", err)
- }
- expspec.Nodes = []string{}
-
- if !reflect.DeepEqual(expspec, spec) {
- t.Errorf("chainspec mismatch")
- c := spew.ConfigState{
- DisablePointerAddresses: true,
- SortKeys: true,
- }
- exp := strings.Split(c.Sdump(expspec), "\n")
- got := strings.Split(c.Sdump(spec), "\n")
- for i := 0; i < len(exp) && i < len(got); i++ {
- if exp[i] != got[i] {
- t.Logf("got: %v\nexp: %v\n", exp[i], got[i])
- }
- }
+ if !bytes.Equal(expBlob, enc) {
+ t.Fatalf("chainspec mismatch")
}
}
diff --git a/cmd/puppeth/ssh.go b/cmd/puppeth/ssh.go
index c507596065..da2862db2f 100644
--- a/cmd/puppeth/ssh.go
+++ b/cmd/puppeth/ssh.go
@@ -129,15 +129,20 @@ func dial(server string, pubkey []byte) (*sshClient, error) {
fmt.Printf("SSH key fingerprint is %s [MD5]\n", ssh.FingerprintLegacyMD5(key))
fmt.Printf("Are you sure you want to continue connecting (yes/no)? ")
- text, err := bufio.NewReader(os.Stdin).ReadString('\n')
- switch {
- case err != nil:
- return err
- case strings.TrimSpace(text) == "yes":
- pubkey = key.Marshal()
- return nil
- default:
- return fmt.Errorf("unknown auth choice: %v", text)
+ for {
+ text, err := bufio.NewReader(os.Stdin).ReadString('\n')
+ switch {
+ case err != nil:
+ return err
+ case strings.TrimSpace(text) == "yes":
+ pubkey = key.Marshal()
+ return nil
+ case strings.TrimSpace(text) == "no":
+ return errors.New("users says no")
+ default:
+ fmt.Println("Please answer 'yes' or 'no'")
+ continue
+ }
}
}
// If a public key exists for this SSH server, check that it matches
diff --git a/cmd/puppeth/testdata/stureby_parity.json b/cmd/puppeth/testdata/stureby_parity.json
index fb84b39e22..e9229f99b7 100644
--- a/cmd/puppeth/testdata/stureby_parity.json
+++ b/cmd/puppeth/testdata/stureby_parity.json
@@ -131,13 +131,22 @@
"builtin": {
"name": "alt_bn128_add",
"pricing": {
- "alt_bn128_const_operations": {
- "price": 500,
- "eip1108_transition_price": 150
+ "0x0": {
+ "price": {
+ "alt_bn128_const_operations": {
+ "price": 500
+ }
+ }
+ },
+ "0xc350": {
+ "price": {
+ "alt_bn128_const_operations": {
+ "price": 150
+ }
+ }
}
},
- "activate_at": "0x7530",
- "eip1108_transition": "0xc350"
+ "activate_at": "0x7530"
}
},
"0000000000000000000000000000000000000007": {
@@ -145,13 +154,22 @@
"builtin": {
"name": "alt_bn128_mul",
"pricing": {
- "alt_bn128_const_operations": {
- "price": 40000,
- "eip1108_transition_price": 6000
+ "0x0": {
+ "price": {
+ "alt_bn128_const_operations": {
+ "price": 40000
+ }
+ }
+ },
+ "0xc350": {
+ "price": {
+ "alt_bn128_const_operations": {
+ "price": 6000
+ }
+ }
}
},
- "activate_at": "0x7530",
- "eip1108_transition": "0xc350"
+ "activate_at": "0x7530"
}
},
"0000000000000000000000000000000000000008": {
@@ -159,15 +177,24 @@
"builtin": {
"name": "alt_bn128_pairing",
"pricing": {
- "alt_bn128_pairing": {
- "base": 100000,
- "pair": 80000,
- "eip1108_transition_base": 45000,
- "eip1108_transition_pair": 34000
+ "0x0": {
+ "price": {
+ "alt_bn128_pairing": {
+ "base": 100000,
+ "pair": 80000
+ }
+ }
+ },
+ "0xc350": {
+ "price": {
+ "alt_bn128_pairing": {
+ "base": 45000,
+ "pair": 34000
+ }
+ }
}
},
- "activate_at": "0x7530",
- "eip1108_transition": "0xc350"
+ "activate_at": "0x7530"
}
},
"0000000000000000000000000000000000000009": {
diff --git a/cmd/puppeth/wizard_genesis.go b/cmd/puppeth/wizard_genesis.go
index 8832de13ab..ab3e2247b6 100644
--- a/cmd/puppeth/wizard_genesis.go
+++ b/cmd/puppeth/wizard_genesis.go
@@ -179,7 +179,7 @@ func (w *wizard) importGenesis() {
// Parse the genesis file and inject it successful
var genesis core.Genesis
if err := json.NewDecoder(reader).Decode(&genesis); err != nil {
- log.Error("Invalid genesis spec", "err", err)
+ log.Error("Invalid genesis spec: %v", err)
return
}
log.Info("Imported genesis block")
diff --git a/cmd/utils/customflags.go b/cmd/utils/customflags.go
index 66ebf9ab04..17dcba5f74 100644
--- a/cmd/utils/customflags.go
+++ b/cmd/utils/customflags.go
@@ -185,28 +185,6 @@ func GlobalBig(ctx *cli.Context, name string) *big.Int {
return (*big.Int)(val.(*bigValue))
}
-func prefixFor(name string) (prefix string) {
- if len(name) == 1 {
- prefix = "-"
- } else {
- prefix = "--"
- }
-
- return
-}
-
-func prefixedNames(fullName string) (prefixed string) {
- parts := strings.Split(fullName, ",")
- for i, name := range parts {
- name = strings.Trim(name, " ")
- prefixed += prefixFor(name) + name
- if i < len(parts)-1 {
- prefixed += ", "
- }
- }
- return
-}
-
// Expands a file path
// 1. replace tilde with users home dir
// 2. expands embedded environment variables
diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go
index 8b9d21f711..65f8896fec 100644
--- a/cmd/utils/flags.go
+++ b/cmd/utils/flags.go
@@ -47,7 +47,6 @@ import (
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
- "github.com/ethereum/go-ethereum/dashboard"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/eth/downloader"
"github.com/ethereum/go-ethereum/eth/gasprice"
@@ -283,26 +282,6 @@ var (
Name: "ulc.onlyannounce",
Usage: "Ultra light server sends announcements only",
}
- // Dashboard settings
- DashboardEnabledFlag = cli.BoolFlag{
- Name: "dashboard",
- Usage: "Enable the dashboard",
- }
- DashboardAddrFlag = cli.StringFlag{
- Name: "dashboard.addr",
- Usage: "Dashboard listening interface",
- Value: dashboard.DefaultConfig.Host,
- }
- DashboardPortFlag = cli.IntFlag{
- Name: "dashboard.host",
- Usage: "Dashboard listening port",
- Value: dashboard.DefaultConfig.Port,
- }
- DashboardRefreshFlag = cli.DurationFlag{
- Name: "dashboard.refresh",
- Usage: "Dashboard metrics collection refresh rate",
- Value: dashboard.DefaultConfig.Refresh,
- }
// Ethash settings
EthashCacheDirFlag = DirectoryFlag{
Name: "ethash.cachedir",
@@ -1736,13 +1715,6 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
}
}
-// SetDashboardConfig applies dashboard related command line flags to the config.
-func SetDashboardConfig(ctx *cli.Context, cfg *dashboard.Config) {
- cfg.Host = ctx.GlobalString(DashboardAddrFlag.Name)
- cfg.Port = ctx.GlobalInt(DashboardPortFlag.Name)
- cfg.Refresh = ctx.GlobalDuration(DashboardRefreshFlag.Name)
-}
-
// RegisterEthService adds an Ethereum client to the stack.
func RegisterEthService(stack *node.Node, cfg *eth.Config) chan *eth.Ethereum {
// Quorum: raft service listens to this channel to get Ethereum backend
@@ -1770,13 +1742,6 @@ func RegisterEthService(stack *node.Node, cfg *eth.Config) chan *eth.Ethereum {
return nodeChan
}
-// RegisterDashboardService adds a dashboard to the stack.
-func RegisterDashboardService(stack *node.Node, cfg *dashboard.Config, commit string) {
- stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
- return dashboard.New(cfg, commit, ctx.ResolvePath("logs")), nil
- })
-}
-
// RegisterShhService configures Whisper and adds it to the given node.
func RegisterShhService(stack *node.Node, cfg *whisper.Config) {
if err := stack.Register(func(n *node.ServiceContext) (node.Service, error) {
diff --git a/cmd/utils/flags_test.go b/cmd/utils/flags_test.go
index 0db5144b23..15ff4313ff 100644
--- a/cmd/utils/flags_test.go
+++ b/cmd/utils/flags_test.go
@@ -1,4 +1,4 @@
-// Copyright 2014 The go-ethereum Authors
+// Copyright 2019 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
diff --git a/cmd/wnode/main.go b/cmd/wnode/main.go
index 49736d7321..968f1fd49f 100644
--- a/cmd/wnode/main.go
+++ b/cmd/wnode/main.go
@@ -37,6 +37,7 @@ import (
"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/console"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
@@ -165,7 +166,7 @@ func echo() {
fmt.Printf("pow = %f \n", *argPoW)
fmt.Printf("mspow = %f \n", *argServerPoW)
fmt.Printf("ip = %s \n", *argIP)
- fmt.Printf("pub = %s \n", common.ToHex(crypto.FromECDSAPub(pub)))
+ fmt.Printf("pub = %s \n", hexutil.Encode(crypto.FromECDSAPub(pub)))
fmt.Printf("idfile = %s \n", *argIDFile)
fmt.Printf("dbpath = %s \n", *argDBPath)
fmt.Printf("boot = %s \n", *argEnode)
@@ -298,7 +299,7 @@ func startServer() error {
return err
}
- fmt.Printf("my public key: %s \n", common.ToHex(crypto.FromECDSAPub(&asymKey.PublicKey)))
+ fmt.Printf("my public key: %s \n", hexutil.Encode(crypto.FromECDSAPub(&asymKey.PublicKey)))
fmt.Println(server.NodeInfo().Enode)
if *bootstrapMode {
diff --git a/common/bytes_test.go b/common/bytes_test.go
index 97dd34d159..7cf6553377 100644
--- a/common/bytes_test.go
+++ b/common/bytes_test.go
@@ -19,41 +19,43 @@ package common
import (
"bytes"
"testing"
-
- checker "gopkg.in/check.v1"
)
-type BytesSuite struct{}
-
-var _ = checker.Suite(&BytesSuite{})
+func TestCopyBytes(t *testing.T) {
+ input := []byte{1, 2, 3, 4}
-func (s *BytesSuite) TestCopyBytes(c *checker.C) {
- data1 := []byte{1, 2, 3, 4}
- exp1 := []byte{1, 2, 3, 4}
- res1 := CopyBytes(data1)
- c.Assert(res1, checker.DeepEquals, exp1)
+ v := CopyBytes(input)
+ if !bytes.Equal(v, []byte{1, 2, 3, 4}) {
+ t.Fatal("not equal after copy")
+ }
+ v[0] = 99
+ if bytes.Equal(v, input) {
+ t.Fatal("result is not a copy")
+ }
}
-func (s *BytesSuite) TestLeftPadBytes(c *checker.C) {
- val1 := []byte{1, 2, 3, 4}
- exp1 := []byte{0, 0, 0, 0, 1, 2, 3, 4}
-
- res1 := LeftPadBytes(val1, 8)
- res2 := LeftPadBytes(val1, 2)
+func TestLeftPadBytes(t *testing.T) {
+ val := []byte{1, 2, 3, 4}
+ padded := []byte{0, 0, 0, 0, 1, 2, 3, 4}
- c.Assert(res1, checker.DeepEquals, exp1)
- c.Assert(res2, checker.DeepEquals, val1)
+ if r := LeftPadBytes(val, 8); !bytes.Equal(r, padded) {
+ t.Fatalf("LeftPadBytes(%v, 8) == %v", val, r)
+ }
+ if r := LeftPadBytes(val, 2); !bytes.Equal(r, val) {
+ t.Fatalf("LeftPadBytes(%v, 2) == %v", val, r)
+ }
}
-func (s *BytesSuite) TestRightPadBytes(c *checker.C) {
+func TestRightPadBytes(t *testing.T) {
val := []byte{1, 2, 3, 4}
- exp := []byte{1, 2, 3, 4, 0, 0, 0, 0}
-
- resstd := RightPadBytes(val, 8)
- resshrt := RightPadBytes(val, 2)
+ padded := []byte{1, 2, 3, 4, 0, 0, 0, 0}
- c.Assert(resstd, checker.DeepEquals, exp)
- c.Assert(resshrt, checker.DeepEquals, val)
+ if r := RightPadBytes(val, 8); !bytes.Equal(r, padded) {
+ t.Fatalf("RightPadBytes(%v, 8) == %v", val, r)
+ }
+ if r := RightPadBytes(val, 2); !bytes.Equal(r, val) {
+ t.Fatalf("RightPadBytes(%v, 2) == %v", val, r)
+ }
}
func TestFromHex(t *testing.T) {
diff --git a/common/hexutil/json.go b/common/hexutil/json.go
index 777b08eca4..50db208118 100644
--- a/common/hexutil/json.go
+++ b/common/hexutil/json.go
@@ -86,7 +86,7 @@ func (b *Bytes) UnmarshalGraphQL(input interface{}) error {
}
*b = data
default:
- err = fmt.Errorf("Unexpected type for Bytes: %v", input)
+ err = fmt.Errorf("unexpected type %T for Bytes", input)
}
return err
}
@@ -220,7 +220,7 @@ func (b *Big) UnmarshalGraphQL(input interface{}) error {
num.SetInt64(int64(input))
*b = Big(num)
default:
- err = fmt.Errorf("Unexpected type for BigInt: %v", input)
+ err = fmt.Errorf("unexpected type %T for BigInt", input)
}
return err
}
@@ -284,7 +284,7 @@ func (b *Uint64) UnmarshalGraphQL(input interface{}) error {
case int32:
*b = Uint64(input)
default:
- err = fmt.Errorf("Unexpected type for Long: %v", input)
+ err = fmt.Errorf("unexpected type %T for Long", input)
}
return err
}
diff --git a/common/main_test.go b/common/main_test.go
deleted file mode 100644
index 149d09928a..0000000000
--- a/common/main_test.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2014 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
, prevState: Readonly) {
- if (this.content && typeof this.content.beforeUpdate === 'function') {
- return this.content.beforeUpdate();
- }
- return null;
- }
-
- render() {
- const {
- classes, active, content, shouldUpdate,
- } = this.props;
-
- let children = null;
- switch (active) {
- case MENU.get('home').id:
- children =
-
-
-
-
- {this.menuItems(transitionState)}
-
- .
-
- signature := &Signature{}
-
- // minimal message is when both numbers are 1 bytes. adding up to:
- // 0x30 + len + 0x02 + 0x01 +
- // hence the -3. We assume that the length must be at least one byte.
- index++
- if rLen <= 0 || rLen > len(sigStr)-index-3 {
- return nil, errors.New("malformed signature: bogus R length")
- }
-
- // Then R itself.
- rBytes := sigStr[index : index+rLen]
- if der {
- switch err := canonicalPadding(rBytes); err {
- case errNegativeValue:
- return nil, errors.New("signature R is negative")
- case errExcessivelyPaddedValue:
- return nil, errors.New("signature R is excessively padded")
- }
- }
- signature.R = new(big.Int).SetBytes(rBytes)
- index += rLen
- // 0x02. length already checked in previous if.
- if sigStr[index] != 0x02 {
- return nil, errors.New("malformed signature: no 2nd int marker")
- }
- index++
-
- // Length of signature S.
- sLen := int(sigStr[index])
- index++
- // S should be the rest of the string.
- if sLen <= 0 || sLen > len(sigStr)-index {
- return nil, errors.New("malformed signature: bogus S length")
- }
-
- // Then S itself.
- sBytes := sigStr[index : index+sLen]
- if der {
- switch err := canonicalPadding(sBytes); err {
- case errNegativeValue:
- return nil, errors.New("signature S is negative")
- case errExcessivelyPaddedValue:
- return nil, errors.New("signature S is excessively padded")
- }
- }
- signature.S = new(big.Int).SetBytes(sBytes)
- index += sLen
-
- // sanity check length parsing
- if index != len(sigStr) {
- return nil, fmt.Errorf("malformed signature: bad final length %v != %v",
- index, len(sigStr))
- }
-
- // Verify also checks this, but we can be more sure that we parsed
- // correctly if we verify here too.
- // FWIW the ecdsa spec states that R and S must be | 1, N - 1 |
- // but crypto/ecdsa only checks for Sign != 0. Mirror that.
- if signature.R.Sign() != 1 {
- return nil, errors.New("signature R isn't 1 or more")
- }
- if signature.S.Sign() != 1 {
- return nil, errors.New("signature S isn't 1 or more")
- }
- if signature.R.Cmp(curve.Params().N) >= 0 {
- return nil, errors.New("signature R is >= curve.N")
- }
- if signature.S.Cmp(curve.Params().N) >= 0 {
- return nil, errors.New("signature S is >= curve.N")
- }
-
- return signature, nil
-}
-
-// ParseSignature parses a signature in BER format for the curve type `curve'
-// into a Signature type, perfoming some basic sanity checks. If parsing
-// according to the more strict DER format is needed, use ParseDERSignature.
-func ParseSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
- return parseSig(sigStr, curve, false)
-}
-
-// ParseDERSignature parses a signature in DER format for the curve type
-// `curve` into a Signature type. If parsing according to the less strict
-// BER format is needed, use ParseSignature.
-func ParseDERSignature(sigStr []byte, curve elliptic.Curve) (*Signature, error) {
- return parseSig(sigStr, curve, true)
-}
-
-// canonicalizeInt returns the bytes for the passed big integer adjusted as
-// necessary to ensure that a big-endian encoded integer can't possibly be
-// misinterpreted as a negative number. This can happen when the most
-// significant bit is set, so it is padded by a leading zero byte in this case.
-// Also, the returned bytes will have at least a single byte when the passed
-// value is 0. This is required for DER encoding.
-func canonicalizeInt(val *big.Int) []byte {
- b := val.Bytes()
- if len(b) == 0 {
- b = []byte{0x00}
- }
- if b[0]&0x80 != 0 {
- paddedBytes := make([]byte, len(b)+1)
- copy(paddedBytes[1:], b)
- b = paddedBytes
- }
- return b
-}
-
-// canonicalPadding checks whether a big-endian encoded integer could
-// possibly be misinterpreted as a negative number (even though OpenSSL
-// treats all numbers as unsigned), or if there is any unnecessary
-// leading zero padding.
-func canonicalPadding(b []byte) error {
- switch {
- case b[0]&0x80 == 0x80:
- return errNegativeValue
- case len(b) > 1 && b[0] == 0x00 && b[1]&0x80 != 0x80:
- return errExcessivelyPaddedValue
- default:
- return nil
- }
-}
-
-// hashToInt converts a hash value to an integer. There is some disagreement
-// about how this is done. [NSA] suggests that this is done in the obvious
-// manner, but [SECG] truncates the hash to the bit-length of the curve order
-// first. We follow [SECG] because that's what OpenSSL does. Additionally,
-// OpenSSL right shifts excess bits from the number if the hash is too large
-// and we mirror that too.
-// This is borrowed from crypto/ecdsa.
-func hashToInt(hash []byte, c elliptic.Curve) *big.Int {
- orderBits := c.Params().N.BitLen()
- orderBytes := (orderBits + 7) / 8
- if len(hash) > orderBytes {
- hash = hash[:orderBytes]
- }
-
- ret := new(big.Int).SetBytes(hash)
- excess := len(hash)*8 - orderBits
- if excess > 0 {
- ret.Rsh(ret, uint(excess))
- }
- return ret
-}
-
-// recoverKeyFromSignature recoves a public key from the signature "sig" on the
-// given message hash "msg". Based on the algorithm found in section 5.1.5 of
-// SEC 1 Ver 2.0, page 47-48 (53 and 54 in the pdf). This performs the details
-// in the inner loop in Step 1. The counter provided is actually the j parameter
-// of the loop * 2 - on the first iteration of j we do the R case, else the -R
-// case in step 1.6. This counter is used in the bitcoin compressed signature
-// format and thus we match bitcoind's behaviour here.
-func recoverKeyFromSignature(curve *KoblitzCurve, sig *Signature, msg []byte,
- iter int, doChecks bool) (*PublicKey, error) {
- // 1.1 x = (n * i) + r
- Rx := new(big.Int).Mul(curve.Params().N,
- new(big.Int).SetInt64(int64(iter/2)))
- Rx.Add(Rx, sig.R)
- if Rx.Cmp(curve.Params().P) != -1 {
- return nil, errors.New("calculated Rx is larger than curve P")
- }
-
- // convert 02