Merge pull request #3525 from fjl/all-gosimple-cleanup

all: clean up lint issues, remove more dead code
This commit is contained in:
Péter Szilágyi 2017-01-06 19:30:44 +02:00 committed by GitHub
commit ac93a6ff6c
118 changed files with 444 additions and 1976 deletions

@ -67,10 +67,10 @@ func TestTypeCheck(t *testing.T) {
{"uint16[3]", [4]uint16{1, 2, 3}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"}, {"uint16[3]", [4]uint16{1, 2, 3}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"},
{"uint16[3]", []uint16{1, 2, 3}, ""}, {"uint16[3]", []uint16{1, 2, 3}, ""},
{"uint16[3]", []uint16{1, 2, 3, 4}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"}, {"uint16[3]", []uint16{1, 2, 3, 4}, "abi: cannot use [4]uint16 as type [3]uint16 as argument"},
{"address[]", []common.Address{common.Address{1}}, ""}, {"address[]", []common.Address{{1}}, ""},
{"address[1]", []common.Address{common.Address{1}}, ""}, {"address[1]", []common.Address{{1}}, ""},
{"address[1]", [1]common.Address{common.Address{1}}, ""}, {"address[1]", [1]common.Address{{1}}, ""},
{"address[2]", [1]common.Address{common.Address{1}}, "abi: cannot use [1]array as type [2]array as argument"}, {"address[2]", [1]common.Address{{1}}, "abi: cannot use [1]array as type [2]array as argument"},
{"bytes32", [32]byte{}, ""}, {"bytes32", [32]byte{}, ""},
{"bytes32", [33]byte{}, "abi: cannot use [33]uint8 as type [32]uint8 as argument"}, {"bytes32", [33]byte{}, "abi: cannot use [33]uint8 as type [32]uint8 as argument"},
{"bytes32", common.Hash{1}, ""}, {"bytes32", common.Hash{1}, ""},
@ -80,7 +80,7 @@ func TestTypeCheck(t *testing.T) {
{"bytes", [2]byte{0, 1}, ""}, {"bytes", [2]byte{0, 1}, ""},
{"bytes", common.Hash{1}, ""}, {"bytes", common.Hash{1}, ""},
{"string", "hello world", ""}, {"string", "hello world", ""},
{"bytes32[]", [][32]byte{[32]byte{}}, ""}, {"bytes32[]", [][32]byte{{}}, ""},
{"function", [24]byte{}, ""}, {"function", [24]byte{}, ""},
} { } {
typ, err := NewType(test.typ) typ, err := NewType(test.typ)
@ -343,8 +343,8 @@ func TestPack(t *testing.T) {
{"uint16[]", []uint16{1, 2}, formatSliceOutput([]byte{1}, []byte{2})}, {"uint16[]", []uint16{1, 2}, formatSliceOutput([]byte{1}, []byte{2})},
{"bytes20", [20]byte{1}, pad([]byte{1}, 32, false)}, {"bytes20", [20]byte{1}, pad([]byte{1}, 32, false)},
{"uint256[]", []*big.Int{big.NewInt(1), big.NewInt(2)}, formatSliceOutput([]byte{1}, []byte{2})}, {"uint256[]", []*big.Int{big.NewInt(1), big.NewInt(2)}, formatSliceOutput([]byte{1}, []byte{2})},
{"address[]", []common.Address{common.Address{1}, common.Address{2}}, formatSliceOutput(pad([]byte{1}, 20, false), pad([]byte{2}, 20, false))}, {"address[]", []common.Address{{1}, {2}}, formatSliceOutput(pad([]byte{1}, 20, false), pad([]byte{2}, 20, false))},
{"bytes32[]", []common.Hash{common.Hash{1}, common.Hash{2}}, formatSliceOutput(pad([]byte{1}, 32, false), pad([]byte{2}, 32, false))}, {"bytes32[]", []common.Hash{{1}, {2}}, formatSliceOutput(pad([]byte{1}, 32, false), pad([]byte{2}, 32, false))},
{"function", [24]byte{1}, pad([]byte{1}, 32, false)}, {"function", [24]byte{1}, pad([]byte{1}, 32, false)},
} { } {
typ, err := NewType(test.typ) typ, err := NewType(test.typ)
@ -458,12 +458,12 @@ func TestReader(t *testing.T) {
Uint256, _ := NewType("uint256") Uint256, _ := NewType("uint256")
exp := ABI{ exp := ABI{
Methods: map[string]Method{ Methods: map[string]Method{
"balance": Method{ "balance": {
"balance", true, nil, nil, "balance", true, nil, nil,
}, },
"send": Method{ "send": {
"send", false, []Argument{ "send", false, []Argument{
Argument{"amount", Uint256, false}, {"amount", Uint256, false},
}, nil, }, nil,
}, },
}, },
@ -562,7 +562,7 @@ func TestTestSlice(t *testing.T) {
func TestMethodSignature(t *testing.T) { func TestMethodSignature(t *testing.T) {
String, _ := NewType("string") String, _ := NewType("string")
m := Method{"foo", false, []Argument{Argument{"bar", String, false}, Argument{"baz", String, false}}, nil} m := Method{"foo", false, []Argument{{"bar", String, false}, {"baz", String, false}}, nil}
exp := "foo(string,string)" exp := "foo(string,string)"
if m.Sig() != exp { if m.Sig() != exp {
t.Error("signature mismatch", exp, "!=", m.Sig()) t.Error("signature mismatch", exp, "!=", m.Sig())
@ -574,7 +574,7 @@ func TestMethodSignature(t *testing.T) {
} }
uintt, _ := NewType("uint") uintt, _ := NewType("uint")
m = Method{"foo", false, []Argument{Argument{"bar", uintt, false}}, nil} m = Method{"foo", false, []Argument{{"bar", uintt, false}}, nil}
exp = "foo(uint256)" exp = "foo(uint256)"
if m.Sig() != exp { if m.Sig() != exp {
t.Error("signature mismatch", exp, "!=", m.Sig()) t.Error("signature mismatch", exp, "!=", m.Sig())
@ -779,8 +779,8 @@ func TestBareEvents(t *testing.T) {
"balance": {false, nil}, "balance": {false, nil},
"anon": {true, nil}, "anon": {true, nil},
"args": {false, []Argument{ "args": {false, []Argument{
Argument{Name: "arg0", Type: arg0, Indexed: false}, {Name: "arg0", Type: arg0, Indexed: false},
Argument{Name: "arg1", Type: arg1, Indexed: true}, {Name: "arg1", Type: arg1, Indexed: true},
}}, }},
} }

@ -147,21 +147,21 @@ func bindTypeGo(kind abi.Type) string {
switch { switch {
case strings.HasPrefix(stringKind, "address"): case strings.HasPrefix(stringKind, "address"):
parts := regexp.MustCompile("address(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 2 { if len(parts) != 2 {
return stringKind return stringKind
} }
return fmt.Sprintf("%scommon.Address", parts[1]) return fmt.Sprintf("%scommon.Address", parts[1])
case strings.HasPrefix(stringKind, "bytes"): case strings.HasPrefix(stringKind, "bytes"):
parts := regexp.MustCompile("bytes([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`bytes([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 3 { if len(parts) != 3 {
return stringKind return stringKind
} }
return fmt.Sprintf("%s[%s]byte", parts[2], parts[1]) return fmt.Sprintf("%s[%s]byte", parts[2], parts[1])
case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"):
parts := regexp.MustCompile("(u)?int([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 4 { if len(parts) != 4 {
return stringKind return stringKind
} }
@ -172,7 +172,7 @@ func bindTypeGo(kind abi.Type) string {
return fmt.Sprintf("%s*big.Int", parts[3]) return fmt.Sprintf("%s*big.Int", parts[3])
case strings.HasPrefix(stringKind, "bool") || strings.HasPrefix(stringKind, "string"): case strings.HasPrefix(stringKind, "bool") || strings.HasPrefix(stringKind, "string"):
parts := regexp.MustCompile("([a-z]+)(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`([a-z]+)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 3 { if len(parts) != 3 {
return stringKind return stringKind
} }
@ -191,7 +191,7 @@ func bindTypeJava(kind abi.Type) string {
switch { switch {
case strings.HasPrefix(stringKind, "address"): case strings.HasPrefix(stringKind, "address"):
parts := regexp.MustCompile("address(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 2 { if len(parts) != 2 {
return stringKind return stringKind
} }
@ -201,7 +201,7 @@ func bindTypeJava(kind abi.Type) string {
return fmt.Sprintf("Addresses") return fmt.Sprintf("Addresses")
case strings.HasPrefix(stringKind, "bytes"): case strings.HasPrefix(stringKind, "bytes"):
parts := regexp.MustCompile("bytes([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`bytes([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 3 { if len(parts) != 3 {
return stringKind return stringKind
} }
@ -211,7 +211,7 @@ func bindTypeJava(kind abi.Type) string {
return "byte[]" return "byte[]"
case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"):
parts := regexp.MustCompile("(u)?int([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 4 { if len(parts) != 4 {
return stringKind return stringKind
} }
@ -230,7 +230,7 @@ func bindTypeJava(kind abi.Type) string {
return fmt.Sprintf("BigInts") return fmt.Sprintf("BigInts")
case strings.HasPrefix(stringKind, "bool"): case strings.HasPrefix(stringKind, "bool"):
parts := regexp.MustCompile("bool(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`bool(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 2 { if len(parts) != 2 {
return stringKind return stringKind
} }
@ -240,7 +240,7 @@ func bindTypeJava(kind abi.Type) string {
return fmt.Sprintf("bool[]") return fmt.Sprintf("bool[]")
case strings.HasPrefix(stringKind, "string"): case strings.HasPrefix(stringKind, "string"):
parts := regexp.MustCompile("string(\\[[0-9]*\\])?").FindStringSubmatch(stringKind) parts := regexp.MustCompile(`string(\[[0-9]*\])?`).FindStringSubmatch(stringKind)
if len(parts) != 2 { if len(parts) != 2 {
return stringKind return stringKind
} }
@ -278,7 +278,7 @@ func namedTypeJava(javaKind string, solKind abi.Type) string {
case "bool[]": case "bool[]":
return "Bools" return "Bools"
case "BigInt": case "BigInt":
parts := regexp.MustCompile("(u)?int([0-9]*)(\\[[0-9]*\\])?").FindStringSubmatch(solKind.String()) parts := regexp.MustCompile(`(u)?int([0-9]*)(\[[0-9]*\])?`).FindStringSubmatch(solKind.String())
if len(parts) != 4 { if len(parts) != 4 {
return javaKind return javaKind
} }

@ -65,7 +65,7 @@ var (
// string int uint fixed // string int uint fixed
// string32 int8 uint8 uint[] // string32 int8 uint8 uint[]
// address int256 uint256 fixed128x128[2] // address int256 uint256 fixed128x128[2]
fullTypeRegex = regexp.MustCompile("([a-zA-Z0-9]+)(\\[([0-9]*)\\])?") fullTypeRegex = regexp.MustCompile(`([a-zA-Z0-9]+)(\[([0-9]*)\])?`)
// typeRegex parses the abi sub types // typeRegex parses the abi sub types
typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?") typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?")
) )

@ -195,7 +195,7 @@ func doInstall(cmdline []string) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
for name, _ := range pkgs { for name := range pkgs {
if name == "main" { if name == "main" {
gobuild := goToolArch(*arch, "build", buildFlags(env)...) gobuild := goToolArch(*arch, "build", buildFlags(env)...)
gobuild.Args = append(gobuild.Args, "-v") gobuild.Args = append(gobuild.Args, "-v")

@ -88,14 +88,9 @@ func runTestWithReader(test string, r io.Reader) error {
default: default:
err = fmt.Errorf("Invalid test type specified: %v", test) err = fmt.Errorf("Invalid test type specified: %v", test)
} }
if err != nil {
return err return err
} }
return nil
}
func getFiles(path string) ([]string, error) { func getFiles(path string) ([]string, error) {
glog.Infoln("getFiles", path) glog.Infoln("getFiles", path)
var files []string var files []string

@ -148,7 +148,7 @@ Passphrase: {{.InputLine "foobar"}}
"Unlocked account f466859ead1932d743d622cb74fc058882e8648a", "Unlocked account f466859ead1932d743d622cb74fc058882e8648a",
} }
for _, m := range wantMessages { for _, m := range wantMessages {
if strings.Index(geth.stderrText(), m) == -1 { if !strings.Contains(geth.stderrText(), m) {
t.Errorf("stderr text does not contain %q", m) t.Errorf("stderr text does not contain %q", m)
} }
} }
@ -193,7 +193,7 @@ Passphrase: {{.InputLine "foobar"}}
"Unlocked account 289d485d9771714cce91d3393d764e1311907acc", "Unlocked account 289d485d9771714cce91d3393d764e1311907acc",
} }
for _, m := range wantMessages { for _, m := range wantMessages {
if strings.Index(geth.stderrText(), m) == -1 { if !strings.Contains(geth.stderrText(), m) {
t.Errorf("stderr text does not contain %q", m) t.Errorf("stderr text does not contain %q", m)
} }
} }
@ -212,7 +212,7 @@ func TestUnlockFlagPasswordFile(t *testing.T) {
"Unlocked account 289d485d9771714cce91d3393d764e1311907acc", "Unlocked account 289d485d9771714cce91d3393d764e1311907acc",
} }
for _, m := range wantMessages { for _, m := range wantMessages {
if strings.Index(geth.stderrText(), m) == -1 { if !strings.Contains(geth.stderrText(), m) {
t.Errorf("stderr text does not contain %q", m) t.Errorf("stderr text does not contain %q", m)
} }
} }
@ -260,7 +260,7 @@ In order to avoid this warning, you need to remove the following duplicate key f
"Unlocked account f466859ead1932d743d622cb74fc058882e8648a", "Unlocked account f466859ead1932d743d622cb74fc058882e8648a",
} }
for _, m := range wantMessages { for _, m := range wantMessages {
if strings.Index(geth.stderrText(), m) == -1 { if !strings.Contains(geth.stderrText(), m) {
t.Errorf("stderr text does not contain %q", m) t.Errorf("stderr text does not contain %q", m)
} }
} }

@ -168,7 +168,6 @@ func init() {
} }
app.After = func(ctx *cli.Context) error { app.After = func(ctx *cli.Context) error {
logger.Flush()
debug.Exit() debug.Exit()
console.Stdin.Close() // Resets terminal mode. console.Stdin.Close() // Resets terminal mode.
return nil return nil

@ -129,7 +129,7 @@ func init() {
app.HideVersion = true // we have a command to print the version app.HideVersion = true // we have a command to print the version
app.Copyright = "Copyright 2013-2016 The go-ethereum Authors" app.Copyright = "Copyright 2013-2016 The go-ethereum Authors"
app.Commands = []cli.Command{ app.Commands = []cli.Command{
cli.Command{ {
Action: version, Action: version,
Name: "version", Name: "version",
Usage: "Print version numbers", Usage: "Print version numbers",
@ -138,7 +138,7 @@ func init() {
The output of this command is supposed to be machine-readable. The output of this command is supposed to be machine-readable.
`, `,
}, },
cli.Command{ {
Action: upload, Action: upload,
Name: "up", Name: "up",
Usage: "upload a file or directory to swarm using the HTTP API", Usage: "upload a file or directory to swarm using the HTTP API",
@ -147,7 +147,7 @@ The output of this command is supposed to be machine-readable.
"upload a file or directory to swarm using the HTTP API and prints the root hash", "upload a file or directory to swarm using the HTTP API and prints the root hash",
`, `,
}, },
cli.Command{ {
Action: hash, Action: hash,
Name: "hash", Name: "hash",
Usage: "print the swarm hash of a file or directory", Usage: "print the swarm hash of a file or directory",

@ -67,7 +67,6 @@ func Fatalf(format string, args ...interface{}) {
} }
} }
fmt.Fprintf(w, "Fatal: "+format+"\n", args...) fmt.Fprintf(w, "Fatal: "+format+"\n", args...)
logger.Flush()
os.Exit(1) os.Exit(1)
} }
@ -95,7 +94,7 @@ func StartNode(stack *node.Node) {
func FormatTransactionData(data string) []byte { func FormatTransactionData(data string) []byte {
d := common.StringToByteFunc(data, func(s string) (ret []byte) { d := common.StringToByteFunc(data, func(s string) (ret []byte) {
slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000) slice := regexp.MustCompile(`\n|\s`).Split(s, 1000000000)
for _, dataItem := range slice { for _, dataItem := range slice {
d := common.FormatData(dataItem) d := common.FormatData(dataItem)
ret = append(ret, d...) ret = append(ret, d...)

@ -27,7 +27,7 @@ func TestMisc(t *testing.T) {
c := []byte{1, 2, 3, 4} c := []byte{1, 2, 3, 4}
z := BitTest(a, 1) z := BitTest(a, 1)
if z != true { if !z {
t.Error("Expected true got", z) t.Error("Expected true got", z)
} }
@ -79,11 +79,11 @@ func TestBigCopy(t *testing.T) {
z := BigToBytes(c, 16) z := BigToBytes(c, 16)
zbytes := []byte{232, 212, 165, 16, 0} zbytes := []byte{232, 212, 165, 16, 0}
if bytes.Compare(y, ybytes) != 0 { if !bytes.Equal(y, ybytes) {
t.Error("Got", ybytes) t.Error("Got", ybytes)
} }
if bytes.Compare(z, zbytes) != 0 { if !bytes.Equal(z, zbytes) {
t.Error("Got", zbytes) t.Error("Got", zbytes)
} }
} }

@ -143,7 +143,7 @@ func Hex2BytesFixed(str string, flen int) []byte {
return h return h
} else { } else {
if len(h) > flen { if len(h) > flen {
return h[len(h)-flen : len(h)] return h[len(h)-flen:]
} else { } else {
hh := make([]byte, flen) hh := make([]byte, flen)
copy(hh[flen-len(h):flen], h[:]) copy(hh[flen-len(h):flen], h[:])

@ -181,7 +181,7 @@ func TestFromHex(t *testing.T) {
input := "0x01" input := "0x01"
expected := []byte{1} expected := []byte{1}
result := FromHex(input) result := FromHex(input)
if bytes.Compare(expected, result) != 0 { if !bytes.Equal(expected, result) {
t.Errorf("Expected % x got % x", expected, result) t.Errorf("Expected % x got % x", expected, result)
} }
} }
@ -190,7 +190,7 @@ func TestFromHexOddLength(t *testing.T) {
input := "0x1" input := "0x1"
expected := []byte{1} expected := []byte{1}
result := FromHex(input) result := FromHex(input)
if bytes.Compare(expected, result) != 0 { if !bytes.Equal(expected, result) {
t.Errorf("Expected % x got % x", expected, result) t.Errorf("Expected % x got % x", expected, result)
} }
} }

@ -32,7 +32,7 @@ import (
) )
var ( var (
versionRegexp = regexp.MustCompile("[0-9]+\\.[0-9]+\\.[0-9]+") versionRegexp = regexp.MustCompile(`[0-9]+\.[0-9]+\.[0-9]+`)
solcParams = []string{ solcParams = []string{
"--combined-json", "bin,abi,userdoc,devdoc", "--combined-json", "bin,abi,userdoc,devdoc",
"--add-std", // include standard lib contracts "--add-std", // include standard lib contracts

@ -27,7 +27,7 @@ import (
// the unnecessary precision off from the formatted textual representation. // the unnecessary precision off from the formatted textual representation.
type PrettyDuration time.Duration type PrettyDuration time.Duration
var prettyDurationRe = regexp.MustCompile("\\.[0-9]+") var prettyDurationRe = regexp.MustCompile(`\.[0-9]+`)
// String implements the Stringer interface, allowing pretty printing of duration // String implements the Stringer interface, allowing pretty printing of duration
// values rounded to three decimals. // values rounded to three decimals.

@ -41,24 +41,24 @@ func TestSum(t *testing.T) {
func TestDist(t *testing.T) { func TestDist(t *testing.T) {
var vectors = []Vector{ var vectors = []Vector{
Vector{big.NewInt(1000), big.NewInt(1234)}, {big.NewInt(1000), big.NewInt(1234)},
Vector{big.NewInt(500), big.NewInt(10023)}, {big.NewInt(500), big.NewInt(10023)},
Vector{big.NewInt(1034), big.NewInt(1987)}, {big.NewInt(1034), big.NewInt(1987)},
Vector{big.NewInt(1034), big.NewInt(1987)}, {big.NewInt(1034), big.NewInt(1987)},
Vector{big.NewInt(8983), big.NewInt(1977)}, {big.NewInt(8983), big.NewInt(1977)},
Vector{big.NewInt(98382), big.NewInt(1887)}, {big.NewInt(98382), big.NewInt(1887)},
Vector{big.NewInt(12398), big.NewInt(1287)}, {big.NewInt(12398), big.NewInt(1287)},
Vector{big.NewInt(12398), big.NewInt(1487)}, {big.NewInt(12398), big.NewInt(1487)},
Vector{big.NewInt(12398), big.NewInt(1987)}, {big.NewInt(12398), big.NewInt(1987)},
Vector{big.NewInt(12398), big.NewInt(128)}, {big.NewInt(12398), big.NewInt(128)},
Vector{big.NewInt(12398), big.NewInt(1987)}, {big.NewInt(12398), big.NewInt(1987)},
Vector{big.NewInt(1398), big.NewInt(187)}, {big.NewInt(1398), big.NewInt(187)},
Vector{big.NewInt(12328), big.NewInt(1927)}, {big.NewInt(12328), big.NewInt(1927)},
Vector{big.NewInt(12398), big.NewInt(1987)}, {big.NewInt(12398), big.NewInt(1987)},
Vector{big.NewInt(22398), big.NewInt(1287)}, {big.NewInt(22398), big.NewInt(1287)},
Vector{big.NewInt(1370), big.NewInt(1981)}, {big.NewInt(1370), big.NewInt(1981)},
Vector{big.NewInt(12398), big.NewInt(1957)}, {big.NewInt(12398), big.NewInt(1957)},
Vector{big.NewInt(42198), big.NewInt(1987)}, {big.NewInt(42198), big.NewInt(1987)},
} }
VectorsBy(GasSort).Sort(vectors) VectorsBy(GasSort).Sort(vectors)

@ -76,9 +76,9 @@ func compressChunk(dat []byte) (ret []byte, n int) {
} }
return []byte{token, byte(j + 2)}, j return []byte{token, byte(j + 2)}, j
case len(dat) >= 32: case len(dat) >= 32:
if dat[0] == empty[0] && bytes.Compare(dat[:32], empty) == 0 { if dat[0] == empty[0] && bytes.Equal(dat[:32], empty) {
return []byte{token, emptyShaToken}, 32 return []byte{token, emptyShaToken}, 32
} else if dat[0] == emptyList[0] && bytes.Compare(dat[:32], emptyList) == 0 { } else if dat[0] == emptyList[0] && bytes.Equal(dat[:32], emptyList) {
return []byte{token, emptyListShaToken}, 32 return []byte{token, emptyListShaToken}, 32
} }
fallthrough fallthrough

@ -36,9 +36,9 @@ import (
) )
var ( var (
passwordRegexp = regexp.MustCompile("personal.[nus]") passwordRegexp = regexp.MustCompile(`personal.[nus]`)
onlyWhitespace = regexp.MustCompile("^\\s*$") onlyWhitespace = regexp.MustCompile(`^\s*$`)
exit = regexp.MustCompile("^\\s*exit\\s*;*\\s*$") exit = regexp.MustCompile(`^\s*exit\s*;*\s*$`)
) )
// HistoryFile is the file within the data directory to store input scrollback. // HistoryFile is the file within the data directory to store input scrollback.
@ -275,10 +275,7 @@ func (c *Console) Evaluate(statement string) error {
fmt.Fprintf(c.printer, "[native] error: %v\n", r) fmt.Fprintf(c.printer, "[native] error: %v\n", r)
} }
}() }()
if err := c.jsre.Evaluate(statement, c.printer); err != nil { return c.jsre.Evaluate(statement, c.printer)
return err
}
return nil
} }
// Interactive starts an interactive user session, where input is propted from // Interactive starts an interactive user session, where input is propted from

@ -27,7 +27,6 @@ import (
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/pow/ezp"
) )
func testChainConfig() *params.ChainConfig { func testChainConfig() *params.ChainConfig {
@ -48,20 +47,19 @@ func proc() (Validator, *BlockChain) {
} }
func TestNumber(t *testing.T) { func TestNumber(t *testing.T) {
pow := ezp.New()
_, chain := proc() _, chain := proc()
statedb, _ := state.New(chain.Genesis().Root(), chain.chainDb) statedb, _ := state.New(chain.Genesis().Root(), chain.chainDb)
cfg := testChainConfig() cfg := testChainConfig()
header := makeHeader(cfg, chain.Genesis(), statedb) header := makeHeader(cfg, chain.Genesis(), statedb)
header.Number = big.NewInt(3) header.Number = big.NewInt(3)
err := ValidateHeader(cfg, pow, header, chain.Genesis().Header(), false, false) err := ValidateHeader(cfg, FakePow{}, header, chain.Genesis().Header(), false, false)
if err != BlockNumberErr { if err != BlockNumberErr {
t.Errorf("expected block number error, got %q", err) t.Errorf("expected block number error, got %q", err)
} }
header = makeHeader(cfg, chain.Genesis(), statedb) header = makeHeader(cfg, chain.Genesis(), statedb)
err = ValidateHeader(cfg, pow, header, chain.Genesis().Header(), false, false) err = ValidateHeader(cfg, FakePow{}, header, chain.Genesis().Header(), false, false)
if err == BlockNumberErr { if err == BlockNumberErr {
t.Errorf("didn't expect block number error") t.Errorf("didn't expect block number error")
} }

@ -46,9 +46,6 @@ import (
) )
var ( var (
chainlogger = logger.NewLogger("CHAIN")
jsonlogger = logger.NewJsonLogger()
blockInsertTimer = metrics.NewTimer("chain/inserts") blockInsertTimer = metrics.NewTimer("chain/inserts")
ErrNoGenesis = errors.New("Genesis not found in chain") ErrNoGenesis = errors.New("Genesis not found in chain")
@ -150,7 +147,7 @@ func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, pow pow.P
return nil, err return nil, err
} }
// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
for hash, _ := range BadHashes { for hash := range BadHashes {
if header := bc.GetHeaderByHash(hash); header != nil { if header := bc.GetHeaderByHash(hash); header != nil {
// get the canonical block corresponding to the offending header's number // get the canonical block corresponding to the offending header's number
headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64()) headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
@ -402,10 +399,7 @@ func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) {
// Export writes the active chain to the given writer. // Export writes the active chain to the given writer.
func (self *BlockChain) Export(w io.Writer) error { func (self *BlockChain) Export(w io.Writer) error {
if err := self.ExportN(w, uint64(0), self.currentBlock.NumberU64()); err != nil { return self.ExportN(w, uint64(0), self.currentBlock.NumberU64())
return err
}
return nil
} }
// ExportN writes a subset of the active chain to the given writer. // ExportN writes a subset of the active chain to the given writer.

@ -1107,7 +1107,7 @@ func TestCanonicalBlockRetrieval(t *testing.T) {
chain, _ := GenerateChain(params.TestChainConfig, genesis, db, 10, func(i int, gen *BlockGen) {}) chain, _ := GenerateChain(params.TestChainConfig, genesis, db, 10, func(i int, gen *BlockGen) {})
for i, _ := range chain { for i := range chain {
go func(block *types.Block) { go func(block *types.Block) {
// try to retrieve a block by its canonical hash and see if the block data can be retrieved. // try to retrieve a block by its canonical hash and see if the block data can be retrieved.
for { for {

@ -45,11 +45,11 @@ func ValidateDAOHeaderExtraData(config *params.ChainConfig, header *types.Header
} }
// Depending whether we support or oppose the fork, validate the extra-data contents // Depending whether we support or oppose the fork, validate the extra-data contents
if config.DAOForkSupport { if config.DAOForkSupport {
if bytes.Compare(header.Extra, params.DAOForkBlockExtra) != 0 { if !bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
return ValidationError("DAO pro-fork bad block extra-data: 0x%x", header.Extra) return ValidationError("DAO pro-fork bad block extra-data: 0x%x", header.Extra)
} }
} else { } else {
if bytes.Compare(header.Extra, params.DAOForkBlockExtra) == 0 { if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
return ValidationError("DAO no-fork bad block extra-data: 0x%x", header.Extra) return ValidationError("DAO no-fork bad block extra-data: 0x%x", header.Extra)
} }
} }

@ -430,7 +430,7 @@ func TestReceiptStorage(t *testing.T) {
rlpHave, _ := rlp.EncodeToBytes(r) rlpHave, _ := rlp.EncodeToBytes(r)
rlpWant, _ := rlp.EncodeToBytes(receipt) rlpWant, _ := rlp.EncodeToBytes(receipt)
if bytes.Compare(rlpHave, rlpWant) != 0 { if !bytes.Equal(rlpHave, rlpWant) {
t.Fatalf("receipt #%d [%x]: receipt mismatch: have %v, want %v", i, receipt.TxHash, r, receipt) t.Fatalf("receipt #%d [%x]: receipt mismatch: have %v, want %v", i, receipt.TxHash, r, receipt)
} }
} }
@ -488,7 +488,7 @@ func TestBlockReceiptStorage(t *testing.T) {
rlpHave, _ := rlp.EncodeToBytes(rs[i]) rlpHave, _ := rlp.EncodeToBytes(rs[i])
rlpWant, _ := rlp.EncodeToBytes(receipts[i]) rlpWant, _ := rlp.EncodeToBytes(receipts[i])
if bytes.Compare(rlpHave, rlpWant) != 0 { if !bytes.Equal(rlpHave, rlpWant) {
t.Fatalf("receipt #%d: receipt mismatch: have %v, want %v", i, rs[i], receipts[i]) t.Fatalf("receipt #%d: receipt mismatch: have %v, want %v", i, rs[i], receipts[i])
} }
} }

@ -123,7 +123,7 @@ func (it *NodeIterator) step() error {
if !it.dataIt.Next() { if !it.dataIt.Next() {
it.dataIt = nil it.dataIt = nil
} }
if bytes.Compare(account.CodeHash, emptyCodeHash) != 0 { if !bytes.Equal(account.CodeHash, emptyCodeHash) {
it.codeHash = common.BytesToHash(account.CodeHash) it.codeHash = common.BytesToHash(account.CodeHash)
it.code, err = it.state.db.Get(account.CodeHash) it.code, err = it.state.db.Get(account.CodeHash)
if err != nil { if err != nil {

@ -41,7 +41,7 @@ func TestNodeIteratorCoverage(t *testing.T) {
} }
} }
// Cross check the hashes and the database itself // Cross check the hashes and the database itself
for hash, _ := range hashes { for hash := range hashes {
if _, err := db.Get(hash.Bytes()); err != nil { if _, err := db.Get(hash.Bytes()); err != nil {
t.Errorf("failed to retrieve reported node %x: %v", hash, err) t.Errorf("failed to retrieve reported node %x: %v", hash, err)
} }

@ -52,7 +52,7 @@ func TestRemove(t *testing.T) {
ms, account := create() ms, account := create()
nn := make([]bool, 10) nn := make([]bool, 10)
for i, _ := range nn { for i := range nn {
nn[i] = true nn[i] = true
} }
account.nonces = append(account.nonces, nn...) account.nonces = append(account.nonces, nn...)
@ -68,7 +68,7 @@ func TestReuse(t *testing.T) {
ms, account := create() ms, account := create()
nn := make([]bool, 10) nn := make([]bool, 10)
for i, _ := range nn { for i := range nn {
nn[i] = true nn[i] = true
} }
account.nonces = append(account.nonces, nn...) account.nonces = append(account.nonces, nn...)
@ -84,7 +84,7 @@ func TestReuse(t *testing.T) {
func TestRemoteNonceChange(t *testing.T) { func TestRemoteNonceChange(t *testing.T) {
ms, account := create() ms, account := create()
nn := make([]bool, 10) nn := make([]bool, 10)
for i, _ := range nn { for i := range nn {
nn[i] = true nn[i] = true
} }
account.nonces = append(account.nonces, nn...) account.nonces = append(account.nonces, nn...)

@ -479,7 +479,7 @@ func (self *StateDB) Copy() *StateDB {
logSize: self.logSize, logSize: self.logSize,
} }
// Copy the dirty states and logs // Copy the dirty states and logs
for addr, _ := range self.stateObjectsDirty { for addr := range self.stateObjectsDirty {
state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty) state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty)
state.stateObjectsDirty[addr] = struct{}{} state.stateObjectsDirty[addr] = struct{}{}
} }
@ -530,7 +530,7 @@ func (self *StateDB) GetRefund() *big.Int {
// It is called in between transactions to get the root hash that // It is called in between transactions to get the root hash that
// goes into transaction receipts. // goes into transaction receipts.
func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
for addr, _ := range s.stateObjectsDirty { for addr := range s.stateObjectsDirty {
stateObject := s.stateObjects[addr] stateObject := s.stateObjects[addr]
if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
s.deleteStateObject(stateObject) s.deleteStateObject(stateObject)
@ -553,7 +553,7 @@ func (s *StateDB) DeleteSuicides() {
// Reset refund so that any used-gas calculations can use this method. // Reset refund so that any used-gas calculations can use this method.
s.clearJournalAndRefund() s.clearJournalAndRefund()
for addr, _ := range s.stateObjectsDirty { for addr := range s.stateObjectsDirty {
stateObject := s.stateObjects[addr] stateObject := s.stateObjects[addr]
// If the object has been removed by a suicide // If the object has been removed by a suicide

@ -84,7 +84,7 @@ func checkStateAccounts(t *testing.T, db ethdb.Database, root common.Hash, accou
if nonce := state.GetNonce(acc.address); nonce != acc.nonce { if nonce := state.GetNonce(acc.address); nonce != acc.nonce {
t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce) t.Errorf("account %d: nonce mismatch: have %v, want %v", i, nonce, acc.nonce)
} }
if code := state.GetCode(acc.address); bytes.Compare(code, acc.code) != 0 { if code := state.GetCode(acc.address); !bytes.Equal(code, acc.code) {
t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code) t.Errorf("account %d: code mismatch: have %x, want %x", i, code, acc.code)
} }
} }
@ -198,7 +198,7 @@ func testIterativeRandomStateSync(t *testing.T, batch int) {
for len(queue) > 0 { for len(queue) > 0 {
// Fetch all the queued nodes in a random order // Fetch all the queued nodes in a random order
results := make([]trie.SyncResult, 0, len(queue)) results := make([]trie.SyncResult, 0, len(queue))
for hash, _ := range queue { for hash := range queue {
data, err := srcDb.Get(hash.Bytes()) data, err := srcDb.Get(hash.Bytes())
if err != nil { if err != nil {
t.Fatalf("failed to retrieve node data for %x: %v", hash, err) t.Fatalf("failed to retrieve node data for %x: %v", hash, err)
@ -235,7 +235,7 @@ func TestIterativeRandomDelayedStateSync(t *testing.T) {
for len(queue) > 0 { for len(queue) > 0 {
// Sync only half of the scheduled nodes, even those in random order // Sync only half of the scheduled nodes, even those in random order
results := make([]trie.SyncResult, 0, len(queue)/2+1) results := make([]trie.SyncResult, 0, len(queue)/2+1)
for hash, _ := range queue { for hash := range queue {
delete(queue, hash) delete(queue, hash)
data, err := srcDb.Get(hash.Bytes()) data, err := srcDb.Get(hash.Bytes())
@ -294,7 +294,7 @@ func TestIncompleteStateSync(t *testing.T) {
// Skim through the accounts and make sure the root hash is not a code node // Skim through the accounts and make sure the root hash is not a code node
codeHash := false codeHash := false
for _, acc := range srcAccounts { for _, acc := range srcAccounts {
if bytes.Compare(root.Bytes(), crypto.Sha3(acc.code)) == 0 { if root == crypto.Keccak256Hash(acc.code) {
codeHash = true codeHash = true
break break
} }

@ -110,7 +110,7 @@ func (m *txSortedMap) Filter(filter func(*types.Transaction) bool) types.Transac
// If transactions were removed, the heap and cache are ruined // If transactions were removed, the heap and cache are ruined
if len(removed) > 0 { if len(removed) > 0 {
*m.index = make([]uint64, 0, len(m.items)) *m.index = make([]uint64, 0, len(m.items))
for nonce, _ := range m.items { for nonce := range m.items {
*m.index = append(*m.index, nonce) *m.index = append(*m.index, nonce)
} }
heap.Init(m.index) heap.Init(m.index)

@ -609,7 +609,7 @@ func (pool *TxPool) promoteExecutables(state *state.StateDB) {
if queued > maxQueuedInTotal { if queued > maxQueuedInTotal {
// Sort all accounts with queued transactions by heartbeat // Sort all accounts with queued transactions by heartbeat
addresses := make(addresssByHeartbeat, 0, len(pool.queue)) addresses := make(addresssByHeartbeat, 0, len(pool.queue))
for addr, _ := range pool.queue { for addr := range pool.queue {
addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]}) addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
} }
sort.Sort(addresses) sort.Sort(addresses)

@ -97,14 +97,8 @@ func CreateBloom(receipts Receipts) Bloom {
func LogsBloom(logs []*Log) *big.Int { func LogsBloom(logs []*Log) *big.Int {
bin := new(big.Int) bin := new(big.Int)
for _, log := range logs { for _, log := range logs {
data := make([]common.Hash, len(log.Topics))
bin.Or(bin, bloom9(log.Address.Bytes())) bin.Or(bin, bloom9(log.Address.Bytes()))
for _, b := range log.Topics {
for i, topic := range log.Topics {
data[i] = topic
}
for _, b := range data {
bin.Or(bin, bloom9(b[:])) bin.Or(bin, bloom9(b[:]))
} }
} }

@ -52,283 +52,283 @@ var defaultJumpTable = NewJumpTable()
func NewJumpTable() [256]operation { func NewJumpTable() [256]operation {
return [256]operation{ return [256]operation{
ADD: operation{ ADD: {
execute: opAdd, execute: opAdd,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
SUB: operation{ SUB: {
execute: opSub, execute: opSub,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
MUL: operation{ MUL: {
execute: opMul, execute: opMul,
gasCost: constGasFunc(GasFastStep), gasCost: constGasFunc(GasFastStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
DIV: operation{ DIV: {
execute: opDiv, execute: opDiv,
gasCost: constGasFunc(GasFastStep), gasCost: constGasFunc(GasFastStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
SDIV: operation{ SDIV: {
execute: opSdiv, execute: opSdiv,
gasCost: constGasFunc(GasFastStep), gasCost: constGasFunc(GasFastStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
MOD: operation{ MOD: {
execute: opMod, execute: opMod,
gasCost: constGasFunc(GasFastStep), gasCost: constGasFunc(GasFastStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
SMOD: operation{ SMOD: {
execute: opSmod, execute: opSmod,
gasCost: constGasFunc(GasFastStep), gasCost: constGasFunc(GasFastStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
EXP: operation{ EXP: {
execute: opExp, execute: opExp,
gasCost: gasExp, gasCost: gasExp,
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
SIGNEXTEND: operation{ SIGNEXTEND: {
execute: opSignExtend, execute: opSignExtend,
gasCost: constGasFunc(GasFastStep), gasCost: constGasFunc(GasFastStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
NOT: operation{ NOT: {
execute: opNot, execute: opNot,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
valid: true, valid: true,
}, },
LT: operation{ LT: {
execute: opLt, execute: opLt,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
GT: operation{ GT: {
execute: opGt, execute: opGt,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
SLT: operation{ SLT: {
execute: opSlt, execute: opSlt,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
SGT: operation{ SGT: {
execute: opSgt, execute: opSgt,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
EQ: operation{ EQ: {
execute: opEq, execute: opEq,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
ISZERO: operation{ ISZERO: {
execute: opIszero, execute: opIszero,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
valid: true, valid: true,
}, },
AND: operation{ AND: {
execute: opAnd, execute: opAnd,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
OR: operation{ OR: {
execute: opOr, execute: opOr,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
XOR: operation{ XOR: {
execute: opXor, execute: opXor,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
BYTE: operation{ BYTE: {
execute: opByte, execute: opByte,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
ADDMOD: operation{ ADDMOD: {
execute: opAddmod, execute: opAddmod,
gasCost: constGasFunc(GasMidStep), gasCost: constGasFunc(GasMidStep),
validateStack: makeStackFunc(3, 1), validateStack: makeStackFunc(3, 1),
valid: true, valid: true,
}, },
MULMOD: operation{ MULMOD: {
execute: opMulmod, execute: opMulmod,
gasCost: constGasFunc(GasMidStep), gasCost: constGasFunc(GasMidStep),
validateStack: makeStackFunc(3, 1), validateStack: makeStackFunc(3, 1),
valid: true, valid: true,
}, },
SHA3: operation{ SHA3: {
execute: opSha3, execute: opSha3,
gasCost: gasSha3, gasCost: gasSha3,
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
memorySize: memorySha3, memorySize: memorySha3,
valid: true, valid: true,
}, },
ADDRESS: operation{ ADDRESS: {
execute: opAddress, execute: opAddress,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
BALANCE: operation{ BALANCE: {
execute: opBalance, execute: opBalance,
gasCost: gasBalance, gasCost: gasBalance,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
ORIGIN: operation{ ORIGIN: {
execute: opOrigin, execute: opOrigin,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
CALLER: operation{ CALLER: {
execute: opCaller, execute: opCaller,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
CALLVALUE: operation{ CALLVALUE: {
execute: opCallValue, execute: opCallValue,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
CALLDATALOAD: operation{ CALLDATALOAD: {
execute: opCalldataLoad, execute: opCalldataLoad,
gasCost: constGasFunc(GasFastestStep), gasCost: constGasFunc(GasFastestStep),
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
valid: true, valid: true,
}, },
CALLDATASIZE: operation{ CALLDATASIZE: {
execute: opCalldataSize, execute: opCalldataSize,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
CALLDATACOPY: operation{ CALLDATACOPY: {
execute: opCalldataCopy, execute: opCalldataCopy,
gasCost: gasCalldataCopy, gasCost: gasCalldataCopy,
validateStack: makeStackFunc(3, 1), validateStack: makeStackFunc(3, 1),
memorySize: memoryCalldataCopy, memorySize: memoryCalldataCopy,
valid: true, valid: true,
}, },
CODESIZE: operation{ CODESIZE: {
execute: opCodeSize, execute: opCodeSize,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
EXTCODESIZE: operation{ EXTCODESIZE: {
execute: opExtCodeSize, execute: opExtCodeSize,
gasCost: gasExtCodeSize, gasCost: gasExtCodeSize,
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
valid: true, valid: true,
}, },
CODECOPY: operation{ CODECOPY: {
execute: opCodeCopy, execute: opCodeCopy,
gasCost: gasCodeCopy, gasCost: gasCodeCopy,
validateStack: makeStackFunc(3, 0), validateStack: makeStackFunc(3, 0),
memorySize: memoryCodeCopy, memorySize: memoryCodeCopy,
valid: true, valid: true,
}, },
EXTCODECOPY: operation{ EXTCODECOPY: {
execute: opExtCodeCopy, execute: opExtCodeCopy,
gasCost: gasExtCodeCopy, gasCost: gasExtCodeCopy,
validateStack: makeStackFunc(4, 0), validateStack: makeStackFunc(4, 0),
memorySize: memoryExtCodeCopy, memorySize: memoryExtCodeCopy,
valid: true, valid: true,
}, },
GASPRICE: operation{ GASPRICE: {
execute: opGasprice, execute: opGasprice,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
BLOCKHASH: operation{ BLOCKHASH: {
execute: opBlockhash, execute: opBlockhash,
gasCost: constGasFunc(GasExtStep), gasCost: constGasFunc(GasExtStep),
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
valid: true, valid: true,
}, },
COINBASE: operation{ COINBASE: {
execute: opCoinbase, execute: opCoinbase,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
TIMESTAMP: operation{ TIMESTAMP: {
execute: opTimestamp, execute: opTimestamp,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
NUMBER: operation{ NUMBER: {
execute: opNumber, execute: opNumber,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
DIFFICULTY: operation{ DIFFICULTY: {
execute: opDifficulty, execute: opDifficulty,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
GASLIMIT: operation{ GASLIMIT: {
execute: opGasLimit, execute: opGasLimit,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
POP: operation{ POP: {
execute: opPop, execute: opPop,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(1, 0), validateStack: makeStackFunc(1, 0),
valid: true, valid: true,
}, },
MLOAD: operation{ MLOAD: {
execute: opMload, execute: opMload,
gasCost: gasMLoad, gasCost: gasMLoad,
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
memorySize: memoryMLoad, memorySize: memoryMLoad,
valid: true, valid: true,
}, },
MSTORE: operation{ MSTORE: {
execute: opMstore, execute: opMstore,
gasCost: gasMStore, gasCost: gasMStore,
validateStack: makeStackFunc(2, 0), validateStack: makeStackFunc(2, 0),
memorySize: memoryMStore, memorySize: memoryMStore,
valid: true, valid: true,
}, },
MSTORE8: operation{ MSTORE8: {
execute: opMstore8, execute: opMstore8,
gasCost: gasMStore8, gasCost: gasMStore8,
memorySize: memoryMStore8, memorySize: memoryMStore8,
@ -336,71 +336,71 @@ func NewJumpTable() [256]operation {
valid: true, valid: true,
}, },
SLOAD: operation{ SLOAD: {
execute: opSload, execute: opSload,
gasCost: gasSLoad, gasCost: gasSLoad,
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
valid: true, valid: true,
}, },
SSTORE: operation{ SSTORE: {
execute: opSstore, execute: opSstore,
gasCost: gasSStore, gasCost: gasSStore,
validateStack: makeStackFunc(2, 0), validateStack: makeStackFunc(2, 0),
valid: true, valid: true,
}, },
JUMPDEST: operation{ JUMPDEST: {
execute: opJumpdest, execute: opJumpdest,
gasCost: constGasFunc(params.JumpdestGas), gasCost: constGasFunc(params.JumpdestGas),
validateStack: makeStackFunc(0, 0), validateStack: makeStackFunc(0, 0),
valid: true, valid: true,
}, },
PC: operation{ PC: {
execute: opPc, execute: opPc,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
MSIZE: operation{ MSIZE: {
execute: opMsize, execute: opMsize,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
GAS: operation{ GAS: {
execute: opGas, execute: opGas,
gasCost: constGasFunc(GasQuickStep), gasCost: constGasFunc(GasQuickStep),
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
CREATE: operation{ CREATE: {
execute: opCreate, execute: opCreate,
gasCost: gasCreate, gasCost: gasCreate,
validateStack: makeStackFunc(3, 1), validateStack: makeStackFunc(3, 1),
memorySize: memoryCreate, memorySize: memoryCreate,
valid: true, valid: true,
}, },
CALL: operation{ CALL: {
execute: opCall, execute: opCall,
gasCost: gasCall, gasCost: gasCall,
validateStack: makeStackFunc(7, 1), validateStack: makeStackFunc(7, 1),
memorySize: memoryCall, memorySize: memoryCall,
valid: true, valid: true,
}, },
CALLCODE: operation{ CALLCODE: {
execute: opCallCode, execute: opCallCode,
gasCost: gasCallCode, gasCost: gasCallCode,
validateStack: makeStackFunc(7, 1), validateStack: makeStackFunc(7, 1),
memorySize: memoryCall, memorySize: memoryCall,
valid: true, valid: true,
}, },
DELEGATECALL: operation{ DELEGATECALL: {
execute: opDelegateCall, execute: opDelegateCall,
gasCost: gasDelegateCall, gasCost: gasDelegateCall,
validateStack: makeStackFunc(6, 1), validateStack: makeStackFunc(6, 1),
memorySize: memoryDelegateCall, memorySize: memoryDelegateCall,
valid: true, valid: true,
}, },
RETURN: operation{ RETURN: {
execute: opReturn, execute: opReturn,
gasCost: gasReturn, gasCost: gasReturn,
validateStack: makeStackFunc(2, 0), validateStack: makeStackFunc(2, 0),
@ -408,448 +408,448 @@ func NewJumpTable() [256]operation {
halts: true, halts: true,
valid: true, valid: true,
}, },
SUICIDE: operation{ SUICIDE: {
execute: opSuicide, execute: opSuicide,
gasCost: gasSuicide, gasCost: gasSuicide,
validateStack: makeStackFunc(1, 0), validateStack: makeStackFunc(1, 0),
halts: true, halts: true,
valid: true, valid: true,
}, },
JUMP: operation{ JUMP: {
execute: opJump, execute: opJump,
gasCost: constGasFunc(GasMidStep), gasCost: constGasFunc(GasMidStep),
validateStack: makeStackFunc(1, 0), validateStack: makeStackFunc(1, 0),
jumps: true, jumps: true,
valid: true, valid: true,
}, },
JUMPI: operation{ JUMPI: {
execute: opJumpi, execute: opJumpi,
gasCost: constGasFunc(GasSlowStep), gasCost: constGasFunc(GasSlowStep),
validateStack: makeStackFunc(2, 0), validateStack: makeStackFunc(2, 0),
jumps: true, jumps: true,
valid: true, valid: true,
}, },
STOP: operation{ STOP: {
execute: opStop, execute: opStop,
gasCost: constGasFunc(Zero), gasCost: constGasFunc(Zero),
validateStack: makeStackFunc(0, 0), validateStack: makeStackFunc(0, 0),
halts: true, halts: true,
valid: true, valid: true,
}, },
LOG0: operation{ LOG0: {
execute: makeLog(0), execute: makeLog(0),
gasCost: makeGasLog(0), gasCost: makeGasLog(0),
validateStack: makeStackFunc(2, 0), validateStack: makeStackFunc(2, 0),
memorySize: memoryLog, memorySize: memoryLog,
valid: true, valid: true,
}, },
LOG1: operation{ LOG1: {
execute: makeLog(1), execute: makeLog(1),
gasCost: makeGasLog(1), gasCost: makeGasLog(1),
validateStack: makeStackFunc(3, 0), validateStack: makeStackFunc(3, 0),
memorySize: memoryLog, memorySize: memoryLog,
valid: true, valid: true,
}, },
LOG2: operation{ LOG2: {
execute: makeLog(2), execute: makeLog(2),
gasCost: makeGasLog(2), gasCost: makeGasLog(2),
validateStack: makeStackFunc(4, 0), validateStack: makeStackFunc(4, 0),
memorySize: memoryLog, memorySize: memoryLog,
valid: true, valid: true,
}, },
LOG3: operation{ LOG3: {
execute: makeLog(3), execute: makeLog(3),
gasCost: makeGasLog(3), gasCost: makeGasLog(3),
validateStack: makeStackFunc(5, 0), validateStack: makeStackFunc(5, 0),
memorySize: memoryLog, memorySize: memoryLog,
valid: true, valid: true,
}, },
LOG4: operation{ LOG4: {
execute: makeLog(4), execute: makeLog(4),
gasCost: makeGasLog(4), gasCost: makeGasLog(4),
validateStack: makeStackFunc(6, 0), validateStack: makeStackFunc(6, 0),
memorySize: memoryLog, memorySize: memoryLog,
valid: true, valid: true,
}, },
SWAP1: operation{ SWAP1: {
execute: makeSwap(1), execute: makeSwap(1),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(2, 0), validateStack: makeStackFunc(2, 0),
valid: true, valid: true,
}, },
SWAP2: operation{ SWAP2: {
execute: makeSwap(2), execute: makeSwap(2),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(3, 0), validateStack: makeStackFunc(3, 0),
valid: true, valid: true,
}, },
SWAP3: operation{ SWAP3: {
execute: makeSwap(3), execute: makeSwap(3),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(4, 0), validateStack: makeStackFunc(4, 0),
valid: true, valid: true,
}, },
SWAP4: operation{ SWAP4: {
execute: makeSwap(4), execute: makeSwap(4),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(5, 0), validateStack: makeStackFunc(5, 0),
valid: true, valid: true,
}, },
SWAP5: operation{ SWAP5: {
execute: makeSwap(5), execute: makeSwap(5),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(6, 0), validateStack: makeStackFunc(6, 0),
valid: true, valid: true,
}, },
SWAP6: operation{ SWAP6: {
execute: makeSwap(6), execute: makeSwap(6),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(7, 0), validateStack: makeStackFunc(7, 0),
valid: true, valid: true,
}, },
SWAP7: operation{ SWAP7: {
execute: makeSwap(7), execute: makeSwap(7),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(8, 0), validateStack: makeStackFunc(8, 0),
valid: true, valid: true,
}, },
SWAP8: operation{ SWAP8: {
execute: makeSwap(8), execute: makeSwap(8),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(9, 0), validateStack: makeStackFunc(9, 0),
valid: true, valid: true,
}, },
SWAP9: operation{ SWAP9: {
execute: makeSwap(9), execute: makeSwap(9),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(10, 0), validateStack: makeStackFunc(10, 0),
valid: true, valid: true,
}, },
SWAP10: operation{ SWAP10: {
execute: makeSwap(10), execute: makeSwap(10),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(11, 0), validateStack: makeStackFunc(11, 0),
valid: true, valid: true,
}, },
SWAP11: operation{ SWAP11: {
execute: makeSwap(11), execute: makeSwap(11),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(12, 0), validateStack: makeStackFunc(12, 0),
valid: true, valid: true,
}, },
SWAP12: operation{ SWAP12: {
execute: makeSwap(12), execute: makeSwap(12),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(13, 0), validateStack: makeStackFunc(13, 0),
valid: true, valid: true,
}, },
SWAP13: operation{ SWAP13: {
execute: makeSwap(13), execute: makeSwap(13),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(14, 0), validateStack: makeStackFunc(14, 0),
valid: true, valid: true,
}, },
SWAP14: operation{ SWAP14: {
execute: makeSwap(14), execute: makeSwap(14),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(15, 0), validateStack: makeStackFunc(15, 0),
valid: true, valid: true,
}, },
SWAP15: operation{ SWAP15: {
execute: makeSwap(15), execute: makeSwap(15),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(16, 0), validateStack: makeStackFunc(16, 0),
valid: true, valid: true,
}, },
SWAP16: operation{ SWAP16: {
execute: makeSwap(16), execute: makeSwap(16),
gasCost: gasSwap, gasCost: gasSwap,
validateStack: makeStackFunc(17, 0), validateStack: makeStackFunc(17, 0),
valid: true, valid: true,
}, },
PUSH1: operation{ PUSH1: {
execute: makePush(1, big.NewInt(1)), execute: makePush(1, big.NewInt(1)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH2: operation{ PUSH2: {
execute: makePush(2, big.NewInt(2)), execute: makePush(2, big.NewInt(2)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH3: operation{ PUSH3: {
execute: makePush(3, big.NewInt(3)), execute: makePush(3, big.NewInt(3)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH4: operation{ PUSH4: {
execute: makePush(4, big.NewInt(4)), execute: makePush(4, big.NewInt(4)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH5: operation{ PUSH5: {
execute: makePush(5, big.NewInt(5)), execute: makePush(5, big.NewInt(5)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH6: operation{ PUSH6: {
execute: makePush(6, big.NewInt(6)), execute: makePush(6, big.NewInt(6)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH7: operation{ PUSH7: {
execute: makePush(7, big.NewInt(7)), execute: makePush(7, big.NewInt(7)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH8: operation{ PUSH8: {
execute: makePush(8, big.NewInt(8)), execute: makePush(8, big.NewInt(8)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH9: operation{ PUSH9: {
execute: makePush(9, big.NewInt(9)), execute: makePush(9, big.NewInt(9)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH10: operation{ PUSH10: {
execute: makePush(10, big.NewInt(10)), execute: makePush(10, big.NewInt(10)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH11: operation{ PUSH11: {
execute: makePush(11, big.NewInt(11)), execute: makePush(11, big.NewInt(11)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH12: operation{ PUSH12: {
execute: makePush(12, big.NewInt(12)), execute: makePush(12, big.NewInt(12)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH13: operation{ PUSH13: {
execute: makePush(13, big.NewInt(13)), execute: makePush(13, big.NewInt(13)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH14: operation{ PUSH14: {
execute: makePush(14, big.NewInt(14)), execute: makePush(14, big.NewInt(14)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH15: operation{ PUSH15: {
execute: makePush(15, big.NewInt(15)), execute: makePush(15, big.NewInt(15)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH16: operation{ PUSH16: {
execute: makePush(16, big.NewInt(16)), execute: makePush(16, big.NewInt(16)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH17: operation{ PUSH17: {
execute: makePush(17, big.NewInt(17)), execute: makePush(17, big.NewInt(17)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH18: operation{ PUSH18: {
execute: makePush(18, big.NewInt(18)), execute: makePush(18, big.NewInt(18)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH19: operation{ PUSH19: {
execute: makePush(19, big.NewInt(19)), execute: makePush(19, big.NewInt(19)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH20: operation{ PUSH20: {
execute: makePush(20, big.NewInt(20)), execute: makePush(20, big.NewInt(20)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH21: operation{ PUSH21: {
execute: makePush(21, big.NewInt(21)), execute: makePush(21, big.NewInt(21)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH22: operation{ PUSH22: {
execute: makePush(22, big.NewInt(22)), execute: makePush(22, big.NewInt(22)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH23: operation{ PUSH23: {
execute: makePush(23, big.NewInt(23)), execute: makePush(23, big.NewInt(23)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH24: operation{ PUSH24: {
execute: makePush(24, big.NewInt(24)), execute: makePush(24, big.NewInt(24)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH25: operation{ PUSH25: {
execute: makePush(25, big.NewInt(25)), execute: makePush(25, big.NewInt(25)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH26: operation{ PUSH26: {
execute: makePush(26, big.NewInt(26)), execute: makePush(26, big.NewInt(26)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH27: operation{ PUSH27: {
execute: makePush(27, big.NewInt(27)), execute: makePush(27, big.NewInt(27)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH28: operation{ PUSH28: {
execute: makePush(28, big.NewInt(28)), execute: makePush(28, big.NewInt(28)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH29: operation{ PUSH29: {
execute: makePush(29, big.NewInt(29)), execute: makePush(29, big.NewInt(29)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH30: operation{ PUSH30: {
execute: makePush(30, big.NewInt(30)), execute: makePush(30, big.NewInt(30)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH31: operation{ PUSH31: {
execute: makePush(31, big.NewInt(31)), execute: makePush(31, big.NewInt(31)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
PUSH32: operation{ PUSH32: {
execute: makePush(32, big.NewInt(32)), execute: makePush(32, big.NewInt(32)),
gasCost: gasPush, gasCost: gasPush,
validateStack: makeStackFunc(0, 1), validateStack: makeStackFunc(0, 1),
valid: true, valid: true,
}, },
DUP1: operation{ DUP1: {
execute: makeDup(1), execute: makeDup(1),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(1, 1), validateStack: makeStackFunc(1, 1),
valid: true, valid: true,
}, },
DUP2: operation{ DUP2: {
execute: makeDup(2), execute: makeDup(2),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(2, 1), validateStack: makeStackFunc(2, 1),
valid: true, valid: true,
}, },
DUP3: operation{ DUP3: {
execute: makeDup(3), execute: makeDup(3),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(3, 1), validateStack: makeStackFunc(3, 1),
valid: true, valid: true,
}, },
DUP4: operation{ DUP4: {
execute: makeDup(4), execute: makeDup(4),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(4, 1), validateStack: makeStackFunc(4, 1),
valid: true, valid: true,
}, },
DUP5: operation{ DUP5: {
execute: makeDup(5), execute: makeDup(5),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(5, 1), validateStack: makeStackFunc(5, 1),
valid: true, valid: true,
}, },
DUP6: operation{ DUP6: {
execute: makeDup(6), execute: makeDup(6),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(6, 1), validateStack: makeStackFunc(6, 1),
valid: true, valid: true,
}, },
DUP7: operation{ DUP7: {
execute: makeDup(7), execute: makeDup(7),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(7, 1), validateStack: makeStackFunc(7, 1),
valid: true, valid: true,
}, },
DUP8: operation{ DUP8: {
execute: makeDup(8), execute: makeDup(8),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(8, 1), validateStack: makeStackFunc(8, 1),
valid: true, valid: true,
}, },
DUP9: operation{ DUP9: {
execute: makeDup(9), execute: makeDup(9),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(9, 1), validateStack: makeStackFunc(9, 1),
valid: true, valid: true,
}, },
DUP10: operation{ DUP10: {
execute: makeDup(10), execute: makeDup(10),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(10, 1), validateStack: makeStackFunc(10, 1),
valid: true, valid: true,
}, },
DUP11: operation{ DUP11: {
execute: makeDup(11), execute: makeDup(11),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(11, 1), validateStack: makeStackFunc(11, 1),
valid: true, valid: true,
}, },
DUP12: operation{ DUP12: {
execute: makeDup(12), execute: makeDup(12),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(12, 1), validateStack: makeStackFunc(12, 1),
valid: true, valid: true,
}, },
DUP13: operation{ DUP13: {
execute: makeDup(13), execute: makeDup(13),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(13, 1), validateStack: makeStackFunc(13, 1),
valid: true, valid: true,
}, },
DUP14: operation{ DUP14: {
execute: makeDup(14), execute: makeDup(14),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(14, 1), validateStack: makeStackFunc(14, 1),
valid: true, valid: true,
}, },
DUP15: operation{ DUP15: {
execute: makeDup(15), execute: makeDup(15),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(15, 1), validateStack: makeStackFunc(15, 1),
valid: true, valid: true,
}, },
DUP16: operation{ DUP16: {
execute: makeDup(16), execute: makeDup(16),
gasCost: gasDup, gasCost: gasDup,
validateStack: makeStackFunc(16, 1), validateStack: makeStackFunc(16, 1),

@ -217,7 +217,7 @@ func TestValidateSignatureValues(t *testing.T) {
func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) { func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
sum := f(msg) sum := f(msg)
if bytes.Compare(exp, sum) != 0 { if !bytes.Equal(exp, sum) {
t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum) t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
} }
} }

@ -109,7 +109,7 @@ func (curve secgNamedCurve) Equal(curve2 secgNamedCurve) bool {
if len(curve) != len(curve2) { if len(curve) != len(curve2) {
return false return false
} }
for i, _ := range curve { for i := range curve {
if curve[i] != curve2[i] { if curve[i] != curve2[i] {
return false return false
} }
@ -157,7 +157,7 @@ func (a asnAlgorithmIdentifier) Cmp(b asnAlgorithmIdentifier) bool {
if len(a.Algorithm) != len(b.Algorithm) { if len(a.Algorithm) != len(b.Algorithm) {
return false return false
} }
for i, _ := range a.Algorithm { for i := range a.Algorithm {
if a.Algorithm[i] != b.Algorithm[i] { if a.Algorithm[i] != b.Algorithm[i] {
return false return false
} }
@ -306,7 +306,7 @@ func (a asnECDHAlgorithm) Cmp(b asnECDHAlgorithm) bool {
if len(a.Algorithm) != len(b.Algorithm) { if len(a.Algorithm) != len(b.Algorithm) {
return false return false
} }
for i, _ := range a.Algorithm { for i := range a.Algorithm {
if a.Algorithm[i] != b.Algorithm[i] { if a.Algorithm[i] != b.Algorithm[i] {
return false return false
} }
@ -325,7 +325,7 @@ func (a asnKeyDerivationFunction) Cmp(b asnKeyDerivationFunction) bool {
if len(a.Algorithm) != len(b.Algorithm) { if len(a.Algorithm) != len(b.Algorithm) {
return false return false
} }
for i, _ := range a.Algorithm { for i := range a.Algorithm {
if a.Algorithm[i] != b.Algorithm[i] { if a.Algorithm[i] != b.Algorithm[i] {
return false return false
} }
@ -360,7 +360,7 @@ func (a asnSymmetricEncryption) Cmp(b asnSymmetricEncryption) bool {
if len(a.Algorithm) != len(b.Algorithm) { if len(a.Algorithm) != len(b.Algorithm) {
return false return false
} }
for i, _ := range a.Algorithm { for i := range a.Algorithm {
if a.Algorithm[i] != b.Algorithm[i] { if a.Algorithm[i] != b.Algorithm[i] {
return false return false
} }
@ -380,7 +380,7 @@ func (a asnMessageAuthenticationCode) Cmp(b asnMessageAuthenticationCode) bool {
if len(a.Algorithm) != len(b.Algorithm) { if len(a.Algorithm) != len(b.Algorithm) {
return false return false
} }
for i, _ := range a.Algorithm { for i := range a.Algorithm {
if a.Algorithm[i] != b.Algorithm[i] { if a.Algorithm[i] != b.Algorithm[i] {
return false return false
} }

@ -291,9 +291,8 @@ func Encrypt(rand io.Reader, pub *PublicKey, m, s1, s2 []byte) (ct []byte, err e
// Decrypt decrypts an ECIES ciphertext. // Decrypt decrypts an ECIES ciphertext.
func (prv *PrivateKey) Decrypt(rand io.Reader, c, s1, s2 []byte) (m []byte, err error) { func (prv *PrivateKey) Decrypt(rand io.Reader, c, s1, s2 []byte) (m []byte, err error) {
if c == nil || len(c) == 0 { if len(c) == 0 {
err = ErrInvalidMessage return nil, ErrInvalidMessage
return
} }
params := prv.PublicKey.Params params := prv.PublicKey.Params
if params == nil { if params == nil {

@ -492,17 +492,17 @@ type testCase struct {
} }
var testCases = []testCase{ var testCases = []testCase{
testCase{ {
Curve: elliptic.P256(), Curve: elliptic.P256(),
Name: "P256", Name: "P256",
Expected: true, Expected: true,
}, },
testCase{ {
Curve: elliptic.P384(), Curve: elliptic.P384(),
Name: "P384", Name: "P384",
Expected: true, Expected: true,
}, },
testCase{ {
Curve: elliptic.P521(), Curve: elliptic.P521(),
Name: "P521", Name: "P521",
Expected: true, Expected: true,

@ -201,7 +201,7 @@ func TestSqueezing(t *testing.T) {
d1 := newShakeHash() d1 := newShakeHash()
d1.Write([]byte(testString)) d1.Write([]byte(testString))
var multiple []byte var multiple []byte
for _ = range ref { for range ref {
one := make([]byte, 1) one := make([]byte, 1)
d1.Read(one) d1.Read(one)
multiple = append(multiple, one...) multiple = append(multiple, one...)

@ -19,7 +19,6 @@ package errs
import ( import (
"fmt" "fmt"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog" "github.com/ethereum/go-ethereum/logger/glog"
) )
@ -32,15 +31,10 @@ Fields:
Package: Package:
name of the package/component name of the package/component
Level:
a function mapping error code to logger.LogLevel (severity)
if not given, errors default to logger.InfoLevel
*/ */
type Errors struct { type Errors struct {
Errors map[int]string Errors map[int]string
Package string Package string
Level func(code int) logger.LogLevel
} }
/* /*
@ -58,7 +52,6 @@ type Error struct {
Code int Code int
Name string Name string
Package string Package string
level logger.LogLevel
message string message string
format string format string
params []interface{} params []interface{}
@ -69,15 +62,10 @@ func (self *Errors) New(code int, format string, params ...interface{}) *Error {
if !ok { if !ok {
panic("invalid error code") panic("invalid error code")
} }
level := logger.InfoLevel
if self.Level != nil {
level = self.Level(code)
}
return &Error{ return &Error{
Code: code, Code: code,
Name: name, Name: name,
Package: self.Package, Package: self.Package,
level: level,
format: format, format: format,
params: params, params: params,
} }
@ -98,13 +86,3 @@ func (self Error) Log(v glog.Verbose) {
v.Infoln(self) v.Infoln(self)
} }
} }
/*
err.Fatal() is true if err's severity level is 0 or 1 (logger.ErrorLevel or logger.Silence)
*/
func (self *Error) Fatal() (fatal bool) {
if self.level < logger.WarnLevel {
fatal = true
}
return
}

@ -19,8 +19,6 @@ package errs
import ( import (
"fmt" "fmt"
"testing" "testing"
"github.com/ethereum/go-ethereum/logger"
) )
func testErrors() *Errors { func testErrors() *Errors {
@ -30,14 +28,6 @@ func testErrors() *Errors {
0: "zero", 0: "zero",
1: "one", 1: "one",
}, },
Level: func(i int) (l logger.LogLevel) {
if i == 0 {
l = logger.ErrorLevel
} else {
l = logger.WarnLevel
}
return
},
} }
} }
@ -49,14 +39,3 @@ func TestErrorMessage(t *testing.T) {
t.Errorf("error message incorrect. expected %v, got %v", exp, message) t.Errorf("error message incorrect. expected %v, got %v", exp, message)
} }
} }
func TestErrorSeverity(t *testing.T) {
err0 := testErrors().New(0, "zero detail")
if !err0.Fatal() {
t.Errorf("error should be fatal")
}
err1 := testErrors().New(1, "one detail")
if err1.Fatal() {
t.Errorf("error should not be fatal")
}
}

@ -37,12 +37,12 @@ func TestMipmapUpgrade(t *testing.T) {
switch i { switch i {
case 1: case 1:
receipt := types.NewReceipt(nil, new(big.Int)) receipt := types.NewReceipt(nil, new(big.Int))
receipt.Logs = []*types.Log{&types.Log{Address: addr}} receipt.Logs = []*types.Log{{Address: addr}}
gen.AddUncheckedReceipt(receipt) gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt} receipts = types.Receipts{receipt}
case 2: case 2:
receipt := types.NewReceipt(nil, new(big.Int)) receipt := types.NewReceipt(nil, new(big.Int))
receipt.Logs = []*types.Log{&types.Log{Address: addr}} receipt.Logs = []*types.Log{{Address: addr}}
gen.AddUncheckedReceipt(receipt) gen.AddUncheckedReceipt(receipt)
receipts = types.Receipts{receipt} receipts = types.Receipts{receipt}
} }

@ -205,7 +205,7 @@ func (p *peer) FetchNodeData(request *fetchRequest) error {
// Convert the hash set to a retrievable slice // Convert the hash set to a retrievable slice
hashes := make([]common.Hash, 0, len(request.Hashes)) hashes := make([]common.Hash, 0, len(request.Hashes))
for hash, _ := range request.Hashes { for hash := range request.Hashes {
hashes = append(hashes, hash) hashes = append(hashes, hash)
} }
go p.getNodeData(hashes) go p.getNodeData(hashes)
@ -314,7 +314,7 @@ func (p *peer) MarkLacking(hash common.Hash) {
defer p.lock.Unlock() defer p.lock.Unlock()
for len(p.lacking) >= maxLackingHashes { for len(p.lacking) >= maxLackingHashes {
for drop, _ := range p.lacking { for drop := range p.lacking {
delete(p.lacking, drop) delete(p.lacking, drop)
break break
} }

@ -844,7 +844,7 @@ func (q *queue) expire(timeout time.Duration, pendPool map[string]*fetchRequest,
} }
} }
// Remove the expired requests from the pending pool // Remove the expired requests from the pending pool
for id, _ := range expiries { for id := range expiries {
delete(pendPool, id) delete(pendPool, id)
} }
return expiries return expiries
@ -1063,7 +1063,7 @@ func (q *queue) DeliverNodeData(id string, data [][]byte, callback func(int, boo
// If no data was retrieved, mark their hashes as unavailable for the origin peer // If no data was retrieved, mark their hashes as unavailable for the origin peer
if len(data) == 0 { if len(data) == 0 {
for hash, _ := range request.Hashes { for hash := range request.Hashes {
request.Peer.MarkLacking(hash) request.Peer.MarkLacking(hash)
} }
} }

@ -505,7 +505,7 @@ func (args *FilterCriteria) UnmarshalJSON(data []byte) error {
switch topic := t.(type) { switch topic := t.(type) {
case nil: case nil:
// ignore topic when matching logs // ignore topic when matching logs
args.Topics[i] = []common.Hash{common.Hash{}} args.Topics[i] = []common.Hash{{}}
case string: case string:
// match specific topic // match specific topic

@ -281,15 +281,15 @@ func TestLogFilter(t *testing.T) {
// match all // match all
0: {FilterCriteria{}, allLogs, ""}, 0: {FilterCriteria{}, allLogs, ""},
// match none due to no matching addresses // match none due to no matching addresses
1: {FilterCriteria{Addresses: []common.Address{common.Address{}, notUsedAddress}, Topics: [][]common.Hash{allLogs[0].Topics}}, []*types.Log{}, ""}, 1: {FilterCriteria{Addresses: []common.Address{{}, notUsedAddress}, Topics: [][]common.Hash{allLogs[0].Topics}}, []*types.Log{}, ""},
// match logs based on addresses, ignore topics // match logs based on addresses, ignore topics
2: {FilterCriteria{Addresses: []common.Address{firstAddr}}, allLogs[:2], ""}, 2: {FilterCriteria{Addresses: []common.Address{firstAddr}}, allLogs[:2], ""},
// match none due to no matching topics (match with address) // match none due to no matching topics (match with address)
3: {FilterCriteria{Addresses: []common.Address{secondAddr}, Topics: [][]common.Hash{[]common.Hash{notUsedTopic}}}, []*types.Log{}, ""}, 3: {FilterCriteria{Addresses: []common.Address{secondAddr}, Topics: [][]common.Hash{{notUsedTopic}}}, []*types.Log{}, ""},
// match logs based on addresses and topics // match logs based on addresses and topics
4: {FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{[]common.Hash{firstTopic, secondTopic}}}, allLogs[3:5], ""}, 4: {FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, allLogs[3:5], ""},
// match logs based on multiple addresses and "or" topics // match logs based on multiple addresses and "or" topics
5: {FilterCriteria{Addresses: []common.Address{secondAddr, thirdAddress}, Topics: [][]common.Hash{[]common.Hash{firstTopic, secondTopic}}}, allLogs[2:5], ""}, 5: {FilterCriteria{Addresses: []common.Address{secondAddr, thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, allLogs[2:5], ""},
// logs in the pending block // logs in the pending block
6: {FilterCriteria{Addresses: []common.Address{firstAddr}, FromBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64())}, allLogs[:2], ""}, 6: {FilterCriteria{Addresses: []common.Address{firstAddr}, FromBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64())}, allLogs[:2], ""},
// mined logs with block num >= 2 or pending logs // mined logs with block num >= 2 or pending logs
@ -299,9 +299,9 @@ func TestLogFilter(t *testing.T) {
// all "mined" logs // all "mined" logs
9: {FilterCriteria{ToBlock: big.NewInt(rpc.LatestBlockNumber.Int64())}, allLogs, ""}, 9: {FilterCriteria{ToBlock: big.NewInt(rpc.LatestBlockNumber.Int64())}, allLogs, ""},
// all "mined" logs with 1>= block num <=2 and topic secondTopic // all "mined" logs with 1>= block num <=2 and topic secondTopic
10: {FilterCriteria{FromBlock: big.NewInt(1), ToBlock: big.NewInt(2), Topics: [][]common.Hash{[]common.Hash{secondTopic}}}, allLogs[3:4], ""}, 10: {FilterCriteria{FromBlock: big.NewInt(1), ToBlock: big.NewInt(2), Topics: [][]common.Hash{{secondTopic}}}, allLogs[3:4], ""},
// all "mined" and pending logs with topic firstTopic // all "mined" and pending logs with topic firstTopic
11: {FilterCriteria{FromBlock: big.NewInt(rpc.LatestBlockNumber.Int64()), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), Topics: [][]common.Hash{[]common.Hash{firstTopic}}}, expectedCase11, ""}, 11: {FilterCriteria{FromBlock: big.NewInt(rpc.LatestBlockNumber.Int64()), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), Topics: [][]common.Hash{{firstTopic}}}, expectedCase11, ""},
} }
) )
@ -402,19 +402,19 @@ func TestPendingLogsSubscription(t *testing.T) {
// match all // match all
{FilterCriteria{}, convertLogs(allLogs), nil, nil}, {FilterCriteria{}, convertLogs(allLogs), nil, nil},
// match none due to no matching addresses // match none due to no matching addresses
{FilterCriteria{Addresses: []common.Address{common.Address{}, notUsedAddress}, Topics: [][]common.Hash{[]common.Hash{}}}, []*types.Log{}, nil, nil}, {FilterCriteria{Addresses: []common.Address{{}, notUsedAddress}, Topics: [][]common.Hash{{}}}, []*types.Log{}, nil, nil},
// match logs based on addresses, ignore topics // match logs based on addresses, ignore topics
{FilterCriteria{Addresses: []common.Address{firstAddr}}, append(convertLogs(allLogs[:2]), allLogs[5].Logs[3]), nil, nil}, {FilterCriteria{Addresses: []common.Address{firstAddr}}, append(convertLogs(allLogs[:2]), allLogs[5].Logs[3]), nil, nil},
// match none due to no matching topics (match with address) // match none due to no matching topics (match with address)
{FilterCriteria{Addresses: []common.Address{secondAddr}, Topics: [][]common.Hash{[]common.Hash{notUsedTopic}}}, []*types.Log{}, nil, nil}, {FilterCriteria{Addresses: []common.Address{secondAddr}, Topics: [][]common.Hash{{notUsedTopic}}}, []*types.Log{}, nil, nil},
// match logs based on addresses and topics // match logs based on addresses and topics
{FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{[]common.Hash{firstTopic, secondTopic}}}, append(convertLogs(allLogs[3:5]), allLogs[5].Logs[0]), nil, nil}, {FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, append(convertLogs(allLogs[3:5]), allLogs[5].Logs[0]), nil, nil},
// match logs based on multiple addresses and "or" topics // match logs based on multiple addresses and "or" topics
{FilterCriteria{Addresses: []common.Address{secondAddr, thirdAddress}, Topics: [][]common.Hash{[]common.Hash{firstTopic, secondTopic}}}, append(convertLogs(allLogs[2:5]), allLogs[5].Logs[0]), nil, nil}, {FilterCriteria{Addresses: []common.Address{secondAddr, thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, append(convertLogs(allLogs[2:5]), allLogs[5].Logs[0]), nil, nil},
// block numbers are ignored for filters created with New***Filter, these return all logs that match the given criterias when the state changes // block numbers are ignored for filters created with New***Filter, these return all logs that match the given criterias when the state changes
{FilterCriteria{Addresses: []common.Address{firstAddr}, FromBlock: big.NewInt(2), ToBlock: big.NewInt(3)}, append(convertLogs(allLogs[:2]), allLogs[5].Logs[3]), nil, nil}, {FilterCriteria{Addresses: []common.Address{firstAddr}, FromBlock: big.NewInt(2), ToBlock: big.NewInt(3)}, append(convertLogs(allLogs[:2]), allLogs[5].Logs[3]), nil, nil},
// multiple pending logs, should match only 2 topics from the logs in block 5 // multiple pending logs, should match only 2 topics from the logs in block 5
{FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{[]common.Hash{firstTopic, forthTopic}}}, []*types.Log{allLogs[5].Logs[0], allLogs[5].Logs[2]}, nil, nil}, {FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{{firstTopic, forthTopic}}}, []*types.Log{allLogs[5].Logs[0], allLogs[5].Logs[2]}, nil, nil},
} }
) )

@ -210,7 +210,7 @@ func TestFilters(t *testing.T) {
filter := New(backend, true) filter := New(backend, true)
filter.SetAddresses([]common.Address{addr}) filter.SetAddresses([]common.Address{addr})
filter.SetTopics([][]common.Hash{[]common.Hash{hash1, hash2, hash3, hash4}}) filter.SetTopics([][]common.Hash{{hash1, hash2, hash3, hash4}})
filter.SetBeginBlock(0) filter.SetBeginBlock(0)
filter.SetEndBlock(-1) filter.SetEndBlock(-1)
@ -221,7 +221,7 @@ func TestFilters(t *testing.T) {
filter = New(backend, true) filter = New(backend, true)
filter.SetAddresses([]common.Address{addr}) filter.SetAddresses([]common.Address{addr})
filter.SetTopics([][]common.Hash{[]common.Hash{hash3}}) filter.SetTopics([][]common.Hash{{hash3}})
filter.SetBeginBlock(900) filter.SetBeginBlock(900)
filter.SetEndBlock(999) filter.SetEndBlock(999)
logs, _ = filter.Find(context.Background()) logs, _ = filter.Find(context.Background())
@ -234,7 +234,7 @@ func TestFilters(t *testing.T) {
filter = New(backend, true) filter = New(backend, true)
filter.SetAddresses([]common.Address{addr}) filter.SetAddresses([]common.Address{addr})
filter.SetTopics([][]common.Hash{[]common.Hash{hash3}}) filter.SetTopics([][]common.Hash{{hash3}})
filter.SetBeginBlock(990) filter.SetBeginBlock(990)
filter.SetEndBlock(-1) filter.SetEndBlock(-1)
logs, _ = filter.Find(context.Background()) logs, _ = filter.Find(context.Background())
@ -246,7 +246,7 @@ func TestFilters(t *testing.T) {
} }
filter = New(backend, true) filter = New(backend, true)
filter.SetTopics([][]common.Hash{[]common.Hash{hash1, hash2}}) filter.SetTopics([][]common.Hash{{hash1, hash2}})
filter.SetBeginBlock(1) filter.SetBeginBlock(1)
filter.SetEndBlock(10) filter.SetEndBlock(10)
@ -257,7 +257,7 @@ func TestFilters(t *testing.T) {
failHash := common.BytesToHash([]byte("fail")) failHash := common.BytesToHash([]byte("fail"))
filter = New(backend, true) filter = New(backend, true)
filter.SetTopics([][]common.Hash{[]common.Hash{failHash}}) filter.SetTopics([][]common.Hash{{failHash}})
filter.SetBeginBlock(0) filter.SetBeginBlock(0)
filter.SetEndBlock(-1) filter.SetEndBlock(-1)
@ -278,7 +278,7 @@ func TestFilters(t *testing.T) {
} }
filter = New(backend, true) filter = New(backend, true)
filter.SetTopics([][]common.Hash{[]common.Hash{failHash}, []common.Hash{hash1}}) filter.SetTopics([][]common.Hash{{failHash}, {hash1}})
filter.SetBeginBlock(0) filter.SetBeginBlock(0)
filter.SetEndBlock(-1) filter.SetEndBlock(-1)

@ -607,38 +607,16 @@ func (pm *ProtocolManager) handleMsg(p *peer) error {
} }
case msg.Code == NewBlockHashesMsg: case msg.Code == NewBlockHashesMsg:
// Retrieve and deserialize the remote new block hashes notification var announces newBlockHashesData
type announce struct { if err := msg.Decode(&announces); err != nil {
Hash common.Hash
Number uint64
}
var announces = []announce{}
if p.version < eth62 {
// We're running the old protocol, make block number unknown (0)
var hashes []common.Hash
if err := msg.Decode(&hashes); err != nil {
return errResp(ErrDecode, "%v: %v", msg, err) return errResp(ErrDecode, "%v: %v", msg, err)
} }
for _, hash := range hashes {
announces = append(announces, announce{hash, 0})
}
} else {
// Otherwise extract both block hash and number
var request newBlockHashesData
if err := msg.Decode(&request); err != nil {
return errResp(ErrDecode, "%v: %v", msg, err)
}
for _, block := range request {
announces = append(announces, announce{block.Hash, block.Number})
}
}
// Mark the hashes as present at the remote node // Mark the hashes as present at the remote node
for _, block := range announces { for _, block := range announces {
p.MarkBlock(block.Hash) p.MarkBlock(block.Hash)
} }
// Schedule all the unknown hashes for retrieval // Schedule all the unknown hashes for retrieval
unknown := make([]announce, 0, len(announces)) unknown := make(newBlockHashesData, 0, len(announces))
for _, block := range announces { for _, block := range announces {
if !pm.blockchain.HasBlock(block.Hash) { if !pm.blockchain.HasBlock(block.Hash) {
unknown = append(unknown, block) unknown = append(unknown, block)

@ -75,7 +75,7 @@ func testGetBlockHeaders(t *testing.T, protocol int) {
// Create a "random" unknown hash for testing // Create a "random" unknown hash for testing
var unknown common.Hash var unknown common.Hash
for i, _ := range unknown { for i := range unknown {
unknown[i] = byte(i) unknown[i] = byte(i)
} }
// Create a batch of tests for various scenarios // Create a batch of tests for various scenarios
@ -246,17 +246,17 @@ func testGetBlockBodies(t *testing.T, protocol int) {
{limit + 1, nil, nil, limit}, // No more than the possible block count should be returned {limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
{0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable {0, []common.Hash{pm.blockchain.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
{0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable {0, []common.Hash{pm.blockchain.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
{0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned {0, []common.Hash{{}}, []bool{false}, 0}, // A non existent block should not be returned
// Existing and non-existing blocks interleaved should not cause problems // Existing and non-existing blocks interleaved should not cause problems
{0, []common.Hash{ {0, []common.Hash{
common.Hash{}, {},
pm.blockchain.GetBlockByNumber(1).Hash(), pm.blockchain.GetBlockByNumber(1).Hash(),
common.Hash{}, {},
pm.blockchain.GetBlockByNumber(10).Hash(), pm.blockchain.GetBlockByNumber(10).Hash(),
common.Hash{}, {},
pm.blockchain.GetBlockByNumber(100).Hash(), pm.blockchain.GetBlockByNumber(100).Hash(),
common.Hash{}, {},
}, []bool{false, true, false, true, false, true, false}, 3}, }, []bool{false, true, false, true, false, true, false}, 3},
} }
// Run each of the tests and verify the results against the chain // Run each of the tests and verify the results against the chain

@ -178,7 +178,7 @@ func testSendTransactions(t *testing.T, protocol int) {
func TestGetBlockHeadersDataEncodeDecode(t *testing.T) { func TestGetBlockHeadersDataEncodeDecode(t *testing.T) {
// Create a "random" hash for testing // Create a "random" hash for testing
var hash common.Hash var hash common.Hash
for i, _ := range hash { for i := range hash {
hash[i] = byte(i) hash[i] = byte(i)
} }
// Assemble some table driven tests // Assemble some table driven tests

@ -67,7 +67,7 @@ func (db *MemDatabase) Keys() [][]byte {
defer db.lock.RUnlock() defer db.lock.RUnlock()
keys := [][]byte{} keys := [][]byte{}
for key, _ := range db.db { for key := range db.db {
keys = append(keys, []byte(key)) keys = append(keys, []byte(key))
} }
return keys return keys

@ -326,7 +326,7 @@ func (s *Service) login(in *json.Decoder, out *json.Encoder) error {
Secret: s.pass, Secret: s.pass,
} }
login := map[string][]interface{}{ login := map[string][]interface{}{
"emit": []interface{}{"hello", auth}, "emit": {"hello", auth},
} }
if err := out.Encode(login); err != nil { if err := out.Encode(login); err != nil {
return err return err
@ -365,7 +365,7 @@ func (s *Service) reportLatency(out *json.Encoder) error {
start := time.Now() start := time.Now()
ping := map[string][]interface{}{ ping := map[string][]interface{}{
"emit": []interface{}{"node-ping", map[string]string{ "emit": {"node-ping", map[string]string{
"id": s.node, "id": s.node,
"clientTime": start.String(), "clientTime": start.String(),
}}, }},
@ -383,15 +383,12 @@ func (s *Service) reportLatency(out *json.Encoder) error {
} }
// Send back the measured latency // Send back the measured latency
latency := map[string][]interface{}{ latency := map[string][]interface{}{
"emit": []interface{}{"latency", map[string]string{ "emit": {"latency", map[string]string{
"id": s.node, "id": s.node,
"latency": strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000)), "latency": strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000)),
}}, }},
} }
if err := out.Encode(latency); err != nil { return out.Encode(latency)
return err
}
return nil
} }
// blockStats is the information to report about individual blocks. // blockStats is the information to report about individual blocks.
@ -438,12 +435,9 @@ func (s *Service) reportBlock(out *json.Encoder, block *types.Block) error {
"block": s.assembleBlockStats(block), "block": s.assembleBlockStats(block),
} }
report := map[string][]interface{}{ report := map[string][]interface{}{
"emit": []interface{}{"block", stats}, "emit": {"block", stats},
} }
if err := out.Encode(report); err != nil { return out.Encode(report)
return err
}
return nil
} }
// assembleBlockStats retrieves any required metadata to report a single block // assembleBlockStats retrieves any required metadata to report a single block
@ -497,9 +491,7 @@ func (s *Service) reportHistory(out *json.Encoder, list []uint64) error {
indexes := make([]uint64, 0, historyUpdateRange) indexes := make([]uint64, 0, historyUpdateRange)
if len(list) > 0 { if len(list) > 0 {
// Specific indexes requested, send them back in particular // Specific indexes requested, send them back in particular
for _, idx := range list { indexes = append(indexes, list...)
indexes = append(indexes, idx)
}
} else { } else {
// No indexes requested, send back the top ones // No indexes requested, send back the top ones
var head *types.Header var head *types.Header
@ -531,12 +523,9 @@ func (s *Service) reportHistory(out *json.Encoder, list []uint64) error {
"history": history, "history": history,
} }
report := map[string][]interface{}{ report := map[string][]interface{}{
"emit": []interface{}{"history", stats}, "emit": {"history", stats},
} }
if err := out.Encode(report); err != nil { return out.Encode(report)
return err
}
return nil
} }
// pendStats is the information to report about pending transactions. // pendStats is the information to report about pending transactions.
@ -562,12 +551,9 @@ func (s *Service) reportPending(out *json.Encoder) error {
}, },
} }
report := map[string][]interface{}{ report := map[string][]interface{}{
"emit": []interface{}{"pending", stats}, "emit": {"pending", stats},
} }
if err := out.Encode(report); err != nil { return out.Encode(report)
return err
}
return nil
} }
// blockStats is the information to report about the local node. // blockStats is the information to report about the local node.
@ -616,10 +602,7 @@ func (s *Service) reportStats(out *json.Encoder) error {
}, },
} }
report := map[string][]interface{}{ report := map[string][]interface{}{
"emit": []interface{}{"stats", stats}, "emit": {"stats", stats},
} }
if err := out.Encode(report); err != nil { return out.Encode(report)
return err
}
return nil
} }

@ -144,7 +144,7 @@ func TestMuxConcurrent(t *testing.T) {
func emptySubscriber(mux *TypeMux, types ...interface{}) { func emptySubscriber(mux *TypeMux, types ...interface{}) {
s := mux.Subscribe(testEvent(0)) s := mux.Subscribe(testEvent(0))
go func() { go func() {
for _ = range s.Chan() { for range s.Chan() {
} }
}() }()
} }
@ -187,7 +187,7 @@ func BenchmarkChanSend(b *testing.B) {
c := make(chan interface{}) c := make(chan interface{})
closed := make(chan struct{}) closed := make(chan struct{})
go func() { go func() {
for _ = range c { for range c {
} }
}() }()

@ -34,7 +34,7 @@ func (self Generic) Compare(f Filter) bool {
strMatch = false strMatch = false
} }
for k, _ := range self.Data { for k := range self.Data {
if _, ok := filter.Data[k]; !ok { if _, ok := filter.Data[k]; !ok {
return false return false
} }

@ -664,7 +664,7 @@ func (f *lightFetcher) updateMaxConfirmedTd(td *big.Int) {
f.lastUpdateStats.next = newEntry f.lastUpdateStats.next = newEntry
} }
f.lastUpdateStats = newEntry f.lastUpdateStats = newEntry
for p, _ := range f.peers { for p := range f.peers {
f.checkUpdateStats(p, newEntry) f.checkUpdateStats(p, newEntry)
} }
} }

@ -126,7 +126,7 @@ func (self *ClientManager) removeNode(node *cmNode) {
// recalc sumWeight // recalc sumWeight
func (self *ClientManager) updateNodes(time int64) (rce bool) { func (self *ClientManager) updateNodes(time int64) (rce bool) {
var sumWeight, rcSum uint64 var sumWeight, rcSum uint64
for node, _ := range self.nodes { for node := range self.nodes {
rc := node.recharging rc := node.recharging
node.update(time) node.update(time)
if rc && !node.recharging { if rc && !node.recharging {
@ -145,13 +145,13 @@ func (self *ClientManager) updateNodes(time int64) (rce bool) {
func (self *ClientManager) update(time int64) { func (self *ClientManager) update(time int64) {
for { for {
firstTime := time firstTime := time
for node, _ := range self.nodes { for node := range self.nodes {
if node.recharging && node.finishRecharge < firstTime { if node.recharging && node.finishRecharge < firstTime {
firstTime = node.finishRecharge firstTime = node.finishRecharge
} }
} }
if self.updateNodes(firstTime) { if self.updateNodes(firstTime) {
for node, _ := range self.nodes { for node := range self.nodes {
if node.recharging { if node.recharging {
node.set(node.serving, self.simReqCnt, self.sumWeight) node.set(node.serving, self.simReqCnt, self.sumWeight)
} }

@ -49,7 +49,7 @@ func testGetBlockHeaders(t *testing.T, protocol int) {
// Create a "random" unknown hash for testing // Create a "random" unknown hash for testing
var unknown common.Hash var unknown common.Hash
for i, _ := range unknown { for i := range unknown {
unknown[i] = byte(i) unknown[i] = byte(i)
} }
// Create a batch of tests for various scenarios // Create a batch of tests for various scenarios
@ -189,17 +189,17 @@ func testGetBlockBodies(t *testing.T, protocol int) {
//{limit + 1, nil, nil, limit}, // No more than the possible block count should be returned //{limit + 1, nil, nil, limit}, // No more than the possible block count should be returned
{0, []common.Hash{bc.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable {0, []common.Hash{bc.Genesis().Hash()}, []bool{true}, 1}, // The genesis block should be retrievable
{0, []common.Hash{bc.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable {0, []common.Hash{bc.CurrentBlock().Hash()}, []bool{true}, 1}, // The chains head block should be retrievable
{0, []common.Hash{common.Hash{}}, []bool{false}, 0}, // A non existent block should not be returned {0, []common.Hash{{}}, []bool{false}, 0}, // A non existent block should not be returned
// Existing and non-existing blocks interleaved should not cause problems // Existing and non-existing blocks interleaved should not cause problems
{0, []common.Hash{ {0, []common.Hash{
common.Hash{}, {},
bc.GetBlockByNumber(1).Hash(), bc.GetBlockByNumber(1).Hash(),
common.Hash{}, {},
bc.GetBlockByNumber(10).Hash(), bc.GetBlockByNumber(10).Hash(),
common.Hash{}, {},
bc.GetBlockByNumber(100).Hash(), bc.GetBlockByNumber(100).Hash(),
common.Hash{}, {},
}, []bool{false, true, false, true, false, true, false}, 3}, }, []bool{false, true, false, true, false, true, false}, 3},
} }
// Run each of the tests and verify the results against the chain // Run each of the tests and verify the results against the chain
@ -312,7 +312,7 @@ func testGetProofs(t *testing.T, protocol int) {
var proofreqs []ProofReq var proofreqs []ProofReq
var proofs [][]rlp.RawValue var proofs [][]rlp.RawValue
accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr, common.Address{}} accounts := []common.Address{testBankAddress, acc1Addr, acc2Addr, {}}
for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ { for i := uint64(0); i <= bc.CurrentBlock().NumberU64(); i++ {
header := bc.GetHeaderByNumber(i) header := bc.GetHeaderByNumber(i)
root := header.Root root := header.Root

@ -467,7 +467,7 @@ func (ps *peerSet) AllPeerIDs() []string {
res := make([]string, len(ps.peers)) res := make([]string, len(ps.peers))
idx := 0 idx := 0
for id, _ := range ps.peers { for id := range ps.peers {
res[idx] = id res[idx] = id
idx++ idx++
} }

@ -39,7 +39,7 @@ func TestWeightedRandomSelect(t *testing.T) {
s := newWeightedRandomSelect() s := newWeightedRandomSelect()
w := -1 w := -1
list := make([]testWrsItem, cnt) list := make([]testWrsItem, cnt)
for i, _ := range list { for i := range list {
list[i] = testWrsItem{idx: i, widx: &w} list[i] = testWrsItem{idx: i, widx: &w}
s.update(&list[i]) s.update(&list[i])
} }

@ -414,7 +414,7 @@ func (pool *serverPool) loadNodes() {
// ordered from least to most recently connected. // ordered from least to most recently connected.
func (pool *serverPool) saveNodes() { func (pool *serverPool) saveNodes() {
list := make([]*poolEntry, len(pool.knownQueue.queue)) list := make([]*poolEntry, len(pool.knownQueue.queue))
for i, _ := range list { for i := range list {
list[i] = pool.knownQueue.fetchOldest() list[i] = pool.knownQueue.fetchOldest()
} }
enc, err := rlp.EncodeToBytes(list) enc, err := rlp.EncodeToBytes(list)

@ -138,7 +138,7 @@ func (self *LesTxRelay) NewHead(head common.Hash, mined []common.Hash, rollback
if len(self.txPending) > 0 { if len(self.txPending) > 0 {
txs := make(types.Transactions, len(self.txPending)) txs := make(types.Transactions, len(self.txPending))
i := 0 i := 0
for hash, _ := range self.txPending { for hash := range self.txPending {
txs[i] = self.txSent[hash].tx txs[i] = self.txSent[hash].tx
i++ i++
} }

@ -135,7 +135,7 @@ func NewLightChain(odr OdrBackend, config *params.ChainConfig, pow pow.PoW, mux
return nil, err return nil, err
} }
// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain // Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
for hash, _ := range core.BadHashes { for hash := range core.BadHashes {
if header := bc.GetHeaderByHash(hash); header != nil { if header := bc.GetHeaderByHash(hash); header != nil {
glog.V(logger.Error).Infof("Found bad hash, rewinding chain to block #%d [%x…]", header.Number, header.ParentHash[:4]) glog.V(logger.Error).Infof("Found bad hash, rewinding chain to block #%d [%x…]", header.Number, header.ParentHash[:4])
bc.SetHead(header.Number.Uint64() - 1) bc.SetHead(header.Number.Uint64() - 1)

@ -73,7 +73,7 @@ func txPoolTestChainGen(i int, block *core.BlockGen) {
} }
func TestTxPool(t *testing.T) { func TestTxPool(t *testing.T) {
for i, _ := range testTx { for i := range testTx {
testTx[i], _ = types.SignTx(types.NewTransaction(uint64(i), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey) testTx[i], _ = types.SignTx(types.NewTransaction(uint64(i), acc1Addr, big.NewInt(10000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey)
} }

@ -1,37 +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 <http://www.gnu.org/licenses/>.
package logger
import "os"
func ExampleLogger() {
logger := NewLogger("TAG")
logger.Infoln("so awesome") // prints [TAG] so awesome
logger.Infof("this %q is raw", "coin") // prints [TAG] this "coin" is raw
}
func ExampleLogSystem() {
filename := "test.log"
file, _ := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModePerm)
fileLog := NewStdLogSystem(file, 0, WarnLevel)
AddLogSystem(fileLog)
stdoutLog := NewStdLogSystem(os.Stdout, 0, WarnLevel)
AddLogSystem(stdoutLog)
NewLogger("TAG").Warnln("reactor meltdown") // writes to both logs
}

@ -928,7 +928,7 @@ const flushInterval = 30 * time.Second
// flushDaemon periodically flushes the log file buffers. // flushDaemon periodically flushes the log file buffers.
func (l *loggingT) flushDaemon() { func (l *loggingT) flushDaemon() {
for _ = range time.NewTicker(flushInterval).C { for range time.NewTicker(flushInterval).C {
l.lockAndFlushAll() l.lockAndFlushAll()
} }
} }

@ -1,65 +0,0 @@
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package logger
import (
"fmt"
"io"
"log"
"os"
"github.com/ethereum/go-ethereum/common"
)
func openLogFile(datadir string, filename string) *os.File {
path := common.AbsolutePath(datadir, filename)
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
}
return file
}
func New(datadir string, logFile string, logLevel int) LogSystem {
var writer io.Writer
if logFile == "" {
writer = os.Stdout
} else {
writer = openLogFile(datadir, logFile)
}
var sys LogSystem
sys = NewStdLogSystem(writer, log.LstdFlags, LogLevel(logLevel))
AddLogSystem(sys)
return sys
}
func NewJSONsystem(datadir string, logFile string) LogSystem {
var writer io.Writer
if logFile == "-" {
writer = os.Stdout
} else {
writer = openLogFile(datadir, logFile)
}
var sys LogSystem
sys = NewJsonLogSystem(writer)
AddLogSystem(sys)
return sys
}

@ -1,149 +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 <http://www.gnu.org/licenses/>.
/*
Package logger implements a multi-output leveled logger.
Other packages use tagged logger to send log messages to shared
(process-wide) logging engine. The shared logging engine dispatches to
multiple log systems. The log level can be set separately per log
system.
Logging is asynchronous and does not block the caller. Message
formatting is performed by the caller goroutine to avoid incorrect
logging of mutable state.
*/
package logger
import (
"encoding/json"
"fmt"
"os"
)
type LogLevel uint32
const (
// Standard log levels
Silence LogLevel = iota
ErrorLevel
WarnLevel
InfoLevel
DebugLevel
DebugDetailLevel
)
// A Logger prints messages prefixed by a given tag. It provides named
// Printf and Println style methods for all loglevels. Each ethereum
// component should have its own logger with a unique prefix.
type Logger struct {
tag string
}
func NewLogger(tag string) *Logger {
return &Logger{"[" + tag + "] "}
}
func (logger *Logger) Sendln(level LogLevel, v ...interface{}) {
logMessageC <- stdMsg{level, logger.tag + fmt.Sprintln(v...)}
}
func (logger *Logger) Sendf(level LogLevel, format string, v ...interface{}) {
logMessageC <- stdMsg{level, logger.tag + fmt.Sprintf(format, v...)}
}
// Errorln writes a message with ErrorLevel.
func (logger *Logger) Errorln(v ...interface{}) {
logger.Sendln(ErrorLevel, v...)
}
// Warnln writes a message with WarnLevel.
func (logger *Logger) Warnln(v ...interface{}) {
logger.Sendln(WarnLevel, v...)
}
// Infoln writes a message with InfoLevel.
func (logger *Logger) Infoln(v ...interface{}) {
logger.Sendln(InfoLevel, v...)
}
// Debugln writes a message with DebugLevel.
func (logger *Logger) Debugln(v ...interface{}) {
logger.Sendln(DebugLevel, v...)
}
// DebugDetailln writes a message with DebugDetailLevel.
func (logger *Logger) DebugDetailln(v ...interface{}) {
logger.Sendln(DebugDetailLevel, v...)
}
// Errorf writes a message with ErrorLevel.
func (logger *Logger) Errorf(format string, v ...interface{}) {
logger.Sendf(ErrorLevel, format, v...)
}
// Warnf writes a message with WarnLevel.
func (logger *Logger) Warnf(format string, v ...interface{}) {
logger.Sendf(WarnLevel, format, v...)
}
// Infof writes a message with InfoLevel.
func (logger *Logger) Infof(format string, v ...interface{}) {
logger.Sendf(InfoLevel, format, v...)
}
// Debugf writes a message with DebugLevel.
func (logger *Logger) Debugf(format string, v ...interface{}) {
logger.Sendf(DebugLevel, format, v...)
}
// DebugDetailf writes a message with DebugDetailLevel.
func (logger *Logger) DebugDetailf(format string, v ...interface{}) {
logger.Sendf(DebugDetailLevel, format, v...)
}
// Fatalln writes a message with ErrorLevel and exits the program.
func (logger *Logger) Fatalln(v ...interface{}) {
logger.Sendln(ErrorLevel, v...)
Flush()
os.Exit(0)
}
// Fatalf writes a message with ErrorLevel and exits the program.
func (logger *Logger) Fatalf(format string, v ...interface{}) {
logger.Sendf(ErrorLevel, format, v...)
Flush()
os.Exit(0)
}
type JsonLogger struct {
Coinbase string
}
func NewJsonLogger() *JsonLogger {
return &JsonLogger{}
}
func (logger *JsonLogger) LogJson(v JsonLog) {
msgname := v.EventName()
obj := map[string]interface{}{
msgname: v,
}
jsontxt, _ := json.Marshal(obj)
logMessageC <- (jsonMsg(jsontxt))
}

@ -1,192 +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 <http://www.gnu.org/licenses/>.
package logger
import (
"io/ioutil"
"math/rand"
"os"
"sync"
"testing"
"time"
)
type TestLogSystem struct {
mutex sync.Mutex
output string
level LogLevel
}
func (ls *TestLogSystem) LogPrint(msg LogMsg) {
ls.mutex.Lock()
if ls.level >= msg.Level() {
ls.output += msg.String()
}
ls.mutex.Unlock()
}
func (ls *TestLogSystem) SetLogLevel(i LogLevel) {
ls.mutex.Lock()
ls.level = i
ls.mutex.Unlock()
}
func (ls *TestLogSystem) GetLogLevel() LogLevel {
ls.mutex.Lock()
defer ls.mutex.Unlock()
return ls.level
}
func (ls *TestLogSystem) CheckOutput(t *testing.T, expected string) {
ls.mutex.Lock()
output := ls.output
ls.mutex.Unlock()
if output != expected {
t.Errorf("log output mismatch:\n got: %q\n want: %q\n", output, expected)
}
}
type blockedLogSystem struct {
LogSystem
unblock chan struct{}
}
func (ls blockedLogSystem) LogPrint(msg LogMsg) {
<-ls.unblock
ls.LogSystem.LogPrint(msg)
}
func TestLoggerFlush(t *testing.T) {
Reset()
logger := NewLogger("TEST")
ls := blockedLogSystem{&TestLogSystem{level: WarnLevel}, make(chan struct{})}
AddLogSystem(ls)
for i := 0; i < 5; i++ {
// these writes shouldn't hang even though ls is blocked
logger.Errorf(".")
}
beforeFlush := time.Now()
time.AfterFunc(80*time.Millisecond, func() { close(ls.unblock) })
Flush() // this should hang for approx. 80ms
if blockd := time.Now().Sub(beforeFlush); blockd < 80*time.Millisecond {
t.Errorf("Flush didn't block long enough, blocked for %v, should've been >= 80ms", blockd)
}
ls.LogSystem.(*TestLogSystem).CheckOutput(t, "[TEST] .[TEST] .[TEST] .[TEST] .[TEST] .")
}
func TestLoggerPrintln(t *testing.T) {
Reset()
logger := NewLogger("TEST")
testLogSystem := &TestLogSystem{level: WarnLevel}
AddLogSystem(testLogSystem)
logger.Errorln("error")
logger.Warnln("warn")
logger.Infoln("info")
logger.Debugln("debug")
Flush()
testLogSystem.CheckOutput(t, "[TEST] error\n[TEST] warn\n")
}
func TestLoggerPrintf(t *testing.T) {
Reset()
logger := NewLogger("TEST")
testLogSystem := &TestLogSystem{level: WarnLevel}
AddLogSystem(testLogSystem)
logger.Errorf("error to %v\n", []int{1, 2, 3})
logger.Warnf("warn %%d %d", 5)
logger.Infof("info")
logger.Debugf("debug")
Flush()
testLogSystem.CheckOutput(t, "[TEST] error to [1 2 3]\n[TEST] warn %d 5")
}
func TestMultipleLogSystems(t *testing.T) {
Reset()
logger := NewLogger("TEST")
testLogSystem0 := &TestLogSystem{level: ErrorLevel}
testLogSystem1 := &TestLogSystem{level: WarnLevel}
AddLogSystem(testLogSystem0)
AddLogSystem(testLogSystem1)
logger.Errorln("error")
logger.Warnln("warn")
Flush()
testLogSystem0.CheckOutput(t, "[TEST] error\n")
testLogSystem1.CheckOutput(t, "[TEST] error\n[TEST] warn\n")
}
func TestFileLogSystem(t *testing.T) {
Reset()
logger := NewLogger("TEST")
filename := "test.log"
file, _ := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, os.ModePerm)
testLogSystem := NewStdLogSystem(file, 0, WarnLevel)
AddLogSystem(testLogSystem)
logger.Errorf("error to %s\n", filename)
logger.Warnln("warn")
Flush()
contents, _ := ioutil.ReadFile(filename)
output := string(contents)
if output != "[TEST] error to test.log\n[TEST] warn\n" {
t.Error("Expected contents of file 'test.log': '[TEST] error to test.log\\n[TEST] warn\\n', got ", output)
} else {
os.Remove(filename)
}
}
func TestNoLogSystem(t *testing.T) {
Reset()
logger := NewLogger("TEST")
logger.Warnln("warn")
Flush()
}
func TestConcurrentAddSystem(t *testing.T) {
rand.Seed(time.Now().Unix())
Reset()
logger := NewLogger("TEST")
stop := make(chan struct{})
writer := func() {
select {
case <-stop:
return
default:
logger.Infoln("foo")
Flush()
}
}
go writer()
go writer()
stopTime := time.Now().Add(100 * time.Millisecond)
for time.Now().Before(stopTime) {
time.Sleep(time.Duration(rand.Intn(20)) * time.Millisecond)
AddLogSystem(NewStdLogSystem(ioutil.Discard, 0, InfoLevel))
}
close(stop)
}

@ -1,76 +0,0 @@
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package logger
import (
"io"
"log"
"sync/atomic"
)
// LogSystem is implemented by log output devices.
// All methods can be called concurrently from multiple goroutines.
type LogSystem interface {
LogPrint(LogMsg)
}
// NewStdLogSystem creates a LogSystem that prints to the given writer.
// The flag values are defined package log.
func NewStdLogSystem(writer io.Writer, flags int, level LogLevel) *StdLogSystem {
logger := log.New(writer, "", flags)
return &StdLogSystem{logger, uint32(level)}
}
type StdLogSystem struct {
logger *log.Logger
level uint32
}
func (t *StdLogSystem) LogPrint(msg LogMsg) {
stdmsg, ok := msg.(stdMsg)
if ok {
if t.GetLogLevel() >= stdmsg.Level() {
t.logger.Print(stdmsg.String())
}
}
}
func (t *StdLogSystem) SetLogLevel(i LogLevel) {
atomic.StoreUint32(&t.level, uint32(i))
}
func (t *StdLogSystem) GetLogLevel() LogLevel {
return LogLevel(atomic.LoadUint32(&t.level))
}
// NewJSONLogSystem creates a LogSystem that prints to the given writer without
// adding extra information irrespective of loglevel only if message is JSON type
func NewJsonLogSystem(writer io.Writer) LogSystem {
logger := log.New(writer, "", 0)
return &jsonLogSystem{logger}
}
type jsonLogSystem struct {
logger *log.Logger
}
func (t *jsonLogSystem) LogPrint(msg LogMsg) {
jsonmsg, ok := msg.(jsonMsg)
if ok {
t.logger.Print(jsonmsg.String())
}
}

@ -1,142 +0,0 @@
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package logger
import (
"fmt"
"sync"
)
type stdMsg struct {
level LogLevel
msg string
}
type jsonMsg []byte
func (m jsonMsg) Level() LogLevel {
return 0
}
func (m jsonMsg) String() string {
return string(m)
}
type LogMsg interface {
Level() LogLevel
fmt.Stringer
}
func (m stdMsg) Level() LogLevel {
return m.level
}
func (m stdMsg) String() string {
return m.msg
}
var (
logMessageC = make(chan LogMsg)
addSystemC = make(chan LogSystem)
flushC = make(chan chan struct{})
resetC = make(chan chan struct{})
)
func init() {
go dispatchLoop()
}
// each system can buffer this many messages before
// blocking incoming log messages.
const sysBufferSize = 500
func dispatchLoop() {
var (
systems []LogSystem
systemIn []chan LogMsg
systemWG sync.WaitGroup
)
bootSystem := func(sys LogSystem) {
in := make(chan LogMsg, sysBufferSize)
systemIn = append(systemIn, in)
systemWG.Add(1)
go sysLoop(sys, in, &systemWG)
}
for {
select {
case msg := <-logMessageC:
for _, c := range systemIn {
c <- msg
}
case sys := <-addSystemC:
systems = append(systems, sys)
bootSystem(sys)
case waiter := <-resetC:
// reset means terminate all systems
for _, c := range systemIn {
close(c)
}
systems = nil
systemIn = nil
systemWG.Wait()
close(waiter)
case waiter := <-flushC:
// flush means reboot all systems
for _, c := range systemIn {
close(c)
}
systemIn = nil
systemWG.Wait()
for _, sys := range systems {
bootSystem(sys)
}
close(waiter)
}
}
}
func sysLoop(sys LogSystem, in <-chan LogMsg, wg *sync.WaitGroup) {
for msg := range in {
sys.LogPrint(msg)
}
wg.Done()
}
// Reset removes all active log systems.
// It blocks until all current messages have been delivered.
func Reset() {
waiter := make(chan struct{})
resetC <- waiter
<-waiter
}
// Flush waits until all current log messages have been dispatched to
// the active log systems.
func Flush() {
waiter := make(chan struct{})
flushC <- waiter
<-waiter
}
// AddLogSystem starts printing messages to the given LogSystem.
func AddLogSystem(sys LogSystem) {
addSystemC <- sys
}

@ -1,381 +0,0 @@
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package logger
import (
"math/big"
"time"
)
type utctime8601 struct{}
func (utctime8601) MarshalJSON() ([]byte, error) {
timestr := time.Now().UTC().Format(time.RFC3339Nano)
// Bounds check
if len(timestr) > 26 {
timestr = timestr[:26]
}
return []byte(`"` + timestr + `Z"`), nil
}
type JsonLog interface {
EventName() string
}
type LogEvent struct {
// Guid string `json:"guid"`
Ts utctime8601 `json:"ts"`
// Level string `json:"level"`
}
type LogStarting struct {
ClientString string `json:"client_impl"`
ProtocolVersion int `json:"eth_version"`
LogEvent
}
func (l *LogStarting) EventName() string {
return "starting"
}
type P2PConnected struct {
RemoteId string `json:"remote_id"`
RemoteAddress string `json:"remote_addr"`
RemoteVersionString string `json:"remote_version_string"`
NumConnections int `json:"num_connections"`
LogEvent
}
func (l *P2PConnected) EventName() string {
return "p2p.connected"
}
type P2PDisconnected struct {
NumConnections int `json:"num_connections"`
RemoteId string `json:"remote_id"`
LogEvent
}
func (l *P2PDisconnected) EventName() string {
return "p2p.disconnected"
}
type EthMinerNewBlock struct {
BlockHash string `json:"block_hash"`
BlockNumber *big.Int `json:"block_number"`
ChainHeadHash string `json:"chain_head_hash"`
BlockPrevHash string `json:"block_prev_hash"`
LogEvent
}
func (l *EthMinerNewBlock) EventName() string {
return "eth.miner.new_block"
}
type EthChainReceivedNewBlock struct {
BlockHash string `json:"block_hash"`
BlockNumber *big.Int `json:"block_number"`
ChainHeadHash string `json:"chain_head_hash"`
BlockPrevHash string `json:"block_prev_hash"`
RemoteId string `json:"remote_id"`
LogEvent
}
func (l *EthChainReceivedNewBlock) EventName() string {
return "eth.chain.received.new_block"
}
type EthChainNewHead struct {
BlockHash string `json:"block_hash"`
BlockNumber *big.Int `json:"block_number"`
ChainHeadHash string `json:"chain_head_hash"`
BlockPrevHash string `json:"block_prev_hash"`
LogEvent
}
func (l *EthChainNewHead) EventName() string {
return "eth.chain.new_head"
}
type EthTxReceived struct {
TxHash string `json:"tx_hash"`
RemoteId string `json:"remote_id"`
LogEvent
}
func (l *EthTxReceived) EventName() string {
return "eth.tx.received"
}
//
//
// The types below are legacy and need to be converted to new format or deleted
//
//
// type P2PConnecting struct {
// RemoteId string `json:"remote_id"`
// RemoteEndpoint string `json:"remote_endpoint"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PConnecting) EventName() string {
// return "p2p.connecting"
// }
// type P2PHandshaked struct {
// RemoteCapabilities []string `json:"remote_capabilities"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PHandshaked) EventName() string {
// return "p2p.handshaked"
// }
// type P2PDisconnecting struct {
// Reason string `json:"reason"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PDisconnecting) EventName() string {
// return "p2p.disconnecting"
// }
// type P2PDisconnectingBadHandshake struct {
// Reason string `json:"reason"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PDisconnectingBadHandshake) EventName() string {
// return "p2p.disconnecting.bad_handshake"
// }
// type P2PDisconnectingBadProtocol struct {
// Reason string `json:"reason"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PDisconnectingBadProtocol) EventName() string {
// return "p2p.disconnecting.bad_protocol"
// }
// type P2PDisconnectingReputation struct {
// Reason string `json:"reason"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PDisconnectingReputation) EventName() string {
// return "p2p.disconnecting.reputation"
// }
// type P2PDisconnectingDHT struct {
// Reason string `json:"reason"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PDisconnectingDHT) EventName() string {
// return "p2p.disconnecting.dht"
// }
// type P2PEthDisconnectingBadBlock struct {
// Reason string `json:"reason"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PEthDisconnectingBadBlock) EventName() string {
// return "p2p.eth.disconnecting.bad_block"
// }
// type P2PEthDisconnectingBadTx struct {
// Reason string `json:"reason"`
// RemoteId string `json:"remote_id"`
// NumConnections int `json:"num_connections"`
// LogEvent
// }
// func (l *P2PEthDisconnectingBadTx) EventName() string {
// return "p2p.eth.disconnecting.bad_tx"
// }
// type EthNewBlockBroadcasted struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockBroadcasted) EventName() string {
// return "eth.newblock.broadcasted"
// }
// type EthNewBlockIsKnown struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockIsKnown) EventName() string {
// return "eth.newblock.is_known"
// }
// type EthNewBlockIsNew struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockIsNew) EventName() string {
// return "eth.newblock.is_new"
// }
// type EthNewBlockMissingParent struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockMissingParent) EventName() string {
// return "eth.newblock.missing_parent"
// }
// type EthNewBlockIsInvalid struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockIsInvalid) EventName() string {
// return "eth.newblock.is_invalid"
// }
// type EthNewBlockChainIsOlder struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockChainIsOlder) EventName() string {
// return "eth.newblock.chain.is_older"
// }
// type EthNewBlockChainIsCanonical struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockChainIsCanonical) EventName() string {
// return "eth.newblock.chain.is_cannonical"
// }
// type EthNewBlockChainNotCanonical struct {
// BlockNumber int `json:"block_number"`
// HeadHash string `json:"head_hash"`
// BlockHash string `json:"block_hash"`
// BlockDifficulty int `json:"block_difficulty"`
// BlockPrevHash string `json:"block_prev_hash"`
// LogEvent
// }
// func (l *EthNewBlockChainNotCanonical) EventName() string {
// return "eth.newblock.chain.not_cannonical"
// }
// type EthTxCreated struct {
// TxHash string `json:"tx_hash"`
// TxSender string `json:"tx_sender"`
// TxAddress string `json:"tx_address"`
// TxHexRLP string `json:"tx_hexrlp"`
// TxNonce int `json:"tx_nonce"`
// LogEvent
// }
// func (l *EthTxCreated) EventName() string {
// return "eth.tx.created"
// }
// type EthTxBroadcasted struct {
// TxHash string `json:"tx_hash"`
// TxSender string `json:"tx_sender"`
// TxAddress string `json:"tx_address"`
// TxNonce int `json:"tx_nonce"`
// LogEvent
// }
// func (l *EthTxBroadcasted) EventName() string {
// return "eth.tx.broadcasted"
// }
// type EthTxValidated struct {
// TxHash string `json:"tx_hash"`
// TxSender string `json:"tx_sender"`
// TxAddress string `json:"tx_address"`
// TxNonce int `json:"tx_nonce"`
// LogEvent
// }
// func (l *EthTxValidated) EventName() string {
// return "eth.tx.validated"
// }
// type EthTxIsInvalid struct {
// TxHash string `json:"tx_hash"`
// TxSender string `json:"tx_sender"`
// TxAddress string `json:"tx_address"`
// Reason string `json:"reason"`
// TxNonce int `json:"tx_nonce"`
// LogEvent
// }
// func (l *EthTxIsInvalid) EventName() string {
// return "eth.tx.is_invalid"
// }

@ -39,8 +39,6 @@ import (
"gopkg.in/fatih/set.v0" "gopkg.in/fatih/set.v0"
) )
var jsonlogger = logger.NewJsonLogger()
const ( const (
resultQueueSize = 10 resultQueueSize = 10
miningLogAtDepth = 5 miningLogAtDepth = 5
@ -256,7 +254,7 @@ func (self *worker) update() {
self.currentMu.Lock() self.currentMu.Lock()
acc, _ := types.Sender(self.current.signer, ev.Tx) acc, _ := types.Sender(self.current.signer, ev.Tx)
txs := map[common.Address]types.Transactions{acc: types.Transactions{ev.Tx}} txs := map[common.Address]types.Transactions{acc: {ev.Tx}}
txset := types.NewTransactionsByPriceAndNonce(txs) txset := types.NewTransactionsByPriceAndNonce(txs)
self.current.commitTransactions(self.mux, txset, self.gasPrice, self.chain) self.current.commitTransactions(self.mux, txset, self.gasPrice, self.chain)
@ -449,7 +447,7 @@ func (self *worker) commitNewWork() {
// Depending whether we support or oppose the fork, override differently // Depending whether we support or oppose the fork, override differently
if self.config.DAOForkSupport { if self.config.DAOForkSupport {
header.Extra = common.CopyBytes(params.DAOForkBlockExtra) header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
} else if bytes.Compare(header.Extra, params.DAOForkBlockExtra) == 0 { } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
} }
} }

@ -114,17 +114,12 @@ type BoundContract struct {
// DeployContract deploys a contract onto the Ethereum blockchain and binds the // DeployContract deploys a contract onto the Ethereum blockchain and binds the
// deployment address with a wrapper. // deployment address with a wrapper.
func DeployContract(opts *TransactOpts, abiJSON string, bytecode []byte, client *EthereumClient, args *Interfaces) (contract *BoundContract, _ error) { func DeployContract(opts *TransactOpts, abiJSON string, bytecode []byte, client *EthereumClient, args *Interfaces) (contract *BoundContract, _ error) {
// Convert all the deployment parameters to Go types
params := make([]interface{}, len(args.objects))
for i, obj := range args.objects {
params[i] = obj
}
// Deploy the contract to the network // Deploy the contract to the network
parsed, err := abi.JSON(strings.NewReader(abiJSON)) parsed, err := abi.JSON(strings.NewReader(abiJSON))
if err != nil { if err != nil {
return nil, err return nil, err
} }
addr, tx, bound, err := bind.DeployContract(&opts.opts, parsed, bytecode, client.client, params...) addr, tx, bound, err := bind.DeployContract(&opts.opts, parsed, bytecode, client.client, args.objects...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -159,32 +154,18 @@ func (c *BoundContract) GetDeployer() *Transaction {
// Call invokes the (constant) contract method with params as input values and // Call invokes the (constant) contract method with params as input values and
// sets the output to result. // sets the output to result.
func (c *BoundContract) Call(opts *CallOpts, out *Interfaces, method string, args *Interfaces) error { func (c *BoundContract) Call(opts *CallOpts, out *Interfaces, method string, args *Interfaces) error {
// Convert all the input and output parameters to Go types
params := make([]interface{}, len(args.objects))
for i, obj := range args.objects {
params[i] = obj
}
results := make([]interface{}, len(out.objects)) results := make([]interface{}, len(out.objects))
for i, obj := range out.objects { copy(results, out.objects)
results[i] = obj if err := c.contract.Call(&opts.opts, &results, method, args.objects...); err != nil {
}
// Execute the call to the contract and wrap any results
if err := c.contract.Call(&opts.opts, &results, method, params...); err != nil {
return err return err
} }
for i, res := range results { copy(out.objects, results)
out.objects[i] = res
}
return nil return nil
} }
// Transact invokes the (paid) contract method with params as input values. // Transact invokes the (paid) contract method with params as input values.
func (c *BoundContract) Transact(opts *TransactOpts, method string, args *Interfaces) (tx *Transaction, _ error) { func (c *BoundContract) Transact(opts *TransactOpts, method string, args *Interfaces) (tx *Transaction, _ error) {
params := make([]interface{}, len(args.objects)) rawTx, err := c.contract.Transact(&opts.opts, method, args.objects)
for i, obj := range args.objects {
params[i] = obj
}
rawTx, err := c.contract.Transact(&opts.opts, method, params)
if err != nil { if err != nil {
return nil, err return nil, err
} }

@ -38,7 +38,7 @@ func (ni *NodeInfo) GetListenerPort() int { return ni.info.Ports.Listener
func (ni *NodeInfo) GetListenerAddress() string { return ni.info.ListenAddr } func (ni *NodeInfo) GetListenerAddress() string { return ni.info.ListenAddr }
func (ni *NodeInfo) GetProtocols() *Strings { func (ni *NodeInfo) GetProtocols() *Strings {
protos := []string{} protos := []string{}
for proto, _ := range ni.info.Protocols { for proto := range ni.info.Protocols {
protos = append(protos, proto) protos = append(protos, proto)
} }
return &Strings{protos} return &Strings{protos}

@ -137,7 +137,7 @@ func TestNodeKeyPersistency(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("failed to read previously persisted node key: %v", err) t.Fatalf("failed to read previously persisted node key: %v", err)
} }
if bytes.Compare(blob1, blob2) != 0 { if !bytes.Equal(blob1, blob2) {
t.Fatalf("persisted node key mismatch: have %x, want %x", blob2, blob1) t.Fatalf("persisted node key mismatch: have %x, want %x", blob2, blob1)
} }

@ -166,7 +166,7 @@ func TestServiceLifeCycle(t *testing.T) {
if err := stack.Start(); err != nil { if err := stack.Start(); err != nil {
t.Fatalf("failed to start protocol stack: %v", err) t.Fatalf("failed to start protocol stack: %v", err)
} }
for id, _ := range services { for id := range services {
if !started[id] { if !started[id] {
t.Fatalf("service %s: freshly started service not running", id) t.Fatalf("service %s: freshly started service not running", id)
} }
@ -178,7 +178,7 @@ func TestServiceLifeCycle(t *testing.T) {
if err := stack.Stop(); err != nil { if err := stack.Stop(); err != nil {
t.Fatalf("failed to stop protocol stack: %v", err) t.Fatalf("failed to stop protocol stack: %v", err)
} }
for id, _ := range services { for id := range services {
if !stopped[id] { if !stopped[id] {
t.Fatalf("service %s: freshly terminated service still running", id) t.Fatalf("service %s: freshly terminated service still running", id)
} }
@ -218,7 +218,7 @@ func TestServiceRestarts(t *testing.T) {
} }
defer stack.Stop() defer stack.Stop()
if running != true || started != 1 { if !running || started != 1 {
t.Fatalf("running/started mismatch: have %v/%d, want true/1", running, started) t.Fatalf("running/started mismatch: have %v/%d, want true/1", running, started)
} }
// Restart the stack a few times and check successful service restarts // Restart the stack a few times and check successful service restarts
@ -227,7 +227,7 @@ func TestServiceRestarts(t *testing.T) {
t.Fatalf("iter %d: failed to restart stack: %v", i, err) t.Fatalf("iter %d: failed to restart stack: %v", i, err)
} }
} }
if running != true || started != 4 { if !running || started != 4 {
t.Fatalf("running/started mismatch: have %v/%d, want true/4", running, started) t.Fatalf("running/started mismatch: have %v/%d, want true/4", running, started)
} }
} }
@ -270,7 +270,7 @@ func TestServiceConstructionAbortion(t *testing.T) {
if err := stack.Start(); err != failure { if err := stack.Start(); err != failure {
t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure) t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure)
} }
for id, _ := range services { for id := range services {
if started[id] { if started[id] {
t.Fatalf("service %s: started should not have", id) t.Fatalf("service %s: started should not have", id)
} }
@ -322,7 +322,7 @@ func TestServiceStartupAbortion(t *testing.T) {
if err := stack.Start(); err != failure { if err := stack.Start(); err != failure {
t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure) t.Fatalf("iter %d: stack startup failure mismatch: have %v, want %v", i, err, failure)
} }
for id, _ := range services { for id := range services {
if started[id] && !stopped[id] { if started[id] && !stopped[id] {
t.Fatalf("service %s: started but not stopped", id) t.Fatalf("service %s: started but not stopped", id)
} }
@ -376,7 +376,7 @@ func TestServiceTerminationGuarantee(t *testing.T) {
if err := stack.Start(); err != nil { if err := stack.Start(); err != nil {
t.Fatalf("iter %d: failed to start protocol stack: %v", i, err) t.Fatalf("iter %d: failed to start protocol stack: %v", i, err)
} }
for id, _ := range services { for id := range services {
if !started[id] { if !started[id] {
t.Fatalf("iter %d, service %s: service not running", i, id) t.Fatalf("iter %d, service %s: service not running", i, id)
} }
@ -397,7 +397,7 @@ func TestServiceTerminationGuarantee(t *testing.T) {
t.Fatalf("iter %d: failure count mismatch: have %d, want %d", i, len(err.Services), 1) t.Fatalf("iter %d: failure count mismatch: have %d, want %d", i, len(err.Services), 1)
} }
} }
for id, _ := range services { for id := range services {
if !stopped[id] { if !stopped[id] {
t.Fatalf("iter %d, service %s: service not terminated", i, id) t.Fatalf("iter %d, service %s: service not terminated", i, id)
} }

@ -258,7 +258,7 @@ func (db *nodeDB) expireNodes() error {
continue continue
} }
// Skip the node if not expired yet (and not self) // Skip the node if not expired yet (and not self)
if bytes.Compare(id[:], db.self[:]) != 0 { if !bytes.Equal(id[:], db.self[:]) {
if seen := db.lastPong(id); seen.After(threshold) { if seen := db.lastPong(id); seen.After(threshold) {
continue continue
} }

@ -242,12 +242,12 @@ func TestNodeDBSeedQuery(t *testing.T) {
if len(seeds) != len(want) { if len(seeds) != len(want) {
t.Errorf("seed count mismatch: have %v, want %v", len(seeds), len(want)) t.Errorf("seed count mismatch: have %v, want %v", len(seeds), len(want))
} }
for id, _ := range have { for id := range have {
if _, ok := want[id]; !ok { if _, ok := want[id]; !ok {
t.Errorf("extra seed: %v", id) t.Errorf("extra seed: %v", id)
} }
} }
for id, _ := range want { for id := range want {
if _, ok := have[id]; !ok { if _, ok := have[id]; !ok {
t.Errorf("missing seed: %v", id) t.Errorf("missing seed: %v", id)
} }

@ -224,11 +224,8 @@ func (n NodeID) GoString() string {
// HexID converts a hex string to a NodeID. // HexID converts a hex string to a NodeID.
// The string may be prefixed with 0x. // The string may be prefixed with 0x.
func HexID(in string) (NodeID, error) { func HexID(in string) (NodeID, error) {
if strings.HasPrefix(in, "0x") {
in = in[2:]
}
var id NodeID var id NodeID
b, err := hex.DecodeString(in) b, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
if err != nil { if err != nil {
return id, err return id, err
} else if len(b) != len(id) { } else if len(b) != len(id) {

@ -433,7 +433,7 @@ func (tab *Table) bondall(nodes []*Node) (result []*Node) {
rc <- nn rc <- nn
}(nodes[i]) }(nodes[i])
} }
for _ = range nodes { for range nodes {
if n := <-rc; n != nil { if n := <-rc; n != nil {
result = append(result, n) result = append(result, n)
} }

@ -314,19 +314,19 @@ var lookupTestnet = &preminedTestnet{
target: MustHexID("166aea4f556532c6d34e8b740e5d314af7e9ac0ca79833bd751d6b665f12dfd38ec563c363b32f02aef4a80b44fd3def94612d497b99cb5f17fd24de454927ec"), target: MustHexID("166aea4f556532c6d34e8b740e5d314af7e9ac0ca79833bd751d6b665f12dfd38ec563c363b32f02aef4a80b44fd3def94612d497b99cb5f17fd24de454927ec"),
targetSha: common.Hash{0x5c, 0x94, 0x4e, 0xe5, 0x1c, 0x5a, 0xe9, 0xf7, 0x2a, 0x95, 0xec, 0xcb, 0x8a, 0xed, 0x3, 0x74, 0xee, 0xcb, 0x51, 0x19, 0xd7, 0x20, 0xcb, 0xea, 0x68, 0x13, 0xe8, 0xe0, 0xd6, 0xad, 0x92, 0x61}, targetSha: common.Hash{0x5c, 0x94, 0x4e, 0xe5, 0x1c, 0x5a, 0xe9, 0xf7, 0x2a, 0x95, 0xec, 0xcb, 0x8a, 0xed, 0x3, 0x74, 0xee, 0xcb, 0x51, 0x19, 0xd7, 0x20, 0xcb, 0xea, 0x68, 0x13, 0xe8, 0xe0, 0xd6, 0xad, 0x92, 0x61},
dists: [257][]NodeID{ dists: [257][]NodeID{
240: []NodeID{ 240: {
MustHexID("2001ad5e3e80c71b952161bc0186731cf5ffe942d24a79230a0555802296238e57ea7a32f5b6f18564eadc1c65389448481f8c9338df0a3dbd18f708cbc2cbcb"), MustHexID("2001ad5e3e80c71b952161bc0186731cf5ffe942d24a79230a0555802296238e57ea7a32f5b6f18564eadc1c65389448481f8c9338df0a3dbd18f708cbc2cbcb"),
MustHexID("6ba3f4f57d084b6bf94cc4555b8c657e4a8ac7b7baf23c6874efc21dd1e4f56b7eb2721e07f5242d2f1d8381fc8cae535e860197c69236798ba1ad231b105794"), MustHexID("6ba3f4f57d084b6bf94cc4555b8c657e4a8ac7b7baf23c6874efc21dd1e4f56b7eb2721e07f5242d2f1d8381fc8cae535e860197c69236798ba1ad231b105794"),
}, },
244: []NodeID{ 244: {
MustHexID("696ba1f0a9d55c59246f776600542a9e6432490f0cd78f8bb55a196918df2081a9b521c3c3ba48e465a75c10768807717f8f689b0b4adce00e1c75737552a178"), MustHexID("696ba1f0a9d55c59246f776600542a9e6432490f0cd78f8bb55a196918df2081a9b521c3c3ba48e465a75c10768807717f8f689b0b4adce00e1c75737552a178"),
}, },
246: []NodeID{ 246: {
MustHexID("d6d32178bdc38416f46ffb8b3ec9e4cb2cfff8d04dd7e4311a70e403cb62b10be1b447311b60b4f9ee221a8131fc2cbd45b96dd80deba68a949d467241facfa8"), MustHexID("d6d32178bdc38416f46ffb8b3ec9e4cb2cfff8d04dd7e4311a70e403cb62b10be1b447311b60b4f9ee221a8131fc2cbd45b96dd80deba68a949d467241facfa8"),
MustHexID("3ea3d04a43a3dfb5ac11cffc2319248cf41b6279659393c2f55b8a0a5fc9d12581a9d97ef5d8ff9b5abf3321a290e8f63a4f785f450dc8a672aba3ba2ff4fdab"), MustHexID("3ea3d04a43a3dfb5ac11cffc2319248cf41b6279659393c2f55b8a0a5fc9d12581a9d97ef5d8ff9b5abf3321a290e8f63a4f785f450dc8a672aba3ba2ff4fdab"),
MustHexID("2fc897f05ae585553e5c014effd3078f84f37f9333afacffb109f00ca8e7a3373de810a3946be971cbccdfd40249f9fe7f322118ea459ac71acca85a1ef8b7f4"), MustHexID("2fc897f05ae585553e5c014effd3078f84f37f9333afacffb109f00ca8e7a3373de810a3946be971cbccdfd40249f9fe7f322118ea459ac71acca85a1ef8b7f4"),
}, },
247: []NodeID{ 247: {
MustHexID("3155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32"), MustHexID("3155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32"),
MustHexID("312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069db"), MustHexID("312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069db"),
MustHexID("38643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aac"), MustHexID("38643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aac"),
@ -338,7 +338,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("4ab0a75941b12892369b4490a1928c8ca52a9ad6d3dffbd1d8c0b907bc200fe74c022d011ec39b64808a39c0ca41f1d3254386c3e7733e7044c44259486461b6"), MustHexID("4ab0a75941b12892369b4490a1928c8ca52a9ad6d3dffbd1d8c0b907bc200fe74c022d011ec39b64808a39c0ca41f1d3254386c3e7733e7044c44259486461b6"),
MustHexID("d45150a72dc74388773e68e03133a3b5f51447fe91837d566706b3c035ee4b56f160c878c6273394daee7f56cc398985269052f22f75a8057df2fe6172765354"), MustHexID("d45150a72dc74388773e68e03133a3b5f51447fe91837d566706b3c035ee4b56f160c878c6273394daee7f56cc398985269052f22f75a8057df2fe6172765354"),
}, },
248: []NodeID{ 248: {
MustHexID("6aadfce366a189bab08ac84721567483202c86590642ea6d6a14f37ca78d82bdb6509eb7b8b2f6f63c78ae3ae1d8837c89509e41497d719b23ad53dd81574afa"), MustHexID("6aadfce366a189bab08ac84721567483202c86590642ea6d6a14f37ca78d82bdb6509eb7b8b2f6f63c78ae3ae1d8837c89509e41497d719b23ad53dd81574afa"),
MustHexID("a605ecfd6069a4cf4cf7f5840e5bc0ce10d23a3ac59e2aaa70c6afd5637359d2519b4524f56fc2ca180cdbebe54262f720ccaae8c1b28fd553c485675831624d"), MustHexID("a605ecfd6069a4cf4cf7f5840e5bc0ce10d23a3ac59e2aaa70c6afd5637359d2519b4524f56fc2ca180cdbebe54262f720ccaae8c1b28fd553c485675831624d"),
MustHexID("29701451cb9448ca33fc33680b44b840d815be90146eb521641efbffed0859c154e8892d3906eae9934bfacee72cd1d2fa9dd050fd18888eea49da155ab0efd2"), MustHexID("29701451cb9448ca33fc33680b44b840d815be90146eb521641efbffed0859c154e8892d3906eae9934bfacee72cd1d2fa9dd050fd18888eea49da155ab0efd2"),
@ -356,7 +356,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("b76ea1a6fd6506ef6e3506a4f1f60ed6287fff8114af6141b2ff13e61242331b54082b023cfea5b3083354a4fb3f9eb8be01fb4a518f579e731a5d0707291a6b"), MustHexID("b76ea1a6fd6506ef6e3506a4f1f60ed6287fff8114af6141b2ff13e61242331b54082b023cfea5b3083354a4fb3f9eb8be01fb4a518f579e731a5d0707291a6b"),
MustHexID("9b53a37950ca8890ee349b325032d7b672cab7eced178d3060137b24ef6b92a43977922d5bdfb4a3409a2d80128e02f795f9dae6d7d99973ad0e23a2afb8442f"), MustHexID("9b53a37950ca8890ee349b325032d7b672cab7eced178d3060137b24ef6b92a43977922d5bdfb4a3409a2d80128e02f795f9dae6d7d99973ad0e23a2afb8442f"),
}, },
249: []NodeID{ 249: {
MustHexID("675ae65567c3c72c50c73bc0fd4f61f202ea5f93346ca57b551de3411ccc614fad61cb9035493af47615311b9d44ee7a161972ee4d77c28fe1ec029d01434e6a"), MustHexID("675ae65567c3c72c50c73bc0fd4f61f202ea5f93346ca57b551de3411ccc614fad61cb9035493af47615311b9d44ee7a161972ee4d77c28fe1ec029d01434e6a"),
MustHexID("8eb81408389da88536ae5800392b16ef5109d7ea132c18e9a82928047ecdb502693f6e4a4cdd18b54296caf561db937185731456c456c98bfe7de0baf0eaa495"), MustHexID("8eb81408389da88536ae5800392b16ef5109d7ea132c18e9a82928047ecdb502693f6e4a4cdd18b54296caf561db937185731456c456c98bfe7de0baf0eaa495"),
MustHexID("2adba8b1612a541771cb93a726a38a4b88e97b18eced2593eb7daf82f05a5321ca94a72cc780c306ff21e551a932fc2c6d791e4681907b5ceab7f084c3fa2944"), MustHexID("2adba8b1612a541771cb93a726a38a4b88e97b18eced2593eb7daf82f05a5321ca94a72cc780c306ff21e551a932fc2c6d791e4681907b5ceab7f084c3fa2944"),
@ -374,7 +374,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("d94193f236105010972f5df1b7818b55846592a0445b9cdc4eaed811b8c4c0f7c27dc8cc9837a4774656d6b34682d6d329d42b6ebb55da1d475c2474dc3dfdf4"), MustHexID("d94193f236105010972f5df1b7818b55846592a0445b9cdc4eaed811b8c4c0f7c27dc8cc9837a4774656d6b34682d6d329d42b6ebb55da1d475c2474dc3dfdf4"),
MustHexID("edd9af6aded4094e9785637c28fccbd3980cbe28e2eb9a411048a23c2ace4bd6b0b7088a7817997b49a3dd05fc6929ca6c7abbb69438dbdabe65e971d2a794b2"), MustHexID("edd9af6aded4094e9785637c28fccbd3980cbe28e2eb9a411048a23c2ace4bd6b0b7088a7817997b49a3dd05fc6929ca6c7abbb69438dbdabe65e971d2a794b2"),
}, },
250: []NodeID{ 250: {
MustHexID("53a5bd1215d4ab709ae8fdc2ced50bba320bced78bd9c5dc92947fb402250c914891786db0978c898c058493f86fc68b1c5de8a5cb36336150ac7a88655b6c39"), MustHexID("53a5bd1215d4ab709ae8fdc2ced50bba320bced78bd9c5dc92947fb402250c914891786db0978c898c058493f86fc68b1c5de8a5cb36336150ac7a88655b6c39"),
MustHexID("b7f79e3ab59f79262623c9ccefc8f01d682323aee56ffbe295437487e9d5acaf556a9c92e1f1c6a9601f2b9eb6b027ae1aeaebac71d61b9b78e88676efd3e1a3"), MustHexID("b7f79e3ab59f79262623c9ccefc8f01d682323aee56ffbe295437487e9d5acaf556a9c92e1f1c6a9601f2b9eb6b027ae1aeaebac71d61b9b78e88676efd3e1a3"),
MustHexID("d374bf7e8d7ffff69cc00bebff38ef5bc1dcb0a8d51c1a3d70e61ac6b2e2d6617109254b0ac224354dfbf79009fe4239e09020c483cc60c071e00b9238684f30"), MustHexID("d374bf7e8d7ffff69cc00bebff38ef5bc1dcb0a8d51c1a3d70e61ac6b2e2d6617109254b0ac224354dfbf79009fe4239e09020c483cc60c071e00b9238684f30"),
@ -392,7 +392,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("5b116f0751526868a909b61a30b0c5282c37df6925cc03ddea556ef0d0602a9595fd6c14d371f8ed7d45d89918a032dcd22be4342a8793d88fdbeb3ca3d75bd7"), MustHexID("5b116f0751526868a909b61a30b0c5282c37df6925cc03ddea556ef0d0602a9595fd6c14d371f8ed7d45d89918a032dcd22be4342a8793d88fdbeb3ca3d75bd7"),
MustHexID("50f3222fb6b82481c7c813b2172e1daea43e2710a443b9c2a57a12bd160dd37e20f87aa968c82ad639af6972185609d47036c0d93b4b7269b74ebd7073221c10"), MustHexID("50f3222fb6b82481c7c813b2172e1daea43e2710a443b9c2a57a12bd160dd37e20f87aa968c82ad639af6972185609d47036c0d93b4b7269b74ebd7073221c10"),
}, },
251: []NodeID{ 251: {
MustHexID("9b8f702a62d1bee67bedfeb102eca7f37fa1713e310f0d6651cc0c33ea7c5477575289ccd463e5a2574a00a676a1fdce05658ba447bb9d2827f0ba47b947e894"), MustHexID("9b8f702a62d1bee67bedfeb102eca7f37fa1713e310f0d6651cc0c33ea7c5477575289ccd463e5a2574a00a676a1fdce05658ba447bb9d2827f0ba47b947e894"),
MustHexID("b97532eb83054ed054b4abdf413bb30c00e4205545c93521554dbe77faa3cfaa5bd31ef466a107b0b34a71ec97214c0c83919720142cddac93aa7a3e928d4708"), MustHexID("b97532eb83054ed054b4abdf413bb30c00e4205545c93521554dbe77faa3cfaa5bd31ef466a107b0b34a71ec97214c0c83919720142cddac93aa7a3e928d4708"),
MustHexID("2f7a5e952bfb67f2f90b8441b5fadc9ee13b1dcde3afeeb3dd64bf937f86663cc5c55d1fa83952b5422763c7df1b7f2794b751c6be316ebc0beb4942e65ab8c1"), MustHexID("2f7a5e952bfb67f2f90b8441b5fadc9ee13b1dcde3afeeb3dd64bf937f86663cc5c55d1fa83952b5422763c7df1b7f2794b751c6be316ebc0beb4942e65ab8c1"),
@ -410,7 +410,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("fcc9a2e1ac3667026ff16192876d1813bb75abdbf39b929a92863012fe8b1d890badea7a0de36274d5c1eb1e8f975785532c50d80fd44b1a4b692f437303393f"), MustHexID("fcc9a2e1ac3667026ff16192876d1813bb75abdbf39b929a92863012fe8b1d890badea7a0de36274d5c1eb1e8f975785532c50d80fd44b1a4b692f437303393f"),
MustHexID("6d8b3efb461151dd4f6de809b62726f5b89e9b38e9ba1391967f61cde844f7528fecf821b74049207cee5a527096b31f3ad623928cd3ce51d926fa345a6b2951"), MustHexID("6d8b3efb461151dd4f6de809b62726f5b89e9b38e9ba1391967f61cde844f7528fecf821b74049207cee5a527096b31f3ad623928cd3ce51d926fa345a6b2951"),
}, },
252: []NodeID{ 252: {
MustHexID("f1ae93157cc48c2075dd5868fbf523e79e06caf4b8198f352f6e526680b78ff4227263de92612f7d63472bd09367bb92a636fff16fe46ccf41614f7a72495c2a"), MustHexID("f1ae93157cc48c2075dd5868fbf523e79e06caf4b8198f352f6e526680b78ff4227263de92612f7d63472bd09367bb92a636fff16fe46ccf41614f7a72495c2a"),
MustHexID("587f482d111b239c27c0cb89b51dd5d574db8efd8de14a2e6a1400c54d4567e77c65f89c1da52841212080b91604104768350276b6682f2f961cdaf4039581c7"), MustHexID("587f482d111b239c27c0cb89b51dd5d574db8efd8de14a2e6a1400c54d4567e77c65f89c1da52841212080b91604104768350276b6682f2f961cdaf4039581c7"),
MustHexID("e3f88274d35cefdaabdf205afe0e80e936cc982b8e3e47a84ce664c413b29016a4fb4f3a3ebae0a2f79671f8323661ed462bf4390af94c424dc8ace0c301b90f"), MustHexID("e3f88274d35cefdaabdf205afe0e80e936cc982b8e3e47a84ce664c413b29016a4fb4f3a3ebae0a2f79671f8323661ed462bf4390af94c424dc8ace0c301b90f"),
@ -428,7 +428,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("d84f06fe64debc4cd0625e36d19b99014b6218375262cc2209202bdbafd7dffcc4e34ce6398e182e02fd8faeed622c3e175545864902dfd3d1ac57647cddf4c6"), MustHexID("d84f06fe64debc4cd0625e36d19b99014b6218375262cc2209202bdbafd7dffcc4e34ce6398e182e02fd8faeed622c3e175545864902dfd3d1ac57647cddf4c6"),
MustHexID("d0ed87b294f38f1d741eb601020eeec30ac16331d05880fe27868f1e454446de367d7457b41c79e202eaf9525b029e4f1d7e17d85a55f83a557c005c68d7328a"), MustHexID("d0ed87b294f38f1d741eb601020eeec30ac16331d05880fe27868f1e454446de367d7457b41c79e202eaf9525b029e4f1d7e17d85a55f83a557c005c68d7328a"),
}, },
253: []NodeID{ 253: {
MustHexID("ad4485e386e3cc7c7310366a7c38fb810b8896c0d52e55944bfd320ca294e7912d6c53c0a0cf85e7ce226e92491d60430e86f8f15cda0161ed71893fb4a9e3a1"), MustHexID("ad4485e386e3cc7c7310366a7c38fb810b8896c0d52e55944bfd320ca294e7912d6c53c0a0cf85e7ce226e92491d60430e86f8f15cda0161ed71893fb4a9e3a1"),
MustHexID("36d0e7e5b7734f98c6183eeeb8ac5130a85e910a925311a19c4941b1290f945d4fc3996b12ef4966960b6fa0fb29b1604f83a0f81bd5fd6398d2e1a22e46af0c"), MustHexID("36d0e7e5b7734f98c6183eeeb8ac5130a85e910a925311a19c4941b1290f945d4fc3996b12ef4966960b6fa0fb29b1604f83a0f81bd5fd6398d2e1a22e46af0c"),
MustHexID("7d307d8acb4a561afa23bdf0bd945d35c90245e26345ec3a1f9f7df354222a7cdcb81339c9ed6744526c27a1a0c8d10857e98df942fa433602facac71ac68a31"), MustHexID("7d307d8acb4a561afa23bdf0bd945d35c90245e26345ec3a1f9f7df354222a7cdcb81339c9ed6744526c27a1a0c8d10857e98df942fa433602facac71ac68a31"),
@ -446,7 +446,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("7a369b2b8962cc4c65900be046482fbf7c14f98a135bbbae25152c82ad168fb2097b3d1429197cf46d3ce9fdeb64808f908a489cc6019725db040060fdfe5405"), MustHexID("7a369b2b8962cc4c65900be046482fbf7c14f98a135bbbae25152c82ad168fb2097b3d1429197cf46d3ce9fdeb64808f908a489cc6019725db040060fdfe5405"),
MustHexID("47bcae48288da5ecc7f5058dfa07cf14d89d06d6e449cb946e237aa6652ea050d9f5a24a65efdc0013ccf232bf88670979eddef249b054f63f38da9d7796dbd8"), MustHexID("47bcae48288da5ecc7f5058dfa07cf14d89d06d6e449cb946e237aa6652ea050d9f5a24a65efdc0013ccf232bf88670979eddef249b054f63f38da9d7796dbd8"),
}, },
254: []NodeID{ 254: {
MustHexID("099739d7abc8abd38ecc7a816c521a1168a4dbd359fa7212a5123ab583ffa1cf485a5fed219575d6475dbcdd541638b2d3631a6c7fce7474e7fe3cba1d4d5853"), MustHexID("099739d7abc8abd38ecc7a816c521a1168a4dbd359fa7212a5123ab583ffa1cf485a5fed219575d6475dbcdd541638b2d3631a6c7fce7474e7fe3cba1d4d5853"),
MustHexID("c2b01603b088a7182d0cf7ef29fb2b04c70acb320fccf78526bf9472e10c74ee70b3fcfa6f4b11d167bd7d3bc4d936b660f2c9bff934793d97cb21750e7c3d31"), MustHexID("c2b01603b088a7182d0cf7ef29fb2b04c70acb320fccf78526bf9472e10c74ee70b3fcfa6f4b11d167bd7d3bc4d936b660f2c9bff934793d97cb21750e7c3d31"),
MustHexID("20e4d8f45f2f863e94b45548c1ef22a11f7d36f263e4f8623761e05a64c4572379b000a52211751e2561b0f14f4fc92dd4130410c8ccc71eb4f0e95a700d4ca9"), MustHexID("20e4d8f45f2f863e94b45548c1ef22a11f7d36f263e4f8623761e05a64c4572379b000a52211751e2561b0f14f4fc92dd4130410c8ccc71eb4f0e95a700d4ca9"),
@ -464,7 +464,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("82504b6eb49bb2c0f91a7006ce9cefdbaf6df38706198502c2e06601091fc9dc91e4f15db3410d45c6af355bc270b0f268d3dff560f956985c7332d4b10bd1ed"), MustHexID("82504b6eb49bb2c0f91a7006ce9cefdbaf6df38706198502c2e06601091fc9dc91e4f15db3410d45c6af355bc270b0f268d3dff560f956985c7332d4b10bd1ed"),
MustHexID("b39b5b677b45944ceebe76e76d1f051de2f2a0ec7b0d650da52135743e66a9a5dba45f638258f9a7545d9a790c7fe6d3fdf82c25425c7887323e45d27d06c057"), MustHexID("b39b5b677b45944ceebe76e76d1f051de2f2a0ec7b0d650da52135743e66a9a5dba45f638258f9a7545d9a790c7fe6d3fdf82c25425c7887323e45d27d06c057"),
}, },
255: []NodeID{ 255: {
MustHexID("5c4d58d46e055dd1f093f81ee60a675e1f02f54da6206720adee4dccef9b67a31efc5c2a2949c31a04ee31beadc79aba10da31440a1f9ff2a24093c63c36d784"), MustHexID("5c4d58d46e055dd1f093f81ee60a675e1f02f54da6206720adee4dccef9b67a31efc5c2a2949c31a04ee31beadc79aba10da31440a1f9ff2a24093c63c36d784"),
MustHexID("ea72161ffdd4b1e124c7b93b0684805f4c4b58d617ed498b37a145c670dbc2e04976f8785583d9c805ffbf343c31d492d79f841652bbbd01b61ed85640b23495"), MustHexID("ea72161ffdd4b1e124c7b93b0684805f4c4b58d617ed498b37a145c670dbc2e04976f8785583d9c805ffbf343c31d492d79f841652bbbd01b61ed85640b23495"),
MustHexID("51caa1d93352d47a8e531692a3612adac1e8ac68d0a200d086c1c57ae1e1a91aa285ab242e8c52ef9d7afe374c9485b122ae815f1707b875569d0433c1c3ce85"), MustHexID("51caa1d93352d47a8e531692a3612adac1e8ac68d0a200d086c1c57ae1e1a91aa285ab242e8c52ef9d7afe374c9485b122ae815f1707b875569d0433c1c3ce85"),
@ -482,7 +482,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("f492c6ee2696d5f682f7f537757e52744c2ae560f1090a07024609e903d334e9e174fc01609c5a229ddbcac36c9d21adaf6457dab38a25bfd44f2f0ee4277998"), MustHexID("f492c6ee2696d5f682f7f537757e52744c2ae560f1090a07024609e903d334e9e174fc01609c5a229ddbcac36c9d21adaf6457dab38a25bfd44f2f0ee4277998"),
MustHexID("459e4db99298cb0467a90acee6888b08bb857450deac11015cced5104853be5adce5b69c740968bc7f931495d671a70cad9f48546d7cd203357fe9af0e8d2164"), MustHexID("459e4db99298cb0467a90acee6888b08bb857450deac11015cced5104853be5adce5b69c740968bc7f931495d671a70cad9f48546d7cd203357fe9af0e8d2164"),
}, },
256: []NodeID{ 256: {
MustHexID("a8593af8a4aef7b806b5197612017951bac8845a1917ca9a6a15dd6086d608505144990b245785c4cd2d67a295701c7aac2aa18823fb0033987284b019656268"), MustHexID("a8593af8a4aef7b806b5197612017951bac8845a1917ca9a6a15dd6086d608505144990b245785c4cd2d67a295701c7aac2aa18823fb0033987284b019656268"),
MustHexID("d2eebef914928c3aad77fc1b2a495f52d2294acf5edaa7d8a530b540f094b861a68fe8348a46a7c302f08ab609d85912a4968eacfea0740847b29421b4795d9e"), MustHexID("d2eebef914928c3aad77fc1b2a495f52d2294acf5edaa7d8a530b540f094b861a68fe8348a46a7c302f08ab609d85912a4968eacfea0740847b29421b4795d9e"),
MustHexID("b14bfcb31495f32b650b63cf7d08492e3e29071fdc73cf2da0da48d4b191a70ba1a65f42ad8c343206101f00f8a48e8db4b08bf3f622c0853e7323b250835b91"), MustHexID("b14bfcb31495f32b650b63cf7d08492e3e29071fdc73cf2da0da48d4b191a70ba1a65f42ad8c343206101f00f8a48e8db4b08bf3f622c0853e7323b250835b91"),

@ -269,7 +269,7 @@ func (db *nodeDB) expireNodes() error {
continue continue
} }
// Skip the node if not expired yet (and not self) // Skip the node if not expired yet (and not self)
if bytes.Compare(id[:], db.self[:]) != 0 { if !bytes.Equal(id[:], db.self[:]) {
if seen := db.lastPong(id); seen.After(threshold) { if seen := db.lastPong(id); seen.After(threshold) {
continue continue
} }

@ -242,12 +242,12 @@ func TestNodeDBSeedQuery(t *testing.T) {
if len(seeds) != len(want) { if len(seeds) != len(want) {
t.Errorf("seed count mismatch: have %v, want %v", len(seeds), len(want)) t.Errorf("seed count mismatch: have %v, want %v", len(seeds), len(want))
} }
for id, _ := range have { for id := range have {
if _, ok := want[id]; !ok { if _, ok := want[id]; !ok {
t.Errorf("extra seed: %v", id) t.Errorf("extra seed: %v", id)
} }
} }
for id, _ := range want { for id := range want {
if _, ok := have[id]; !ok { if _, ok := have[id]; !ok {
t.Errorf("missing seed: %v", id) t.Errorf("missing seed: %v", id)
} }

@ -69,19 +69,19 @@ var lookupTestnet = &preminedTestnet{
target: MustHexID("166aea4f556532c6d34e8b740e5d314af7e9ac0ca79833bd751d6b665f12dfd38ec563c363b32f02aef4a80b44fd3def94612d497b99cb5f17fd24de454927ec"), target: MustHexID("166aea4f556532c6d34e8b740e5d314af7e9ac0ca79833bd751d6b665f12dfd38ec563c363b32f02aef4a80b44fd3def94612d497b99cb5f17fd24de454927ec"),
targetSha: common.Hash{0x5c, 0x94, 0x4e, 0xe5, 0x1c, 0x5a, 0xe9, 0xf7, 0x2a, 0x95, 0xec, 0xcb, 0x8a, 0xed, 0x3, 0x74, 0xee, 0xcb, 0x51, 0x19, 0xd7, 0x20, 0xcb, 0xea, 0x68, 0x13, 0xe8, 0xe0, 0xd6, 0xad, 0x92, 0x61}, targetSha: common.Hash{0x5c, 0x94, 0x4e, 0xe5, 0x1c, 0x5a, 0xe9, 0xf7, 0x2a, 0x95, 0xec, 0xcb, 0x8a, 0xed, 0x3, 0x74, 0xee, 0xcb, 0x51, 0x19, 0xd7, 0x20, 0xcb, 0xea, 0x68, 0x13, 0xe8, 0xe0, 0xd6, 0xad, 0x92, 0x61},
dists: [257][]NodeID{ dists: [257][]NodeID{
240: []NodeID{ 240: {
MustHexID("2001ad5e3e80c71b952161bc0186731cf5ffe942d24a79230a0555802296238e57ea7a32f5b6f18564eadc1c65389448481f8c9338df0a3dbd18f708cbc2cbcb"), MustHexID("2001ad5e3e80c71b952161bc0186731cf5ffe942d24a79230a0555802296238e57ea7a32f5b6f18564eadc1c65389448481f8c9338df0a3dbd18f708cbc2cbcb"),
MustHexID("6ba3f4f57d084b6bf94cc4555b8c657e4a8ac7b7baf23c6874efc21dd1e4f56b7eb2721e07f5242d2f1d8381fc8cae535e860197c69236798ba1ad231b105794"), MustHexID("6ba3f4f57d084b6bf94cc4555b8c657e4a8ac7b7baf23c6874efc21dd1e4f56b7eb2721e07f5242d2f1d8381fc8cae535e860197c69236798ba1ad231b105794"),
}, },
244: []NodeID{ 244: {
MustHexID("696ba1f0a9d55c59246f776600542a9e6432490f0cd78f8bb55a196918df2081a9b521c3c3ba48e465a75c10768807717f8f689b0b4adce00e1c75737552a178"), MustHexID("696ba1f0a9d55c59246f776600542a9e6432490f0cd78f8bb55a196918df2081a9b521c3c3ba48e465a75c10768807717f8f689b0b4adce00e1c75737552a178"),
}, },
246: []NodeID{ 246: {
MustHexID("d6d32178bdc38416f46ffb8b3ec9e4cb2cfff8d04dd7e4311a70e403cb62b10be1b447311b60b4f9ee221a8131fc2cbd45b96dd80deba68a949d467241facfa8"), MustHexID("d6d32178bdc38416f46ffb8b3ec9e4cb2cfff8d04dd7e4311a70e403cb62b10be1b447311b60b4f9ee221a8131fc2cbd45b96dd80deba68a949d467241facfa8"),
MustHexID("3ea3d04a43a3dfb5ac11cffc2319248cf41b6279659393c2f55b8a0a5fc9d12581a9d97ef5d8ff9b5abf3321a290e8f63a4f785f450dc8a672aba3ba2ff4fdab"), MustHexID("3ea3d04a43a3dfb5ac11cffc2319248cf41b6279659393c2f55b8a0a5fc9d12581a9d97ef5d8ff9b5abf3321a290e8f63a4f785f450dc8a672aba3ba2ff4fdab"),
MustHexID("2fc897f05ae585553e5c014effd3078f84f37f9333afacffb109f00ca8e7a3373de810a3946be971cbccdfd40249f9fe7f322118ea459ac71acca85a1ef8b7f4"), MustHexID("2fc897f05ae585553e5c014effd3078f84f37f9333afacffb109f00ca8e7a3373de810a3946be971cbccdfd40249f9fe7f322118ea459ac71acca85a1ef8b7f4"),
}, },
247: []NodeID{ 247: {
MustHexID("3155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32"), MustHexID("3155e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa829115d224c523596b401065a97f74010610fce76382c0bf32"),
MustHexID("312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069db"), MustHexID("312c55512422cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e829f04c2d314fc2d4e255e0d3bc08792b069db"),
MustHexID("38643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aac"), MustHexID("38643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aac"),
@ -93,7 +93,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("4ab0a75941b12892369b4490a1928c8ca52a9ad6d3dffbd1d8c0b907bc200fe74c022d011ec39b64808a39c0ca41f1d3254386c3e7733e7044c44259486461b6"), MustHexID("4ab0a75941b12892369b4490a1928c8ca52a9ad6d3dffbd1d8c0b907bc200fe74c022d011ec39b64808a39c0ca41f1d3254386c3e7733e7044c44259486461b6"),
MustHexID("d45150a72dc74388773e68e03133a3b5f51447fe91837d566706b3c035ee4b56f160c878c6273394daee7f56cc398985269052f22f75a8057df2fe6172765354"), MustHexID("d45150a72dc74388773e68e03133a3b5f51447fe91837d566706b3c035ee4b56f160c878c6273394daee7f56cc398985269052f22f75a8057df2fe6172765354"),
}, },
248: []NodeID{ 248: {
MustHexID("6aadfce366a189bab08ac84721567483202c86590642ea6d6a14f37ca78d82bdb6509eb7b8b2f6f63c78ae3ae1d8837c89509e41497d719b23ad53dd81574afa"), MustHexID("6aadfce366a189bab08ac84721567483202c86590642ea6d6a14f37ca78d82bdb6509eb7b8b2f6f63c78ae3ae1d8837c89509e41497d719b23ad53dd81574afa"),
MustHexID("a605ecfd6069a4cf4cf7f5840e5bc0ce10d23a3ac59e2aaa70c6afd5637359d2519b4524f56fc2ca180cdbebe54262f720ccaae8c1b28fd553c485675831624d"), MustHexID("a605ecfd6069a4cf4cf7f5840e5bc0ce10d23a3ac59e2aaa70c6afd5637359d2519b4524f56fc2ca180cdbebe54262f720ccaae8c1b28fd553c485675831624d"),
MustHexID("29701451cb9448ca33fc33680b44b840d815be90146eb521641efbffed0859c154e8892d3906eae9934bfacee72cd1d2fa9dd050fd18888eea49da155ab0efd2"), MustHexID("29701451cb9448ca33fc33680b44b840d815be90146eb521641efbffed0859c154e8892d3906eae9934bfacee72cd1d2fa9dd050fd18888eea49da155ab0efd2"),
@ -111,7 +111,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("b76ea1a6fd6506ef6e3506a4f1f60ed6287fff8114af6141b2ff13e61242331b54082b023cfea5b3083354a4fb3f9eb8be01fb4a518f579e731a5d0707291a6b"), MustHexID("b76ea1a6fd6506ef6e3506a4f1f60ed6287fff8114af6141b2ff13e61242331b54082b023cfea5b3083354a4fb3f9eb8be01fb4a518f579e731a5d0707291a6b"),
MustHexID("9b53a37950ca8890ee349b325032d7b672cab7eced178d3060137b24ef6b92a43977922d5bdfb4a3409a2d80128e02f795f9dae6d7d99973ad0e23a2afb8442f"), MustHexID("9b53a37950ca8890ee349b325032d7b672cab7eced178d3060137b24ef6b92a43977922d5bdfb4a3409a2d80128e02f795f9dae6d7d99973ad0e23a2afb8442f"),
}, },
249: []NodeID{ 249: {
MustHexID("675ae65567c3c72c50c73bc0fd4f61f202ea5f93346ca57b551de3411ccc614fad61cb9035493af47615311b9d44ee7a161972ee4d77c28fe1ec029d01434e6a"), MustHexID("675ae65567c3c72c50c73bc0fd4f61f202ea5f93346ca57b551de3411ccc614fad61cb9035493af47615311b9d44ee7a161972ee4d77c28fe1ec029d01434e6a"),
MustHexID("8eb81408389da88536ae5800392b16ef5109d7ea132c18e9a82928047ecdb502693f6e4a4cdd18b54296caf561db937185731456c456c98bfe7de0baf0eaa495"), MustHexID("8eb81408389da88536ae5800392b16ef5109d7ea132c18e9a82928047ecdb502693f6e4a4cdd18b54296caf561db937185731456c456c98bfe7de0baf0eaa495"),
MustHexID("2adba8b1612a541771cb93a726a38a4b88e97b18eced2593eb7daf82f05a5321ca94a72cc780c306ff21e551a932fc2c6d791e4681907b5ceab7f084c3fa2944"), MustHexID("2adba8b1612a541771cb93a726a38a4b88e97b18eced2593eb7daf82f05a5321ca94a72cc780c306ff21e551a932fc2c6d791e4681907b5ceab7f084c3fa2944"),
@ -129,7 +129,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("d94193f236105010972f5df1b7818b55846592a0445b9cdc4eaed811b8c4c0f7c27dc8cc9837a4774656d6b34682d6d329d42b6ebb55da1d475c2474dc3dfdf4"), MustHexID("d94193f236105010972f5df1b7818b55846592a0445b9cdc4eaed811b8c4c0f7c27dc8cc9837a4774656d6b34682d6d329d42b6ebb55da1d475c2474dc3dfdf4"),
MustHexID("edd9af6aded4094e9785637c28fccbd3980cbe28e2eb9a411048a23c2ace4bd6b0b7088a7817997b49a3dd05fc6929ca6c7abbb69438dbdabe65e971d2a794b2"), MustHexID("edd9af6aded4094e9785637c28fccbd3980cbe28e2eb9a411048a23c2ace4bd6b0b7088a7817997b49a3dd05fc6929ca6c7abbb69438dbdabe65e971d2a794b2"),
}, },
250: []NodeID{ 250: {
MustHexID("53a5bd1215d4ab709ae8fdc2ced50bba320bced78bd9c5dc92947fb402250c914891786db0978c898c058493f86fc68b1c5de8a5cb36336150ac7a88655b6c39"), MustHexID("53a5bd1215d4ab709ae8fdc2ced50bba320bced78bd9c5dc92947fb402250c914891786db0978c898c058493f86fc68b1c5de8a5cb36336150ac7a88655b6c39"),
MustHexID("b7f79e3ab59f79262623c9ccefc8f01d682323aee56ffbe295437487e9d5acaf556a9c92e1f1c6a9601f2b9eb6b027ae1aeaebac71d61b9b78e88676efd3e1a3"), MustHexID("b7f79e3ab59f79262623c9ccefc8f01d682323aee56ffbe295437487e9d5acaf556a9c92e1f1c6a9601f2b9eb6b027ae1aeaebac71d61b9b78e88676efd3e1a3"),
MustHexID("d374bf7e8d7ffff69cc00bebff38ef5bc1dcb0a8d51c1a3d70e61ac6b2e2d6617109254b0ac224354dfbf79009fe4239e09020c483cc60c071e00b9238684f30"), MustHexID("d374bf7e8d7ffff69cc00bebff38ef5bc1dcb0a8d51c1a3d70e61ac6b2e2d6617109254b0ac224354dfbf79009fe4239e09020c483cc60c071e00b9238684f30"),
@ -147,7 +147,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("5b116f0751526868a909b61a30b0c5282c37df6925cc03ddea556ef0d0602a9595fd6c14d371f8ed7d45d89918a032dcd22be4342a8793d88fdbeb3ca3d75bd7"), MustHexID("5b116f0751526868a909b61a30b0c5282c37df6925cc03ddea556ef0d0602a9595fd6c14d371f8ed7d45d89918a032dcd22be4342a8793d88fdbeb3ca3d75bd7"),
MustHexID("50f3222fb6b82481c7c813b2172e1daea43e2710a443b9c2a57a12bd160dd37e20f87aa968c82ad639af6972185609d47036c0d93b4b7269b74ebd7073221c10"), MustHexID("50f3222fb6b82481c7c813b2172e1daea43e2710a443b9c2a57a12bd160dd37e20f87aa968c82ad639af6972185609d47036c0d93b4b7269b74ebd7073221c10"),
}, },
251: []NodeID{ 251: {
MustHexID("9b8f702a62d1bee67bedfeb102eca7f37fa1713e310f0d6651cc0c33ea7c5477575289ccd463e5a2574a00a676a1fdce05658ba447bb9d2827f0ba47b947e894"), MustHexID("9b8f702a62d1bee67bedfeb102eca7f37fa1713e310f0d6651cc0c33ea7c5477575289ccd463e5a2574a00a676a1fdce05658ba447bb9d2827f0ba47b947e894"),
MustHexID("b97532eb83054ed054b4abdf413bb30c00e4205545c93521554dbe77faa3cfaa5bd31ef466a107b0b34a71ec97214c0c83919720142cddac93aa7a3e928d4708"), MustHexID("b97532eb83054ed054b4abdf413bb30c00e4205545c93521554dbe77faa3cfaa5bd31ef466a107b0b34a71ec97214c0c83919720142cddac93aa7a3e928d4708"),
MustHexID("2f7a5e952bfb67f2f90b8441b5fadc9ee13b1dcde3afeeb3dd64bf937f86663cc5c55d1fa83952b5422763c7df1b7f2794b751c6be316ebc0beb4942e65ab8c1"), MustHexID("2f7a5e952bfb67f2f90b8441b5fadc9ee13b1dcde3afeeb3dd64bf937f86663cc5c55d1fa83952b5422763c7df1b7f2794b751c6be316ebc0beb4942e65ab8c1"),
@ -165,7 +165,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("fcc9a2e1ac3667026ff16192876d1813bb75abdbf39b929a92863012fe8b1d890badea7a0de36274d5c1eb1e8f975785532c50d80fd44b1a4b692f437303393f"), MustHexID("fcc9a2e1ac3667026ff16192876d1813bb75abdbf39b929a92863012fe8b1d890badea7a0de36274d5c1eb1e8f975785532c50d80fd44b1a4b692f437303393f"),
MustHexID("6d8b3efb461151dd4f6de809b62726f5b89e9b38e9ba1391967f61cde844f7528fecf821b74049207cee5a527096b31f3ad623928cd3ce51d926fa345a6b2951"), MustHexID("6d8b3efb461151dd4f6de809b62726f5b89e9b38e9ba1391967f61cde844f7528fecf821b74049207cee5a527096b31f3ad623928cd3ce51d926fa345a6b2951"),
}, },
252: []NodeID{ 252: {
MustHexID("f1ae93157cc48c2075dd5868fbf523e79e06caf4b8198f352f6e526680b78ff4227263de92612f7d63472bd09367bb92a636fff16fe46ccf41614f7a72495c2a"), MustHexID("f1ae93157cc48c2075dd5868fbf523e79e06caf4b8198f352f6e526680b78ff4227263de92612f7d63472bd09367bb92a636fff16fe46ccf41614f7a72495c2a"),
MustHexID("587f482d111b239c27c0cb89b51dd5d574db8efd8de14a2e6a1400c54d4567e77c65f89c1da52841212080b91604104768350276b6682f2f961cdaf4039581c7"), MustHexID("587f482d111b239c27c0cb89b51dd5d574db8efd8de14a2e6a1400c54d4567e77c65f89c1da52841212080b91604104768350276b6682f2f961cdaf4039581c7"),
MustHexID("e3f88274d35cefdaabdf205afe0e80e936cc982b8e3e47a84ce664c413b29016a4fb4f3a3ebae0a2f79671f8323661ed462bf4390af94c424dc8ace0c301b90f"), MustHexID("e3f88274d35cefdaabdf205afe0e80e936cc982b8e3e47a84ce664c413b29016a4fb4f3a3ebae0a2f79671f8323661ed462bf4390af94c424dc8ace0c301b90f"),
@ -183,7 +183,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("d84f06fe64debc4cd0625e36d19b99014b6218375262cc2209202bdbafd7dffcc4e34ce6398e182e02fd8faeed622c3e175545864902dfd3d1ac57647cddf4c6"), MustHexID("d84f06fe64debc4cd0625e36d19b99014b6218375262cc2209202bdbafd7dffcc4e34ce6398e182e02fd8faeed622c3e175545864902dfd3d1ac57647cddf4c6"),
MustHexID("d0ed87b294f38f1d741eb601020eeec30ac16331d05880fe27868f1e454446de367d7457b41c79e202eaf9525b029e4f1d7e17d85a55f83a557c005c68d7328a"), MustHexID("d0ed87b294f38f1d741eb601020eeec30ac16331d05880fe27868f1e454446de367d7457b41c79e202eaf9525b029e4f1d7e17d85a55f83a557c005c68d7328a"),
}, },
253: []NodeID{ 253: {
MustHexID("ad4485e386e3cc7c7310366a7c38fb810b8896c0d52e55944bfd320ca294e7912d6c53c0a0cf85e7ce226e92491d60430e86f8f15cda0161ed71893fb4a9e3a1"), MustHexID("ad4485e386e3cc7c7310366a7c38fb810b8896c0d52e55944bfd320ca294e7912d6c53c0a0cf85e7ce226e92491d60430e86f8f15cda0161ed71893fb4a9e3a1"),
MustHexID("36d0e7e5b7734f98c6183eeeb8ac5130a85e910a925311a19c4941b1290f945d4fc3996b12ef4966960b6fa0fb29b1604f83a0f81bd5fd6398d2e1a22e46af0c"), MustHexID("36d0e7e5b7734f98c6183eeeb8ac5130a85e910a925311a19c4941b1290f945d4fc3996b12ef4966960b6fa0fb29b1604f83a0f81bd5fd6398d2e1a22e46af0c"),
MustHexID("7d307d8acb4a561afa23bdf0bd945d35c90245e26345ec3a1f9f7df354222a7cdcb81339c9ed6744526c27a1a0c8d10857e98df942fa433602facac71ac68a31"), MustHexID("7d307d8acb4a561afa23bdf0bd945d35c90245e26345ec3a1f9f7df354222a7cdcb81339c9ed6744526c27a1a0c8d10857e98df942fa433602facac71ac68a31"),
@ -201,7 +201,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("7a369b2b8962cc4c65900be046482fbf7c14f98a135bbbae25152c82ad168fb2097b3d1429197cf46d3ce9fdeb64808f908a489cc6019725db040060fdfe5405"), MustHexID("7a369b2b8962cc4c65900be046482fbf7c14f98a135bbbae25152c82ad168fb2097b3d1429197cf46d3ce9fdeb64808f908a489cc6019725db040060fdfe5405"),
MustHexID("47bcae48288da5ecc7f5058dfa07cf14d89d06d6e449cb946e237aa6652ea050d9f5a24a65efdc0013ccf232bf88670979eddef249b054f63f38da9d7796dbd8"), MustHexID("47bcae48288da5ecc7f5058dfa07cf14d89d06d6e449cb946e237aa6652ea050d9f5a24a65efdc0013ccf232bf88670979eddef249b054f63f38da9d7796dbd8"),
}, },
254: []NodeID{ 254: {
MustHexID("099739d7abc8abd38ecc7a816c521a1168a4dbd359fa7212a5123ab583ffa1cf485a5fed219575d6475dbcdd541638b2d3631a6c7fce7474e7fe3cba1d4d5853"), MustHexID("099739d7abc8abd38ecc7a816c521a1168a4dbd359fa7212a5123ab583ffa1cf485a5fed219575d6475dbcdd541638b2d3631a6c7fce7474e7fe3cba1d4d5853"),
MustHexID("c2b01603b088a7182d0cf7ef29fb2b04c70acb320fccf78526bf9472e10c74ee70b3fcfa6f4b11d167bd7d3bc4d936b660f2c9bff934793d97cb21750e7c3d31"), MustHexID("c2b01603b088a7182d0cf7ef29fb2b04c70acb320fccf78526bf9472e10c74ee70b3fcfa6f4b11d167bd7d3bc4d936b660f2c9bff934793d97cb21750e7c3d31"),
MustHexID("20e4d8f45f2f863e94b45548c1ef22a11f7d36f263e4f8623761e05a64c4572379b000a52211751e2561b0f14f4fc92dd4130410c8ccc71eb4f0e95a700d4ca9"), MustHexID("20e4d8f45f2f863e94b45548c1ef22a11f7d36f263e4f8623761e05a64c4572379b000a52211751e2561b0f14f4fc92dd4130410c8ccc71eb4f0e95a700d4ca9"),
@ -219,7 +219,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("82504b6eb49bb2c0f91a7006ce9cefdbaf6df38706198502c2e06601091fc9dc91e4f15db3410d45c6af355bc270b0f268d3dff560f956985c7332d4b10bd1ed"), MustHexID("82504b6eb49bb2c0f91a7006ce9cefdbaf6df38706198502c2e06601091fc9dc91e4f15db3410d45c6af355bc270b0f268d3dff560f956985c7332d4b10bd1ed"),
MustHexID("b39b5b677b45944ceebe76e76d1f051de2f2a0ec7b0d650da52135743e66a9a5dba45f638258f9a7545d9a790c7fe6d3fdf82c25425c7887323e45d27d06c057"), MustHexID("b39b5b677b45944ceebe76e76d1f051de2f2a0ec7b0d650da52135743e66a9a5dba45f638258f9a7545d9a790c7fe6d3fdf82c25425c7887323e45d27d06c057"),
}, },
255: []NodeID{ 255: {
MustHexID("5c4d58d46e055dd1f093f81ee60a675e1f02f54da6206720adee4dccef9b67a31efc5c2a2949c31a04ee31beadc79aba10da31440a1f9ff2a24093c63c36d784"), MustHexID("5c4d58d46e055dd1f093f81ee60a675e1f02f54da6206720adee4dccef9b67a31efc5c2a2949c31a04ee31beadc79aba10da31440a1f9ff2a24093c63c36d784"),
MustHexID("ea72161ffdd4b1e124c7b93b0684805f4c4b58d617ed498b37a145c670dbc2e04976f8785583d9c805ffbf343c31d492d79f841652bbbd01b61ed85640b23495"), MustHexID("ea72161ffdd4b1e124c7b93b0684805f4c4b58d617ed498b37a145c670dbc2e04976f8785583d9c805ffbf343c31d492d79f841652bbbd01b61ed85640b23495"),
MustHexID("51caa1d93352d47a8e531692a3612adac1e8ac68d0a200d086c1c57ae1e1a91aa285ab242e8c52ef9d7afe374c9485b122ae815f1707b875569d0433c1c3ce85"), MustHexID("51caa1d93352d47a8e531692a3612adac1e8ac68d0a200d086c1c57ae1e1a91aa285ab242e8c52ef9d7afe374c9485b122ae815f1707b875569d0433c1c3ce85"),
@ -237,7 +237,7 @@ var lookupTestnet = &preminedTestnet{
MustHexID("f492c6ee2696d5f682f7f537757e52744c2ae560f1090a07024609e903d334e9e174fc01609c5a229ddbcac36c9d21adaf6457dab38a25bfd44f2f0ee4277998"), MustHexID("f492c6ee2696d5f682f7f537757e52744c2ae560f1090a07024609e903d334e9e174fc01609c5a229ddbcac36c9d21adaf6457dab38a25bfd44f2f0ee4277998"),
MustHexID("459e4db99298cb0467a90acee6888b08bb857450deac11015cced5104853be5adce5b69c740968bc7f931495d671a70cad9f48546d7cd203357fe9af0e8d2164"), MustHexID("459e4db99298cb0467a90acee6888b08bb857450deac11015cced5104853be5adce5b69c740968bc7f931495d671a70cad9f48546d7cd203357fe9af0e8d2164"),
}, },
256: []NodeID{ 256: {
MustHexID("a8593af8a4aef7b806b5197612017951bac8845a1917ca9a6a15dd6086d608505144990b245785c4cd2d67a295701c7aac2aa18823fb0033987284b019656268"), MustHexID("a8593af8a4aef7b806b5197612017951bac8845a1917ca9a6a15dd6086d608505144990b245785c4cd2d67a295701c7aac2aa18823fb0033987284b019656268"),
MustHexID("d2eebef914928c3aad77fc1b2a495f52d2294acf5edaa7d8a530b540f094b861a68fe8348a46a7c302f08ab609d85912a4968eacfea0740847b29421b4795d9e"), MustHexID("d2eebef914928c3aad77fc1b2a495f52d2294acf5edaa7d8a530b540f094b861a68fe8348a46a7c302f08ab609d85912a4968eacfea0740847b29421b4795d9e"),
MustHexID("b14bfcb31495f32b650b63cf7d08492e3e29071fdc73cf2da0da48d4b191a70ba1a65f42ad8c343206101f00f8a48e8db4b08bf3f622c0853e7323b250835b91"), MustHexID("b14bfcb31495f32b650b63cf7d08492e3e29071fdc73cf2da0da48d4b191a70ba1a65f42ad8c343206101f00f8a48e8db4b08bf3f622c0853e7323b250835b91"),

@ -262,11 +262,8 @@ func (n NodeID) GoString() string {
// HexID converts a hex string to a NodeID. // HexID converts a hex string to a NodeID.
// The string may be prefixed with 0x. // The string may be prefixed with 0x.
func HexID(in string) (NodeID, error) { func HexID(in string) (NodeID, error) {
if strings.HasPrefix(in, "0x") {
in = in[2:]
}
var id NodeID var id NodeID
b, err := hex.DecodeString(in) b, err := hex.DecodeString(strings.TrimPrefix(in, "0x"))
if err != nil { if err != nil {
return id, err return id, err
} else if len(b) != len(id) { } else if len(b) != len(id) {

@ -74,7 +74,7 @@ func TestSimTopics(t *testing.T) {
go func() { go func() {
nets := make([]*Network, 1024) nets := make([]*Network, 1024)
for i, _ := range nets { for i := range nets {
net := sim.launchNode(false) net := sim.launchNode(false)
nets[i] = net nets[i] = net
if err := net.SetFallbackNodes([]*Node{bootnode.Self()}); err != nil { if err := net.SetFallbackNodes([]*Node{bootnode.Self()}); err != nil {
@ -147,7 +147,7 @@ func TestSimTopics(t *testing.T) {
func testHierarchicalTopics(i int) []Topic { func testHierarchicalTopics(i int) []Topic {
digits := strconv.FormatInt(int64(128+i/8), 2) digits := strconv.FormatInt(int64(128+i/8), 2)
res := make([]Topic, 8) res := make([]Topic, 8)
for i, _ := range res { for i := range res {
res[i] = Topic("foo" + digits[1:i+1]) res[i] = Topic("foo" + digits[1:i+1])
} }
return res return res
@ -167,7 +167,7 @@ func TestSimTopicHierarchy(t *testing.T) {
go func() { go func() {
nets := make([]*Network, 1024) nets := make([]*Network, 1024)
for i, _ := range nets { for i := range nets {
net := sim.launchNode(false) net := sim.launchNode(false)
nets[i] = net nets[i] = net
if err := net.SetFallbackNodes([]*Node{bootnode.Self()}); err != nil { if err := net.SetFallbackNodes([]*Node{bootnode.Self()}); err != nil {

@ -831,7 +831,7 @@ func (r *topicRadius) recalcRadius() (radius uint64, radiusLookup int) {
maxValue := float64(0) maxValue := float64(0)
now := mclock.Now() now := mclock.Now()
v := float64(0) v := float64(0)
for i, _ := range r.buckets { for i := range r.buckets {
r.buckets[i].update(now) r.buckets[i].update(now)
v += r.buckets[i].weights[trOutside] - r.buckets[i].weights[trInside] v += r.buckets[i].weights[trOutside] - r.buckets[i].weights[trInside]
r.buckets[i].value = v r.buckets[i].value = v

@ -316,7 +316,7 @@ func (t *topicTable) collectGarbage() {
t.checkDeleteNode(node) t.checkDeleteNode(node)
} }
for topic, _ := range t.topics { for topic := range t.topics {
t.checkDeleteTopic(topic) t.checkDeleteTopic(topic)
} }
} }

@ -82,7 +82,7 @@ func discoverPMP() Interface {
// any responses after a very short timeout. // any responses after a very short timeout.
timeout := time.NewTimer(1 * time.Second) timeout := time.NewTimer(1 * time.Second)
defer timeout.Stop() defer timeout.Stop()
for _ = range gws { for range gws {
select { select {
case c := <-found: case c := <-found:
if c != nil { if c != nil {

@ -299,7 +299,7 @@ func TestMatchProtocols(t *testing.T) {
} }
} }
// Make sure no protocols missed negotiation // Make sure no protocols missed negotiation
for name, _ := range tt.Match { for name := range tt.Match {
if _, ok := result[name]; !ok { if _, ok := result[name]; !ok {
t.Errorf("test %d, proto '%s': not negotiated, should have", i, name) t.Errorf("test %d, proto '%s': not negotiated, should have", i, name)
continue continue

@ -54,8 +54,6 @@ const (
var errServerStopped = errors.New("server stopped") var errServerStopped = errors.New("server stopped")
var srvjslog = logger.NewJsonLogger()
// Config holds Server options. // Config holds Server options.
type Config struct { type Config struct {
// This field must be set to a valid secp256k1 private key. // This field must be set to a valid secp256k1 private key.
@ -737,12 +735,6 @@ func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
// the peer. // the peer.
func (srv *Server) runPeer(p *Peer) { func (srv *Server) runPeer(p *Peer) {
glog.V(logger.Debug).Infof("Added %v\n", p) glog.V(logger.Debug).Infof("Added %v\n", p)
srvjslog.LogJson(&logger.P2PConnected{
RemoteId: p.ID().String(),
RemoteAddress: p.RemoteAddr().String(),
RemoteVersionString: p.Name(),
NumConnections: srv.PeerCount(),
})
if srv.newPeerHook != nil { if srv.newPeerHook != nil {
srv.newPeerHook(p) srv.newPeerHook(p)
@ -753,10 +745,6 @@ func (srv *Server) runPeer(p *Peer) {
srv.delpeer <- p srv.delpeer <- p
glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason) glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
srvjslog.LogJson(&logger.P2PDisconnected{
RemoteId: p.ID().String(),
NumConnections: srv.PeerCount(),
})
} }
// NodeInfo represents a short summary of the information known about the host. // NodeInfo represents a short summary of the information known about the host.

@ -1,176 +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 <http://www.gnu.org/licenses/>.
package dagger
import (
"hash"
"math/big"
"math/rand"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto/sha3"
"github.com/ethereum/go-ethereum/logger"
)
var powlogger = logger.NewLogger("POW")
type Dagger struct {
hash *big.Int
xn *big.Int
}
var Found bool
func (dag *Dagger) Find(obj *big.Int, resChan chan int64) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 1000; i++ {
rnd := r.Int63()
res := dag.Eval(big.NewInt(rnd))
powlogger.Infof("rnd %v\nres %v\nobj %v\n", rnd, res, obj)
if res.Cmp(obj) < 0 {
// Post back result on the channel
resChan <- rnd
// Notify other threads we've found a valid nonce
Found = true
}
// Break out if found
if Found {
break
}
}
resChan <- 0
}
func (dag *Dagger) Search(hash, diff *big.Int) (uint64, []byte) {
// TODO fix multi threading. Somehow it results in the wrong nonce
amountOfRoutines := 1
dag.hash = hash
obj := common.BigPow(2, 256)
obj = obj.Div(obj, diff)
Found = false
resChan := make(chan int64, 3)
var res int64
for k := 0; k < amountOfRoutines; k++ {
go dag.Find(obj, resChan)
// Wait for each go routine to finish
}
for k := 0; k < amountOfRoutines; k++ {
// Get the result from the channel. 0 = quit
if r := <-resChan; r != 0 {
res = r
}
}
return uint64(res), nil
}
func (dag *Dagger) Verify(hash, diff, nonce *big.Int) bool {
dag.hash = hash
obj := common.BigPow(2, 256)
obj = obj.Div(obj, diff)
return dag.Eval(nonce).Cmp(obj) < 0
}
func DaggerVerify(hash, diff, nonce *big.Int) bool {
dagger := &Dagger{}
dagger.hash = hash
obj := common.BigPow(2, 256)
obj = obj.Div(obj, diff)
return dagger.Eval(nonce).Cmp(obj) < 0
}
func (dag *Dagger) Node(L uint64, i uint64) *big.Int {
if L == i {
return dag.hash
}
var m *big.Int
if L == 9 {
m = big.NewInt(16)
} else {
m = big.NewInt(3)
}
sha := sha3.NewKeccak256()
sha.Reset()
d := sha3.NewKeccak256()
b := new(big.Int)
ret := new(big.Int)
for k := 0; k < int(m.Uint64()); k++ {
d.Reset()
d.Write(dag.hash.Bytes())
d.Write(dag.xn.Bytes())
d.Write(big.NewInt(int64(L)).Bytes())
d.Write(big.NewInt(int64(i)).Bytes())
d.Write(big.NewInt(int64(k)).Bytes())
b.SetBytes(Sum(d))
pk := b.Uint64() & ((1 << ((L - 1) * 3)) - 1)
sha.Write(dag.Node(L-1, pk).Bytes())
}
ret.SetBytes(Sum(sha))
return ret
}
func Sum(sha hash.Hash) []byte {
//in := make([]byte, 32)
return sha.Sum(nil)
}
func (dag *Dagger) Eval(N *big.Int) *big.Int {
pow := common.BigPow(2, 26)
dag.xn = pow.Div(N, pow)
sha := sha3.NewKeccak256()
sha.Reset()
ret := new(big.Int)
for k := 0; k < 4; k++ {
d := sha3.NewKeccak256()
b := new(big.Int)
d.Reset()
d.Write(dag.hash.Bytes())
d.Write(dag.xn.Bytes())
d.Write(N.Bytes())
d.Write(big.NewInt(int64(k)).Bytes())
b.SetBytes(Sum(d))
pk := (b.Uint64() & 0x1ffffff)
sha.Write(dag.Node(9, pk).Bytes())
}
return ret.SetBytes(Sum(sha))
}

@ -1,35 +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 <http://www.gnu.org/licenses/>.
package dagger
import (
"math/big"
"testing"
"github.com/ethereum/go-ethereum/common"
)
func BenchmarkDaggerSearch(b *testing.B) {
hash := big.NewInt(0)
diff := common.BigPow(2, 36)
o := big.NewInt(0) // nonce doesn't matter. We're only testing against speed, not validity
// Reset timer so the big generation isn't included in the benchmark
b.ResetTimer()
// Validate
DaggerVerify(hash, diff, o)
}

@ -1,113 +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 <http://www.gnu.org/licenses/>.
package ezp
import (
"encoding/binary"
"math/big"
"math/rand"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto/sha3"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/pow"
)
var powlogger = logger.NewLogger("POW")
type EasyPow struct {
hash *big.Int
HashRate int64
turbo bool
}
func New() *EasyPow {
return &EasyPow{turbo: false}
}
func (pow *EasyPow) GetHashrate() int64 {
return pow.HashRate
}
func (pow *EasyPow) Turbo(on bool) {
pow.turbo = on
}
func (pow *EasyPow) Search(block pow.Block, stop <-chan struct{}, index int) (uint64, []byte) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
hash := block.HashNoNonce()
diff := block.Difficulty()
//i := int64(0)
// TODO fix offset
i := rand.Int63()
starti := i
start := time.Now().UnixNano()
defer func() { pow.HashRate = 0 }()
// Make sure stop is empty
empty:
for {
select {
case <-stop:
default:
break empty
}
}
for {
select {
case <-stop:
return 0, nil
default:
i++
elapsed := time.Now().UnixNano() - start
hashes := ((float64(1e9) / float64(elapsed)) * float64(i-starti)) / 1000
pow.HashRate = int64(hashes)
sha := uint64(r.Int63())
if verify(hash, diff, sha) {
return sha, nil
}
}
if !pow.turbo {
time.Sleep(20 * time.Microsecond)
}
}
}
func (pow *EasyPow) Verify(block pow.Block) bool {
return Verify(block)
}
func verify(hash common.Hash, diff *big.Int, nonce uint64) bool {
sha := sha3.NewKeccak256()
n := make([]byte, 8)
binary.PutUvarint(n, nonce)
sha.Write(n)
sha.Write(hash[:])
verification := new(big.Int).Div(common.BigPow(2, 256), diff)
res := common.BigD(sha.Sum(nil))
return res.Cmp(verification) <= 0
}
func Verify(block pow.Block) bool {
return verify(block.HashNoNonce(), block.Difficulty(), block.Nonce())
}

@ -166,7 +166,7 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
// subscribe are special, they will always use `subscribeMethod` as first param in the payload // subscribe are special, they will always use `subscribeMethod` as first param in the payload
if in.Method == subscribeMethod { if in.Method == subscribeMethod {
reqs := []rpcRequest{rpcRequest{id: &in.Id, isPubSub: true}} reqs := []rpcRequest{{id: &in.Id, isPubSub: true}}
if len(in.Payload) > 0 { if len(in.Payload) > 0 {
// first param must be subscription name // first param must be subscription name
var subscribeMethod [1]string var subscribeMethod [1]string
@ -184,7 +184,7 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
} }
if in.Method == unsubscribeMethod { if in.Method == unsubscribeMethod {
return []rpcRequest{rpcRequest{id: &in.Id, isPubSub: true, return []rpcRequest{{id: &in.Id, isPubSub: true,
method: unsubscribeMethod, params: in.Payload}}, false, nil method: unsubscribeMethod, params: in.Payload}}, false, nil
} }
@ -195,10 +195,10 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) {
// regular RPC call // regular RPC call
if len(in.Payload) == 0 { if len(in.Payload) == 0 {
return []rpcRequest{rpcRequest{service: elems[0], method: elems[1], id: &in.Id}}, false, nil return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil
} }
return []rpcRequest{rpcRequest{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil
} }
// parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication

@ -538,13 +538,6 @@ func (self *bzz) protoError(code int, format string, params ...interface{}) (err
return return
} }
func (self *bzz) protoErrorDisconnect(err *errs.Error) {
err.Log(glog.V(logger.Info))
if err.Fatal() {
self.peer.Disconnect(p2p.DiscSubprotocolError)
}
}
func (self *bzz) send(msg uint64, data interface{}) error { func (self *bzz) send(msg uint64, data interface{}) error {
if self.hive.blockWrite { if self.hive.blockWrite {
return fmt.Errorf("network write blocked") return fmt.Errorf("network write blocked")

@ -354,7 +354,7 @@ func (s *DbStore) Get(key Key) (chunk *Chunk, err error) {
hasher := s.hashfunc() hasher := s.hashfunc()
hasher.Write(data) hasher.Write(data)
hash := hasher.Sum(nil) hash := hasher.Sum(nil)
if bytes.Compare(hash, key) != 0 { if !bytes.Equal(hash, key) {
s.db.Delete(getDataKey(index.Idx)) s.db.Delete(getDataKey(index.Idx))
err = fmt.Errorf("invalid chunk. hash=%x, key=%v", hash, key[:]) err = fmt.Errorf("invalid chunk. hash=%x, key=%v", hash, key[:])
return return

@ -67,7 +67,7 @@ func TestDPArandom(t *testing.T) {
ioutil.WriteFile("/tmp/result.bzz.16M", resultSlice, 0666) ioutil.WriteFile("/tmp/result.bzz.16M", resultSlice, 0666)
localStore.memStore = NewMemStore(dbStore, defaultCacheCapacity) localStore.memStore = NewMemStore(dbStore, defaultCacheCapacity)
resultReader = dpa.Retrieve(key) resultReader = dpa.Retrieve(key)
for i, _ := range resultSlice { for i := range resultSlice {
resultSlice[i] = 0 resultSlice[i] = 0
} }
n, err = resultReader.ReadAt(resultSlice, 0) n, err = resultReader.ReadAt(resultSlice, 0)
@ -128,7 +128,7 @@ func TestDPA_capacity(t *testing.T) {
dpa.ChunkStore = localStore dpa.ChunkStore = localStore
// localStore.dbStore.setCapacity(0) // localStore.dbStore.setCapacity(0)
resultReader = dpa.Retrieve(key) resultReader = dpa.Retrieve(key)
for i, _ := range resultSlice { for i := range resultSlice {
resultSlice[i] = 0 resultSlice[i] = 0
} }
n, err = resultReader.ReadAt(resultSlice, 0) n, err = resultReader.ReadAt(resultSlice, 0)

@ -41,7 +41,7 @@ func (x Key) Size() uint {
} }
func (x Key) isEqual(y Key) bool { func (x Key) isEqual(y Key) bool {
return bytes.Compare(x, y) == 0 return bytes.Equal(x, y)
} }
func (h Key) bits(i, j uint) uint { func (h Key) bits(i, j uint) uint {

@ -552,9 +552,7 @@ func LoadBlockTests(file string) (map[string]*BlockTest, error) {
// Nothing to see here, please move along... // Nothing to see here, please move along...
func prepInt(base int, s string) string { func prepInt(base int, s string) string {
if base == 16 { if base == 16 {
if strings.HasPrefix(s, "0x") { s = strings.TrimPrefix(s, "0x")
s = s[2:]
}
if len(s) == 0 { if len(s) == 0 {
s = "00" s = "00"
} }

@ -87,11 +87,7 @@ func readJsonHttp(uri string, value interface{}) error {
} }
defer resp.Body.Close() defer resp.Body.Close()
err = readJson(resp.Body, value) return readJson(resp.Body, value)
if err != nil {
return err
}
return nil
} }
func readJsonFile(fn string, value interface{}) error { func readJsonFile(fn string, value interface{}) error {

@ -159,7 +159,7 @@ func runStateTest(chainConfig *params.ChainConfig, test VmTest) error {
} else { } else {
rexp = common.FromHex(test.Out) rexp = common.FromHex(test.Out)
} }
if bytes.Compare(rexp, ret) != 0 { if !bytes.Equal(rexp, ret) {
return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret) return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret)
} }

@ -172,7 +172,7 @@ func runVmTest(test VmTest) error {
// Compare expected and actual return // Compare expected and actual return
rexp := common.FromHex(test.Out) rexp := common.FromHex(test.Out)
if bytes.Compare(rexp, ret) != 0 { if !bytes.Equal(rexp, ret) {
return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret) return fmt.Errorf("return failed. Expected %x, got %x\n", rexp, ret)
} }

Some files were not shown because too many files have changed in this diff Show More