diff --git a/accounts/abi/argument.go b/accounts/abi/argument.go index 501cb16213..00c41fcd23 100644 --- a/accounts/abi/argument.go +++ b/accounts/abi/argument.go @@ -257,7 +257,6 @@ func (arguments Arguments) unpackTuple(v interface{}, marshalledValues []interfa } } return nil - } // UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification, diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 7371dfb1f1..71c5930cfa 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -489,12 +489,15 @@ func (fb *filterBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event. return nil }) } + func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { return fb.bc.SubscribeChainEvent(ch) } + func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { return fb.bc.SubscribeRemovedLogsEvent(ch) } + func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { return fb.bc.SubscribeLogsEvent(ch) } diff --git a/accounts/abi/bind/backends/simulated_test.go b/accounts/abi/bind/backends/simulated_test.go index bd75807d75..ff3f072d5f 100644 --- a/accounts/abi/bind/backends/simulated_test.go +++ b/accounts/abi/bind/backends/simulated_test.go @@ -78,5 +78,4 @@ func TestSimulatedBackend(t *testing.T) { if isPending { t.Fatal("transaction should not have pending status") } - } diff --git a/accounts/abi/bind/base_test.go b/accounts/abi/bind/base_test.go index f65c9e9b49..24eec18641 100644 --- a/accounts/abi/bind/base_test.go +++ b/accounts/abi/bind/base_test.go @@ -47,8 +47,8 @@ func (mc *mockCaller) CallContract(ctx context.Context, call ethereum.CallMsg, b mc.callContractBlockNumber = blockNumber return nil, nil } -func TestPassingBlockNumber(t *testing.T) { +func TestPassingBlockNumber(t *testing.T) { mc := &mockCaller{} bc := bind.NewBoundContract(common.HexToAddress("0x0"), abi.ABI{ diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index 5ee30d0249..96f4efcf8d 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -174,11 +174,11 @@ var bindType = map[Lang]func(kind abi.Type) string{ // Array sizes may also be "", indicating a dynamic array. func wrapArray(stringKind string, innerLen int, innerMapping string) (string, []string) { remainder := stringKind[innerLen:] - //find all the sizes + // find all the sizes matches := regexp.MustCompile(`\[(\d*)\]`).FindAllStringSubmatch(remainder, -1) parts := make([]string, 0, len(matches)) for _, match := range matches { - //get group 1 from the regex match + // get group 1 from the regex match parts = append(parts, match[1]) } return innerMapping, parts @@ -188,7 +188,7 @@ func wrapArray(stringKind string, innerLen int, innerMapping string) (string, [] // Simply returns the inner type if arraySizes is empty. func arrayBindingGo(inner string, arraySizes []string) string { out := "" - //prepend all array sizes, from outer (end arraySizes) to inner (start arraySizes) + // prepend all array sizes, from outer (end arraySizes) to inner (start arraySizes) for i := len(arraySizes) - 1; i >= 0; i-- { out += "[" + arraySizes[i] + "]" } @@ -209,7 +209,6 @@ func bindTypeGo(kind abi.Type) string { // (Or just the type itself if it is not an array or slice) // The length of the matched part is returned, with the translated type. func bindUnnestedTypeGo(stringKind string) (int, string) { - switch { case strings.HasPrefix(stringKind, "address"): return len("address"), "common.Address" @@ -257,7 +256,6 @@ func bindTypeJava(kind abi.Type) string { // (Or just the type itself if it is not an array or slice) // The length of the matched part is returned, with the translated type. func bindUnnestedTypeJava(stringKind string) (int, string) { - switch { case strings.HasPrefix(stringKind, "address"): parts := regexp.MustCompile(`address(\[[0-9]*\])?`).FindStringSubmatch(stringKind) @@ -277,7 +275,7 @@ func bindUnnestedTypeJava(stringKind string) (int, string) { return len(parts[0]), "byte[]" case strings.HasPrefix(stringKind, "int") || strings.HasPrefix(stringKind, "uint"): - //Note that uint and int (without digits) are also matched, + // Note that uint and int (without digits) are also matched, // these are size 256, and will translate to BigInt (the default). parts := regexp.MustCompile(`(u)?int([0-9]*)`).FindStringSubmatch(stringKind) if len(parts) != 3 { @@ -291,7 +289,7 @@ func bindUnnestedTypeJava(stringKind string) (int, string) { "64": "long", }[parts[2]] - //default to BigInt + // default to BigInt if namedSize == "" { namedSize = "BigInt" } diff --git a/accounts/abi/error.go b/accounts/abi/error.go index 9d8674ad08..f66730be88 100644 --- a/accounts/abi/error.go +++ b/accounts/abi/error.go @@ -22,9 +22,7 @@ import ( "reflect" ) -var ( - errBadBool = errors.New("abi: improperly encoded boolean value") -) +var errBadBool = errors.New("abi: improperly encoded boolean value") // formatSliceString formats the reflection kind with the given slice size // and returns a formatted string representation. @@ -75,7 +73,6 @@ func typeCheck(t Type, value reflect.Value) error { } else { return nil } - } // typeErr returns a formatted type casting error. diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go index e735cceb88..2d109ba8f2 100644 --- a/accounts/abi/event_test.go +++ b/accounts/abi/event_test.go @@ -165,7 +165,6 @@ func TestEventMultiValueWithArrayUnpack(t *testing.T) { } func TestEventTupleUnpack(t *testing.T) { - type EventTransfer struct { Value *big.Int } @@ -269,7 +268,8 @@ func TestEventTupleUnpack(t *testing.T) { &EventPledge{ addr, bigintExpected2, - [3]byte{'u', 's', 'd'}}, + [3]byte{'u', 's', 'd'}, + }, jsonEventPledge, "", "Can unpack Pledge event into structure", @@ -279,7 +279,8 @@ func TestEventTupleUnpack(t *testing.T) { &[]interface{}{ &addr, &bigintExpected2, - &[3]byte{'u', 's', 'd'}}, + &[3]byte{'u', 's', 'd'}, + }, jsonEventPledge, "", "Can unpack Pledge event into slice", @@ -289,7 +290,8 @@ func TestEventTupleUnpack(t *testing.T) { &[3]interface{}{ &addr, &bigintExpected2, - &[3]byte{'u', 's', 'd'}}, + &[3]byte{'u', 's', 'd'}, + }, jsonEventPledge, "", "Can unpack Pledge event into an array", diff --git a/accounts/abi/pack.go b/accounts/abi/pack.go index 36c58265bd..cacd3e2d6f 100644 --- a/accounts/abi/pack.go +++ b/accounts/abi/pack.go @@ -77,5 +77,4 @@ func packNum(value reflect.Value) []byte { default: panic("abi: fatal error") } - } diff --git a/accounts/abi/pack_test.go b/accounts/abi/pack_test.go index 10cd3a3962..ffb3842950 100644 --- a/accounts/abi/pack_test.go +++ b/accounts/abi/pack_test.go @@ -530,7 +530,8 @@ func TestPack(t *testing.T) { FieldA *big.Int `abi:"a"` // Test whether abi tag works for nested tuple B []*big.Int }{big.NewInt(1), []*big.Int{big.NewInt(1), big.NewInt(0)}}, - B: []*big.Int{big.NewInt(1), big.NewInt(0)}}, + B: []*big.Int{big.NewInt(1), big.NewInt(0)}, + }, common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040" + // a offset "00000000000000000000000000000000000000000000000000000000000000e0" + // b offset "0000000000000000000000000000000000000000000000000000000000000001" + // a.a value diff --git a/accounts/abi/reflect.go b/accounts/abi/reflect.go index ccc6a65932..8fe6c61127 100644 --- a/accounts/abi/reflect.go +++ b/accounts/abi/reflect.go @@ -112,7 +112,6 @@ func requireAssignable(dst, src reflect.Value) error { // requireUnpackKind verifies preconditions for unpacking `args` into `kind` func requireUnpackKind(v reflect.Value, t reflect.Type, k reflect.Kind, args Arguments) error { - switch k { case reflect.Struct: case reflect.Slice, reflect.Array: diff --git a/accounts/abi/type.go b/accounts/abi/type.go index 1a37182353..34188caa54 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -57,10 +57,8 @@ type Type struct { TupleRawNames []string // Raw field name of all tuple fields } -var ( - // typeRegex parses the abi sub types - typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?") -) +// typeRegex parses the abi sub types +var typeRegex = regexp.MustCompile("([a-zA-Z]+)(([0-9]+)(x([0-9]+))?)?") // NewType creates a new reflection type of abi type given in t. func NewType(t string, components []ArgumentMarshaling) (typ Type, err error) { diff --git a/accounts/abi/type_test.go b/accounts/abi/type_test.go index 5023456aec..c3c885a890 100644 --- a/accounts/abi/type_test.go +++ b/accounts/abi/type_test.go @@ -95,14 +95,18 @@ func TestTypeRegexp(t *testing.T) { // {"fixed[2]", nil, Type{}}, // {"fixed128x128[]", nil, Type{}}, // {"fixed128x128[2]", nil, Type{}}, - {"tuple", []ArgumentMarshaling{{Name: "a", Type: "int64"}}, Type{Kind: reflect.Struct, T: TupleTy, Type: reflect.TypeOf(struct { - A int64 `json:"a"` - }{}), stringKind: "(int64)", - TupleElems: []*Type{{Kind: reflect.Int64, T: IntTy, Type: reflect.TypeOf(int64(0)), Size: 64, stringKind: "int64"}}, TupleRawNames: []string{"a"}}}, - {"tuple with long name", []ArgumentMarshaling{{Name: "aTypicalParamName", Type: "int64"}}, Type{Kind: reflect.Struct, T: TupleTy, Type: reflect.TypeOf(struct { - ATypicalParamName int64 `json:"aTypicalParamName"` - }{}), stringKind: "(int64)", - TupleElems: []*Type{{Kind: reflect.Int64, T: IntTy, Type: reflect.TypeOf(int64(0)), Size: 64, stringKind: "int64"}}, TupleRawNames: []string{"aTypicalParamName"}}}, + {"tuple", []ArgumentMarshaling{{Name: "a", Type: "int64"}}, Type{ + Kind: reflect.Struct, T: TupleTy, Type: reflect.TypeOf(struct { + A int64 `json:"a"` + }{}), stringKind: "(int64)", + TupleElems: []*Type{{Kind: reflect.Int64, T: IntTy, Type: reflect.TypeOf(int64(0)), Size: 64, stringKind: "int64"}}, TupleRawNames: []string{"a"}, + }}, + {"tuple with long name", []ArgumentMarshaling{{Name: "aTypicalParamName", Type: "int64"}}, Type{ + Kind: reflect.Struct, T: TupleTy, Type: reflect.TypeOf(struct { + ATypicalParamName int64 `json:"aTypicalParamName"` + }{}), stringKind: "(int64)", + TupleElems: []*Type{{Kind: reflect.Int64, T: IntTy, Type: reflect.TypeOf(int64(0)), Size: 64, stringKind: "int64"}}, TupleRawNames: []string{"aTypicalParamName"}, + }}, } for _, tt := range tests { diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go index b2e61d06c4..66d584ff86 100644 --- a/accounts/abi/unpack.go +++ b/accounts/abi/unpack.go @@ -112,7 +112,6 @@ func readFixedBytes(t Type, word []byte) (interface{}, error) { reflect.Copy(array, reflect.ValueOf(word[0:t.Size])) return array.Interface(), nil - } // iteratively unpack elements diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index fa8a69d05c..bcf66c2020 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -679,7 +679,7 @@ func TestMultiReturnWithDeeplyNestedArray(t *testing.T) { // construct the test array, each 3 char element is joined with 61 '0' chars, // to from the ((3 + 61) * 0.5) = 32 byte elements in the array. buff.Write(common.Hex2Bytes(strings.Join([]string{ - "", //empty, to apply the 61-char separator to the first element as well. + "", // empty, to apply the 61-char separator to the first element as well. "111", "112", "113", "121", "122", "123", "211", "212", "213", "221", "222", "223", "311", "312", "313", "321", "322", "323", diff --git a/accounts/external/backend.go b/accounts/external/backend.go index 21a313b669..9751eba309 100644 --- a/accounts/external/backend.go +++ b/accounts/external/backend.go @@ -207,6 +207,7 @@ func (api *ExternalSigner) SignTextWithPassphrase(account accounts.Account, pass func (api *ExternalSigner) SignTxWithPassphrase(account accounts.Account, passphrase string, tx *types.Transaction, chainID *big.Int) (*types.Transaction, error) { return nil, fmt.Errorf("passphrase-operations not supported on external signers") } + func (api *ExternalSigner) SignDataWithPassphrase(account accounts.Account, passphrase, mimeType string, data []byte) ([]byte, error) { return nil, fmt.Errorf("passphrase-operations not supported on external signers") } diff --git a/accounts/keystore/key.go b/accounts/keystore/key.go index 84d8df0c5a..2fc4652955 100644 --- a/accounts/keystore/key.go +++ b/accounts/keystore/key.go @@ -35,9 +35,7 @@ import ( "github.com/pborman/uuid" ) -const ( - version = 3 -) +const version = 3 type Key struct { Id uuid.UUID // Version 4 "random" for unique id not derived from key data diff --git a/accounts/keystore/passphrase.go b/accounts/keystore/passphrase.go index a0b6cf5385..607d0e07a9 100644 --- a/accounts/keystore/passphrase.go +++ b/accounts/keystore/passphrase.go @@ -137,7 +137,6 @@ func (ks keyStorePassphrase) JoinPath(filename string) string { // Encryptdata encrypts the data given as 'data' with the password 'auth'. func EncryptDataV3(data, auth []byte, scryptN, scryptP int) (CryptoJSON, error) { - salt := make([]byte, 32) if _, err := io.ReadFull(rand.Reader, salt); err != nil { panic("reading from crypto/rand failed: " + err.Error()) diff --git a/accounts/url_test.go b/accounts/url_test.go index 8027728719..9ff375b58f 100644 --- a/accounts/url_test.go +++ b/accounts/url_test.go @@ -16,9 +16,7 @@ package accounts -import ( - "testing" -) +import "testing" func TestURLParsing(t *testing.T) { url, err := parseURL("https://ethereum.org") diff --git a/accounts/usbwallet/trezor/messages.pb.go b/accounts/usbwallet/trezor/messages.pb.go index 15bb6fb73b..a09670a05a 100644 --- a/accounts/usbwallet/trezor/messages.pb.go +++ b/accounts/usbwallet/trezor/messages.pb.go @@ -167,6 +167,7 @@ var MessageType_name = map[int32]string{ 112: "MessageType_DebugLinkMemoryWrite", 113: "MessageType_DebugLinkFlashErase", } + var MessageType_value = map[string]int32{ "MessageType_Initialize": 0, "MessageType_Ping": 1, @@ -248,9 +249,11 @@ func (x MessageType) Enum() *MessageType { *p = x return p } + func (x MessageType) String() string { return proto.EnumName(MessageType_name, int32(x)) } + func (x *MessageType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(MessageType_value, data, "MessageType") if err != nil { diff --git a/accounts/usbwallet/trezor/types.pb.go b/accounts/usbwallet/trezor/types.pb.go index 25b7672d23..8fbecea03e 100644 --- a/accounts/usbwallet/trezor/types.pb.go +++ b/accounts/usbwallet/trezor/types.pb.go @@ -146,6 +146,7 @@ var FailureType_name = map[int32]string{ 11: "Failure_NotInitialized", 99: "Failure_FirmwareError", } + var FailureType_value = map[string]int32{ "Failure_UnexpectedMessage": 1, "Failure_ButtonExpected": 2, @@ -166,9 +167,11 @@ func (x FailureType) Enum() *FailureType { *p = x return p } + func (x FailureType) String() string { return proto.EnumName(FailureType_name, int32(x)) } + func (x *FailureType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FailureType_value, data, "FailureType") if err != nil { @@ -201,6 +204,7 @@ var OutputScriptType_name = map[int32]string{ 4: "PAYTOWITNESS", 5: "PAYTOP2SHWITNESS", } + var OutputScriptType_value = map[string]int32{ "PAYTOADDRESS": 0, "PAYTOSCRIPTHASH": 1, @@ -215,9 +219,11 @@ func (x OutputScriptType) Enum() *OutputScriptType { *p = x return p } + func (x OutputScriptType) String() string { return proto.EnumName(OutputScriptType_name, int32(x)) } + func (x *OutputScriptType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(OutputScriptType_value, data, "OutputScriptType") if err != nil { @@ -248,6 +254,7 @@ var InputScriptType_name = map[int32]string{ 3: "SPENDWITNESS", 4: "SPENDP2SHWITNESS", } + var InputScriptType_value = map[string]int32{ "SPENDADDRESS": 0, "SPENDMULTISIG": 1, @@ -261,9 +268,11 @@ func (x InputScriptType) Enum() *InputScriptType { *p = x return p } + func (x InputScriptType) String() string { return proto.EnumName(InputScriptType_name, int32(x)) } + func (x *InputScriptType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(InputScriptType_value, data, "InputScriptType") if err != nil { @@ -294,6 +303,7 @@ var RequestType_name = map[int32]string{ 3: "TXFINISHED", 4: "TXEXTRADATA", } + var RequestType_value = map[string]int32{ "TXINPUT": 0, "TXOUTPUT": 1, @@ -307,9 +317,11 @@ func (x RequestType) Enum() *RequestType { *p = x return p } + func (x RequestType) String() string { return proto.EnumName(RequestType_name, int32(x)) } + func (x *RequestType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(RequestType_value, data, "RequestType") if err != nil { @@ -352,6 +364,7 @@ var ButtonRequestType_name = map[int32]string{ 10: "ButtonRequest_Address", 11: "ButtonRequest_PublicKey", } + var ButtonRequestType_value = map[string]int32{ "ButtonRequest_Other": 1, "ButtonRequest_FeeOverThreshold": 2, @@ -371,9 +384,11 @@ func (x ButtonRequestType) Enum() *ButtonRequestType { *p = x return p } + func (x ButtonRequestType) String() string { return proto.EnumName(ButtonRequestType_name, int32(x)) } + func (x *ButtonRequestType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(ButtonRequestType_value, data, "ButtonRequestType") if err != nil { @@ -400,6 +415,7 @@ var PinMatrixRequestType_name = map[int32]string{ 2: "PinMatrixRequestType_NewFirst", 3: "PinMatrixRequestType_NewSecond", } + var PinMatrixRequestType_value = map[string]int32{ "PinMatrixRequestType_Current": 1, "PinMatrixRequestType_NewFirst": 2, @@ -411,9 +427,11 @@ func (x PinMatrixRequestType) Enum() *PinMatrixRequestType { *p = x return p } + func (x PinMatrixRequestType) String() string { return proto.EnumName(PinMatrixRequestType_name, int32(x)) } + func (x *PinMatrixRequestType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(PinMatrixRequestType_value, data, "PinMatrixRequestType") if err != nil { @@ -445,6 +463,7 @@ var RecoveryDeviceType_name = map[int32]string{ 0: "RecoveryDeviceType_ScrambledWords", 1: "RecoveryDeviceType_Matrix", } + var RecoveryDeviceType_value = map[string]int32{ "RecoveryDeviceType_ScrambledWords": 0, "RecoveryDeviceType_Matrix": 1, @@ -455,9 +474,11 @@ func (x RecoveryDeviceType) Enum() *RecoveryDeviceType { *p = x return p } + func (x RecoveryDeviceType) String() string { return proto.EnumName(RecoveryDeviceType_name, int32(x)) } + func (x *RecoveryDeviceType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(RecoveryDeviceType_value, data, "RecoveryDeviceType") if err != nil { @@ -484,6 +505,7 @@ var WordRequestType_name = map[int32]string{ 1: "WordRequestType_Matrix9", 2: "WordRequestType_Matrix6", } + var WordRequestType_value = map[string]int32{ "WordRequestType_Plain": 0, "WordRequestType_Matrix9": 1, @@ -495,9 +517,11 @@ func (x WordRequestType) Enum() *WordRequestType { *p = x return p } + func (x WordRequestType) String() string { return proto.EnumName(WordRequestType_name, int32(x)) } + func (x *WordRequestType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(WordRequestType_value, data, "WordRequestType") if err != nil { diff --git a/build/ci.go b/build/ci.go index f5553fd300..cc16573356 100644 --- a/build/ci.go +++ b/build/ci.go @@ -1007,9 +1007,9 @@ func newPodMetadata(env build.Environment, archive string) podMetadata { // Cross compilation func doXgo(cmdline []string) { - var ( - alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`) - ) + + var alltools = flag.Bool("alltools", false, `Flag whether we're building all known tools, or only on in particular`) + flag.CommandLine.Parse(cmdline) env := build.Env() diff --git a/cmd/clef/main.go b/cmd/clef/main.go index 06c034a554..90d24d1adb 100644 --- a/cmd/clef/main.go +++ b/cmd/clef/main.go @@ -176,14 +176,16 @@ Clef that the file is 'safe' to execute.`, Description: ` The setpw command stores a password for a given address (keyfile). If you enter a blank passphrase, it will remove any stored credential for that address (keyfile) -`} +`, + } gendocCommand = cli.Command{ Action: GenDoc, Name: "gendoc", Usage: "Generate documentation about json-rpc format", Description: ` The gendoc generates example structures of the json-rpc communication types. -`} +`, + } ) func init() { @@ -213,8 +215,8 @@ func init() { } app.Action = signer app.Commands = []cli.Command{initCommand, attestCommand, setCredentialCommand, gendocCommand} - } + func main() { if err := app.Run(os.Args); err != nil { fmt.Fprintln(os.Stderr, err) @@ -281,6 +283,7 @@ NOTE: This file does not contain your accounts. Those need to be backed up separ `) return nil } + func attestFile(ctx *cli.Context) error { if len(ctx.Args()) < 1 { utils.Fatalf("This command requires an argument.") @@ -352,9 +355,9 @@ func signer(c *cli.Context) error { if err := initialize(c); err != nil { return err } - var ( - ui core.UIClientAPI - ) + + var ui core.UIClientAPI + if c.GlobalBool(stdiouiFlag.Name) { log.Info("Using stdin/stdout as UI-channel") ui = core.NewStdIOUI() @@ -391,7 +394,7 @@ func signer(c *cli.Context) error { jsStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "jsstorage.json"), jskey) configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confkey) - //Do we have a rule-file? + // Do we have a rule-file? if ruleFile := c.GlobalString(ruleFlag.Name); ruleFile != "" { ruleJS, err := ioutil.ReadFile(c.GlobalString(ruleFile)) if err != nil { @@ -449,7 +452,8 @@ func signer(c *cli.Context) error { Namespace: "account", Public: true, Service: api, - Version: "1.0"}, + Version: "1.0", + }, } if c.GlobalBool(utils.RPCEnabledFlag.Name) { @@ -554,6 +558,7 @@ func homeDir() string { } return "" } + func readMasterKey(ctx *cli.Context, ui core.UIClientAPI) ([]byte, error) { var ( file string @@ -577,7 +582,8 @@ func readMasterKey(ctx *cli.Context, ui core.UIClientAPI) ([]byte, error) { resp, err := ui.OnInputRequired(core.UserInputRequest{ Title: "Master Password", Prompt: "Please enter the password to decrypt the master seed", - IsPassword: true}) + IsPassword: true, + }) if err != nil { return nil, err } @@ -634,7 +640,6 @@ func confirm(text string) bool { } func testExternalUI(api *core.SignerAPI) { - ctx := context.WithValue(context.Background(), "remote", "clef binary") ctx = context.WithValue(ctx, "scheme", "in-proc") ctx = context.WithValue(ctx, "local", "main") @@ -755,7 +760,6 @@ func testExternalUI(api *core.SignerAPI) { } result := fmt.Sprintf("Tests completed. %d errors:\n%s\n", len(errs), strings.Join(errs, "\n")) api.UI.ShowInfo(result) - } // getPassPhrase retrieves the password associated with clef, either fetched @@ -813,7 +817,6 @@ func decryptSeed(keyjson []byte, auth string) ([]byte, error) { // GenDoc outputs examples of all structures used in json-rpc communication func GenDoc(ctx *cli.Context) { - var ( a = common.HexToAddress("0xdeadbeef000000000000000000000000deadbeef") b = common.HexToAddress("0x1111111122222222222233333333334444444444") @@ -848,7 +851,8 @@ func GenDoc(ctx *cli.Context) { ContentType: accounts.MimetypeTextPlain, Rawdata: []byte(msg), Message: message, - Hash: sighash}) + Hash: sighash, + }) } { // Sign plain text response add("SignDataResponse - approve", "Response to SignDataRequest", @@ -883,13 +887,15 @@ func GenDoc(ctx *cli.Context) { GasPrice: hexutil.Big(*big.NewInt(5)), Gas: 1000, Input: nil, - }}) + }, + }) } { // Sign tx response data := hexutil.Bytes([]byte{0x04, 0x03, 0x02, 0x01}) add("SignTxResponse - approve", "Response to request to sign a transaction. This response needs to contain the `transaction`"+ ", because the UI is free to make modifications to the transaction.", - &core.SignTxResponse{Approved: true, + &core.SignTxResponse{ + Approved: true, Transaction: core.SendTxArgs{ Data: &data, Nonce: 0x4, @@ -899,7 +905,8 @@ func GenDoc(ctx *cli.Context) { GasPrice: hexutil.Big(*big.NewInt(5)), Gas: 1000, Input: nil, - }}) + }, + }) add("SignTxResponse - deny", "Response to SignTxRequest. When denying a request, there's no need to "+ "provide the transaction in return", &core.SignTxResponse{}) @@ -939,7 +946,8 @@ func GenDoc(ctx *cli.Context) { Meta: meta, Accounts: []accounts.Account{ {a, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/a"}}, - {b, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}}, + {b, accounts.URL{Scheme: "keystore", Path: "/path/to/keyfile/b"}}, + }, }) add("ListResponse", "Response to list request. The response contains a list of all addresses to show to the caller. "+ @@ -948,7 +956,8 @@ func GenDoc(ctx *cli.Context) { Accounts: []accounts.Account{ {common.HexToAddress("0xcowbeef000000cowbeef00000000000000000c0w"), accounts.URL{Path: ".. ignored .."}}, {common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff"), accounts.URL{}}, - }}) + }, + }) } fmt.Println(`## UI Client interface diff --git a/cmd/ethkey/main.go b/cmd/ethkey/main.go index c434da0c05..4cbc41e8cc 100644 --- a/cmd/ethkey/main.go +++ b/cmd/ethkey/main.go @@ -24,9 +24,7 @@ import ( "gopkg.in/urfave/cli.v1" ) -const ( - defaultKeyfileName = "keyfile.json" -) +const defaultKeyfileName = "keyfile.json" // Git SHA1 commit hash of the release (set via linker flags) var gitCommit = "" diff --git a/cmd/evm/runner.go b/cmd/evm/runner.go index bc5d00cfbe..3c58855f48 100644 --- a/cmd/evm/runner.go +++ b/cmd/evm/runner.go @@ -52,7 +52,7 @@ var runCommand = cli.Command{ // the initialized Genesis structure func readGenesis(genesisPath string) *core.Genesis { // Make sure we have a valid genesis JSON - //genesisPath := ctx.Args().First() + // genesisPath := ctx.Args().First() if len(genesisPath) == 0 { utils.Fatalf("Must supply path to genesis JSON file") } @@ -127,7 +127,7 @@ func runCmd(ctx *cli.Context) error { var err error // If - is specified, it means that code comes from stdin if ctx.GlobalString(CodeFileFlag.Name) == "-" { - //Try reading from stdin + // Try reading from stdin if hexcode, err = ioutil.ReadAll(os.Stdin); err != nil { fmt.Printf("Could not load code from stdin: %v\n", err) os.Exit(1) diff --git a/cmd/faucet/faucet.go b/cmd/faucet/faucet.go index 78b4a65634..6218fa887c 100644 --- a/cmd/faucet/faucet.go +++ b/cmd/faucet/faucet.go @@ -84,9 +84,7 @@ var ( logFlag = flag.Int("loglevel", 3, "Log level to use for Ethereum and the faucet") ) -var ( - ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) -) +var ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) func main() { // Parse the flags and set up the logger to print everything requested diff --git a/cmd/faucet/website.go b/cmd/faucet/website.go index fab1d43460..1b47323bce 100644 --- a/cmd/faucet/website.go +++ b/cmd/faucet/website.go @@ -51,18 +51,23 @@ type bindataFileInfo struct { func (fi bindataFileInfo) Name() string { return fi.name } + func (fi bindataFileInfo) Size() int64 { return fi.size } + func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } + func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } + func (fi bindataFileInfo) IsDir() bool { return false } + func (fi bindataFileInfo) Sys() interface{} { return nil } diff --git a/cmd/geth/main.go b/cmd/geth/main.go index 4f3849a41b..78f202c52a 100644 --- a/cmd/geth/main.go +++ b/cmd/geth/main.go @@ -43,9 +43,7 @@ import ( cli "gopkg.in/urfave/cli.v1" ) -const ( - clientIdentifier = "geth" // Client identifier to advertise over the network -) +const clientIdentifier = "geth" // Client identifier to advertise over the network var ( // Git SHA1 commit hash of the release (set via linker flags) diff --git a/cmd/puppeth/genesis.go b/cmd/puppeth/genesis.go index ae7675cd9b..8aa1026bc2 100644 --- a/cmd/puppeth/genesis.go +++ b/cmd/puppeth/genesis.go @@ -147,25 +147,41 @@ func newAlethGenesisSpec(network string, genesis *core.Genesis) (*alethGenesisSp spec.setAccount(address, account) } - spec.setPrecompile(1, &alethGenesisSpecBuiltin{Name: "ecrecover", - Linear: &alethGenesisSpecLinearPricing{Base: 3000}}) - spec.setPrecompile(2, &alethGenesisSpecBuiltin{Name: "sha256", - Linear: &alethGenesisSpecLinearPricing{Base: 60, Word: 12}}) - spec.setPrecompile(3, &alethGenesisSpecBuiltin{Name: "ripemd160", - Linear: &alethGenesisSpecLinearPricing{Base: 600, Word: 120}}) - spec.setPrecompile(4, &alethGenesisSpecBuiltin{Name: "identity", - Linear: &alethGenesisSpecLinearPricing{Base: 15, Word: 3}}) + spec.setPrecompile(1, &alethGenesisSpecBuiltin{ + Name: "ecrecover", + Linear: &alethGenesisSpecLinearPricing{Base: 3000}, + }) + spec.setPrecompile(2, &alethGenesisSpecBuiltin{ + Name: "sha256", + Linear: &alethGenesisSpecLinearPricing{Base: 60, Word: 12}, + }) + spec.setPrecompile(3, &alethGenesisSpecBuiltin{ + Name: "ripemd160", + Linear: &alethGenesisSpecLinearPricing{Base: 600, Word: 120}, + }) + spec.setPrecompile(4, &alethGenesisSpecBuiltin{ + Name: "identity", + Linear: &alethGenesisSpecLinearPricing{Base: 15, Word: 3}, + }) if genesis.Config.ByzantiumBlock != nil { - spec.setPrecompile(5, &alethGenesisSpecBuiltin{Name: "modexp", - StartingBlock: (hexutil.Uint64)(genesis.Config.ByzantiumBlock.Uint64())}) - spec.setPrecompile(6, &alethGenesisSpecBuiltin{Name: "alt_bn128_G1_add", + spec.setPrecompile(5, &alethGenesisSpecBuiltin{ + Name: "modexp", StartingBlock: (hexutil.Uint64)(genesis.Config.ByzantiumBlock.Uint64()), - Linear: &alethGenesisSpecLinearPricing{Base: 500}}) - spec.setPrecompile(7, &alethGenesisSpecBuiltin{Name: "alt_bn128_G1_mul", + }) + spec.setPrecompile(6, &alethGenesisSpecBuiltin{ + Name: "alt_bn128_G1_add", StartingBlock: (hexutil.Uint64)(genesis.Config.ByzantiumBlock.Uint64()), - Linear: &alethGenesisSpecLinearPricing{Base: 40000}}) - spec.setPrecompile(8, &alethGenesisSpecBuiltin{Name: "alt_bn128_pairing_product", - StartingBlock: (hexutil.Uint64)(genesis.Config.ByzantiumBlock.Uint64())}) + Linear: &alethGenesisSpecLinearPricing{Base: 500}, + }) + spec.setPrecompile(7, &alethGenesisSpecBuiltin{ + Name: "alt_bn128_G1_mul", + StartingBlock: (hexutil.Uint64)(genesis.Config.ByzantiumBlock.Uint64()), + Linear: &alethGenesisSpecLinearPricing{Base: 40000}, + }) + spec.setPrecompile(8, &alethGenesisSpecBuiltin{ + Name: "alt_bn128_pairing_product", + StartingBlock: (hexutil.Uint64)(genesis.Config.ByzantiumBlock.Uint64()), + }) } return spec, nil } @@ -193,7 +209,6 @@ func (spec *alethGenesisSpec) setAccount(address common.Address, account core.Ge } a.Balance = (*math2.HexOrDecimal256)(account.Balance) a.Nonce = account.Nonce - } func (spec *alethGenesisSpec) setByzantium(num *big.Int) { @@ -385,8 +400,10 @@ func newParityChainSpec(network string, genesis *core.Genesis, bootnodes []strin Nonce: math2.HexOrDecimal64(account.Nonce), } } - spec.setPrecompile(1, &parityChainSpecBuiltin{Name: "ecrecover", - Pricing: &parityChainSpecPricing{Linear: &parityChainSpecLinearPricing{Base: 3000}}}) + spec.setPrecompile(1, &parityChainSpecBuiltin{ + Name: "ecrecover", + Pricing: &parityChainSpecPricing{Linear: &parityChainSpecLinearPricing{Base: 3000}}, + }) spec.setPrecompile(2, &parityChainSpecBuiltin{ Name: "sha256", Pricing: &parityChainSpecPricing{Linear: &parityChainSpecLinearPricing{Base: 60, Word: 12}}, diff --git a/cmd/swarm/access_test.go b/cmd/swarm/access_test.go index 0898d33bca..807953a25a 100644 --- a/cmd/swarm/access_test.go +++ b/cmd/swarm/access_test.go @@ -204,7 +204,7 @@ func testPassword(t *testing.T) { wrongPasswordFilename := testutil.TempFileWithContent(t, "just wr0ng") defer os.RemoveAll(wrongPasswordFilename) - //download file with 'swarm down' with wrong password + // download file with 'swarm down' with wrong password up = runSwarm(t, "--bzzapi", cluster.Nodes[0].URL, @@ -282,7 +282,7 @@ func testPK(t *testing.T) { t.Fatalf("stdout not matched") } - //get the public key from the publisher directory + // get the public key from the publisher directory publicKeyFromDataDir := runSwarm(t, "--bzzaccount", publisherAccount.Address.String(), @@ -464,7 +464,7 @@ func testACT(t *testing.T, bogusEntries int) { t.Fatalf("stdout not matched") } - //get the public key from the publisher directory + // get the public key from the publisher directory publicKeyFromDataDir := runSwarm(t, "--bzzaccount", publisherAccount.Address.String(), diff --git a/cmd/swarm/config.go b/cmd/swarm/config.go index 32cd442a03..2688c28d00 100644 --- a/cmd/swarm/config.go +++ b/cmd/swarm/config.go @@ -39,7 +39,7 @@ import ( ) var ( - //flag definition for the dumpconfig command + // flag definition for the dumpconfig command DumpConfigCommand = cli.Command{ Action: utils.MigrateFlags(dumpConfig), Name: "dumpconfig", @@ -50,14 +50,14 @@ var ( Description: `The dumpconfig command shows configuration values.`, } - //flag definition for the config file command + // flag definition for the config file command SwarmTomlConfigPathFlag = cli.StringFlag{ Name: "config", Usage: "TOML configuration file", } ) -//constants for environment variables +// constants for environment variables const ( SwarmEnvChequebookAddr = "SWARM_CHEQUEBOOK_ADDR" SwarmEnvAccount = "SWARM_ACCOUNT" @@ -103,49 +103,49 @@ var tomlSettings = toml.Config{ }, } -//before booting the swarm node, build the configuration +// before booting the swarm node, build the configuration func buildConfig(ctx *cli.Context) (config *bzzapi.Config, err error) { - //start by creating a default config + // start by creating a default config config = bzzapi.NewConfig() - //first load settings from config file (if provided) + // first load settings from config file (if provided) config, err = configFileOverride(config, ctx) if err != nil { return nil, err } - //override settings provided by environment variables + // override settings provided by environment variables config = envVarsOverride(config) - //override settings provided by command line + // override settings provided by command line config = cmdLineOverride(config, ctx) - //validate configuration parameters + // validate configuration parameters err = validateConfig(config) return } -//finally, after the configuration build phase is finished, initialize +// finally, after the configuration build phase is finished, initialize func initSwarmNode(config *bzzapi.Config, stack *node.Node, ctx *cli.Context, nodeconfig *node.Config) error { - //at this point, all vars should be set in the Config - //get the account for the provided swarm account + // at this point, all vars should be set in the Config + // get the account for the provided swarm account prvkey := getAccount(config.BzzAccount, ctx, stack) - //set the resolved config path (geth --datadir) + // set the resolved config path (geth --datadir) config.Path = expandPath(stack.InstanceDir()) - //finally, initialize the configuration + // finally, initialize the configuration err := config.Init(prvkey, nodeconfig.NodeKey()) if err != nil { return err } - //configuration phase completed here + // configuration phase completed here log.Debug("Starting Swarm with the following parameters:") - //after having created the config, print it to screen + // after having created the config, print it to screen log.Debug(printConfig(config)) return nil } -//configFileOverride overrides the current config with the config file, if a config file has been provided +// configFileOverride overrides the current config with the config file, if a config file has been provided func configFileOverride(config *bzzapi.Config, ctx *cli.Context) (*bzzapi.Config, error) { var err error - //only do something if the -config flag has been set + // only do something if the -config flag has been set if ctx.GlobalIsSet(SwarmTomlConfigPathFlag.Name) { var filepath string if filepath = ctx.GlobalString(SwarmTomlConfigPathFlag.Name); filepath == "" { @@ -158,9 +158,9 @@ func configFileOverride(config *bzzapi.Config, ctx *cli.Context) (*bzzapi.Config } defer f.Close() - //decode the TOML file into a Config struct - //note that we are decoding into the existing defaultConfig; - //if an entry is not present in the file, the default entry is kept + // decode the TOML file into a Config struct + // note that we are decoding into the existing defaultConfig; + // if an entry is not present in the file, the default entry is kept err = tomlSettings.NewDecoder(f).Decode(&config) // Add file name to errors that have a line number. if _, ok := err.(*toml.LineError); ok { @@ -272,7 +272,6 @@ func cmdLineOverride(currentConfig *bzzapi.Config, ctx *cli.Context) *bzzapi.Con } return currentConfig - } // envVarsOverride overrides the current config with whatver is provided in environment variables @@ -408,7 +407,7 @@ func dumpConfig(ctx *cli.Context) error { return nil } -//validate configuration parameters +// validate configuration parameters func validateConfig(cfg *bzzapi.Config) (err error) { for _, ensAPI := range cfg.EnsAPIs { if ensAPI != "" { @@ -420,7 +419,7 @@ func validateConfig(cfg *bzzapi.Config) (err error) { return nil } -//validate EnsAPIs configuration parameter +// validate EnsAPIs configuration parameter func validateEnsAPIs(s string) (err error) { // missing contract address if strings.HasPrefix(s, "@") { @@ -441,7 +440,7 @@ func validateEnsAPIs(s string) (err error) { return nil } -//print a Config as string +// print a Config as string func printConfig(config *bzzapi.Config) string { out, err := tomlSettings.Marshal(&config) if err != nil { diff --git a/cmd/swarm/config_test.go b/cmd/swarm/config_test.go index 869edd0f70..078f246637 100644 --- a/cmd/swarm/config_test.go +++ b/cmd/swarm/config_test.go @@ -142,17 +142,16 @@ func TestConfigCmdLineOverrides(t *testing.T) { } func TestConfigFileOverrides(t *testing.T) { - // assign ports httpPort, err := assignTCPPort() if err != nil { t.Fatal(err) } - //create a config file - //first, create a default conf + // create a config file + // first, create a default conf defaultConf := api.NewConfig() - //change some values in order to test if they have been loaded + // change some values in order to test if they have been loaded defaultConf.SyncEnabled = false defaultConf.DeliverySkipCheck = true defaultConf.NetworkID = 54 @@ -160,18 +159,18 @@ func TestConfigFileOverrides(t *testing.T) { defaultConf.DbCapacity = 9000000 defaultConf.HiveParams.KeepAliveInterval = 6000000000 defaultConf.Swap.Params.Strategy.AutoCashInterval = 600 * time.Second - //defaultConf.SyncParams.KeyBufferSize = 512 - //create a TOML string + // defaultConf.SyncParams.KeyBufferSize = 512 + // create a TOML string out, err := tomlSettings.Marshal(&defaultConf) if err != nil { t.Fatalf("Error creating TOML file in TestFileOverride: %v", err) } - //create file + // create file f, err := ioutil.TempFile("", "testconfig.toml") if err != nil { t.Fatalf("Error writing TOML file in TestFileOverride: %v", err) } - //write file + // write file _, err = f.WriteString(string(out)) if err != nil { t.Fatalf("Error writing TOML file in TestFileOverride: %v", err) @@ -280,9 +279,9 @@ func TestConfigEnvVars(t *testing.T) { "--ipcpath", conf.IPCPath, } - //node.Cmd = runSwarm(t,flags...) - //node.Cmd.cmd.Env = envVars - //the above assignment does not work, so we need a custom Cmd here in order to pass envVars: + // node.Cmd = runSwarm(t,flags...) + // node.Cmd.cmd.Env = envVars + // the above assignment does not work, so we need a custom Cmd here in order to pass envVars: cmd := &exec.Cmd{ Path: reexec.Self(), Args: append([]string{"swarm-test"}, flags...), @@ -290,11 +289,11 @@ func TestConfigEnvVars(t *testing.T) { Stdout: os.Stdout, } cmd.Env = envVars - //stdout, err := cmd.StdoutPipe() - //if err != nil { + // stdout, err := cmd.StdoutPipe() + // if err != nil { // t.Fatal(err) //} - //stdout = bufio.NewReader(stdout) + // stdout = bufio.NewReader(stdout) var stdin io.WriteCloser if stdin, err = cmd.StdinPipe(); err != nil { t.Fatal(err) @@ -303,7 +302,7 @@ func TestConfigEnvVars(t *testing.T) { t.Fatal(err) } - //cmd.InputLine(testPassphrase) + // cmd.InputLine(testPassphrase) io.WriteString(stdin, testPassphrase+"\n") defer func() { if t.Failed() { @@ -354,37 +353,36 @@ func TestConfigEnvVars(t *testing.T) { } func TestConfigCmdLineOverridesFile(t *testing.T) { - // assign ports httpPort, err := assignTCPPort() if err != nil { t.Fatal(err) } - //create a config file - //first, create a default conf + // create a config file + // first, create a default conf defaultConf := api.NewConfig() - //change some values in order to test if they have been loaded + // change some values in order to test if they have been loaded defaultConf.SyncEnabled = true defaultConf.NetworkID = 54 defaultConf.Port = "8588" defaultConf.DbCapacity = 9000000 defaultConf.HiveParams.KeepAliveInterval = 6000000000 defaultConf.Swap.Params.Strategy.AutoCashInterval = 600 * time.Second - //defaultConf.SyncParams.KeyBufferSize = 512 - //create a TOML file + // defaultConf.SyncParams.KeyBufferSize = 512 + // create a TOML file out, err := tomlSettings.Marshal(&defaultConf) if err != nil { t.Fatalf("Error creating TOML file in TestFileOverride: %v", err) } - //write file + // write file fname := "testconfig.toml" f, err := ioutil.TempFile("", fname) if err != nil { t.Fatalf("Error writing TOML file in TestFileOverride: %v", err) } defer os.Remove(fname) - //write file + // write file _, err = f.WriteString(string(out)) if err != nil { t.Fatalf("Error writing TOML file in TestFileOverride: %v", err) diff --git a/cmd/swarm/feeds.go b/cmd/swarm/feeds.go index 6cd971a92c..af519b6906 100644 --- a/cmd/swarm/feeds.go +++ b/cmd/swarm/feeds.go @@ -136,7 +136,6 @@ func feedCreateManifest(ctx *cli.Context) { return } fmt.Println(manifestAddress) // output manifest address to the user in a single line (useful for other commands to pick up) - } func feedUpdate(ctx *cli.Context) { @@ -234,5 +233,4 @@ func feedGetUser(ctx *cli.Context) common.Address { utils.Fatalf("Cannot read private key. Must specify --user or --bzzaccount") } return crypto.PubkeyToAddress(pk.PublicKey) - } diff --git a/cmd/swarm/feeds_test.go b/cmd/swarm/feeds_test.go index 4c40f62a82..72e9a97357 100644 --- a/cmd/swarm/feeds_test.go +++ b/cmd/swarm/feeds_test.go @@ -65,7 +65,8 @@ func TestCLIFeedUpdate(t *testing.T) { "feed", "update", "--topic", topic.Hex(), "--name", name, - hexData} + hexData, + } // create an update and expect an exit without errors log.Info("updating a feed with 'swarm feed update'") @@ -183,7 +184,8 @@ func TestCLIFeedUpdate(t *testing.T) { "--bzzaccount", pkFileName, "feed", "update", "--manifest", manifestAddress, - hexData} + hexData, + } // create an update and expect an error given there is a user mismatch log.Info("updating a feed with 'swarm feed update'") diff --git a/cmd/swarm/fs.go b/cmd/swarm/fs.go index 7f156523ba..392f25c84f 100644 --- a/cmd/swarm/fs.go +++ b/cmd/swarm/fs.go @@ -110,7 +110,7 @@ func unmount(cliContext *cli.Context) { if err != nil { utils.Fatalf("encountered an error calling the RPC endpoint while unmounting: %v", err) } - fmt.Printf("%s\n", mf.LatestManifest) //print the latest manifest hash for user reference + fmt.Printf("%s\n", mf.LatestManifest) // print the latest manifest hash for user reference } func listMounts(cliContext *cli.Context) { diff --git a/cmd/swarm/fs_test.go b/cmd/swarm/fs_test.go index 5f58d6c0d8..4025c01bb5 100644 --- a/cmd/swarm/fs_test.go +++ b/cmd/swarm/fs_test.go @@ -137,7 +137,7 @@ func TestCLISwarmFs(t *testing.T) { } log.Debug("swarmfs cli test: asserting no files in mount point") - //check that there's nothing in the mount folder + // check that there's nothing in the mount folder filesInDir, err := ioutil.ReadDir(mountPoint) if err != nil { t.Fatalf("had an error reading the directory: %v", err) @@ -156,7 +156,7 @@ func TestCLISwarmFs(t *testing.T) { log.Debug("swarmfs cli test: remounting at second mount point", "ipc path", filepath.Join(handlingNode.Dir, handlingNode.IpcPath)) - //remount, check files + // remount, check files newMount := runSwarm(t, []string{ fmt.Sprintf("--%s", utils.IPCPathFlag.Name), filepath.Join(handlingNode.Dir, handlingNode.IpcPath), "fs", @@ -222,7 +222,8 @@ func doUploadEmptyDir(t *testing.T, node *testNode) string { "--bzzapi", node.URL, "--recursive", "up", - tmpDir} + tmpDir, + } log.Info("swarmfs cli test: uploading dir with 'swarm up'") up := runSwarm(t, flags...) diff --git a/cmd/swarm/hash.go b/cmd/swarm/hash.go index 2df02c0ed7..601b92036b 100644 --- a/cmd/swarm/hash.go +++ b/cmd/swarm/hash.go @@ -63,7 +63,8 @@ var hashCommand = cli.Command{ }, }, }, - }} + }, +} func hash(ctx *cli.Context) { args := ctx.Args() @@ -85,6 +86,7 @@ func hash(ctx *cli.Context) { fmt.Printf("%v\n", addr) } } + func ensNodeHash(ctx *cli.Context) { args := ctx.Args() if len(args) < 1 { @@ -97,6 +99,7 @@ func ensNodeHash(ctx *cli.Context) { stringHex := hex.EncodeToString(hash[:]) fmt.Println(stringHex) } + func encodeEipHash(ctx *cli.Context) { args := ctx.Args() if len(args) < 1 { diff --git a/cmd/swarm/main.go b/cmd/swarm/main.go index a4041eb3d1..dc99e2d738 100644 --- a/cmd/swarm/main.go +++ b/cmd/swarm/main.go @@ -74,7 +74,7 @@ OPTIONS: // e.g.: go install -ldflags "-X main.gitCommit=ed1312d01b19e04ef578946226e5d8069d5dfd5a" ./cmd/swarm var gitCommit string -//declare a few constant error messages, useful for later error check comparisons in test +// declare a few constant error messages, useful for later error check comparisons in test var ( SwarmErrNoBZZAccount = "bzzaccount option is required but not set; check your config file, command line or environment variables" SwarmErrSwapSetNoAPI = "SWAP is enabled but --swap-api is not set" @@ -262,8 +262,8 @@ func version(ctx *cli.Context) error { } func bzzd(ctx *cli.Context) error { - //build a valid bzzapi.Config from all available sources: - //default config, file config, command line and env vars + // build a valid bzzapi.Config from all available sources: + // default config, file config, command line and env vars bzzconfig, err := buildConfig(ctx) if err != nil { @@ -272,22 +272,22 @@ func bzzd(ctx *cli.Context) error { cfg := defaultNodeConfig - //pss operates on ws + // pss operates on ws cfg.WSModules = append(cfg.WSModules, "pss") - //geth only supports --datadir via command line - //in order to be consistent within swarm, if we pass --datadir via environment variable - //or via config file, we get the same directory for geth and swarm + // geth only supports --datadir via command line + // in order to be consistent within swarm, if we pass --datadir via environment variable + // or via config file, we get the same directory for geth and swarm if _, err := os.Stat(bzzconfig.Path); err == nil { cfg.DataDir = bzzconfig.Path } - //optionally set the bootnodes before configuring the node + // optionally set the bootnodes before configuring the node setSwarmBootstrapNodes(ctx, &cfg) - //setup the ethereum node + // setup the ethereum node utils.SetNodeConfig(ctx, &cfg) - //disable dynamic dialing from p2p/discovery + // disable dynamic dialing from p2p/discovery cfg.P2P.NoDial = true stack, err := node.New(&cfg) @@ -296,15 +296,15 @@ func bzzd(ctx *cli.Context) error { } defer stack.Close() - //a few steps need to be done after the config phase is completed, - //due to overriding behavior + // a few steps need to be done after the config phase is completed, + // due to overriding behavior err = initSwarmNode(bzzconfig, stack, ctx, &cfg) if err != nil { return err } - //register BZZ as node.Service in the ethereum node + // register BZZ as node.Service in the ethereum node registerBzzService(bzzconfig, stack) - //start the node + // start the node utils.StartNode(stack) go func() { @@ -330,7 +330,7 @@ func bzzd(ctx *cli.Context) error { } func registerBzzService(bzzconfig *bzzapi.Config, stack *node.Node) { - //define the swarm service boot function + // define the swarm service boot function boot := func(_ *node.ServiceContext) (node.Service, error) { var nodeStore *mock.NodeStore if bzzconfig.GlobalStoreAPI != "" { @@ -345,14 +345,14 @@ func registerBzzService(bzzconfig *bzzapi.Config, stack *node.Node) { } return swarm.NewSwarm(bzzconfig, nodeStore) } - //register within the ethereum node + // register within the ethereum node if err := stack.Register(boot); err != nil { utils.Fatalf("Failed to register the Swarm service: %v", err) } } func getAccount(bzzaccount string, ctx *cli.Context, stack *node.Node) *ecdsa.PrivateKey { - //an account is mandatory + // an account is mandatory if bzzaccount == "" { utils.Fatalf(SwarmErrNoBZZAccount) } @@ -471,5 +471,4 @@ func setSwarmBootstrapNodes(ctx *cli.Context, cfg *node.Config) { } cfg.P2P.BootstrapNodes = append(cfg.P2P.BootstrapNodes, node) } - } diff --git a/cmd/swarm/run_test.go b/cmd/swarm/run_test.go index 9681c8990a..7809584388 100644 --- a/cmd/swarm/run_test.go +++ b/cmd/swarm/run_test.go @@ -71,6 +71,7 @@ func initCluster(t *testing.T) { func serverFunc(api *api.API) swarmhttp.TestServer { return swarmhttp.NewServer(api, "") } + func TestMain(m *testing.M) { // check if we have been reexec'd if reexec.Init() { @@ -322,7 +323,6 @@ func existingTestNode(t *testing.T, dir string, bzzaccount string) *testNode { } func newTestNode(t *testing.T, dir string) *testNode { - conf, account := getTestAccount(t, dir) ks := keystore.NewKeyStore(path.Join(dir, "keystore"), 1<<18, 1) diff --git a/cmd/swarm/swarm-smoke/feed_upload_and_sync.go b/cmd/swarm/swarm-smoke/feed_upload_and_sync.go index 6b3fed0c7e..872e8027dd 100644 --- a/cmd/swarm/swarm-smoke/feed_upload_and_sync.go +++ b/cmd/swarm/swarm-smoke/feed_upload_and_sync.go @@ -22,9 +22,7 @@ import ( cli "gopkg.in/urfave/cli.v1" ) -const ( - feedRandomDataLength = 8 -) +const feedRandomDataLength = 8 func feedUploadAndSyncCmd(ctx *cli.Context, tuid string) error { errc := make(chan error) @@ -265,7 +263,6 @@ func feedUploadAndSync(c *cli.Context, tuid string) error { time.Sleep(3 * time.Second) for _, host := range hosts { - // manifest retrieve, topic only for _, url := range []string{manifestWithTopic, manifestWithSubTopic, manifestWithMergedTopic} { wg.Add(1) @@ -282,7 +279,6 @@ func feedUploadAndSync(c *cli.Context, tuid string) error { } }(url, httpEndpoint(host), ruid) } - } wg.Wait() log.Info("all endpoints synced random file successfully") diff --git a/cmd/swarm/swarm-smoke/main.go b/cmd/swarm/swarm-smoke/main.go index 860fbcc1dd..6c6b3ed80f 100644 --- a/cmd/swarm/swarm-smoke/main.go +++ b/cmd/swarm/swarm-smoke/main.go @@ -32,9 +32,7 @@ import ( cli "gopkg.in/urfave/cli.v1" ) -var ( - gitCommit string // Git SHA1 commit hash of the release (set via linker flags) -) +var gitCommit string // Git SHA1 commit hash of the release (set via linker flags) var ( allhosts string @@ -51,7 +49,6 @@ var ( ) func main() { - app := cli.NewApp() app.Name = "smoke-test" app.Usage = "" diff --git a/cmd/swarm/swarm-smoke/sliding_window.go b/cmd/swarm/swarm-smoke/sliding_window.go index d589124bd1..9086543e21 100644 --- a/cmd/swarm/swarm-smoke/sliding_window.go +++ b/cmd/swarm/swarm-smoke/sliding_window.go @@ -50,7 +50,7 @@ func slidingWindowCmd(ctx *cli.Context, tuid string) error { } func slidingWindow(ctx *cli.Context, tuid string) error { - var hashes []uploadResult //swarm hashes of the uploads + var hashes []uploadResult // swarm hashes of the uploads nodes := len(hosts) log.Info("sliding window test started", "tuid", tuid, "nodes", nodes, "filesize(kb)", filesize, "timeout", timeout) uploadedBytes := 0 diff --git a/cmd/swarm/swarm-smoke/util.go b/cmd/swarm/swarm-smoke/util.go index 87abb44b0b..660612c01e 100644 --- a/cmd/swarm/swarm-smoke/util.go +++ b/cmd/swarm/swarm-smoke/util.go @@ -107,7 +107,7 @@ func fetchFeed(topic string, user string, endpoint string, original []byte, ruid req = req.WithContext(httptrace.WithClientTrace(ctx, trace)) transport := http.DefaultTransport - //transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + // transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} tn = time.Now() res, err := transport.RoundTrip(req) @@ -162,7 +162,7 @@ func fetch(hash string, endpoint string, original []byte, ruid string, tuid stri req = req.WithContext(httptrace.WithClientTrace(ctx, trace)) transport := http.DefaultTransport - //transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + // transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} tn = time.Now() res, err := transport.RoundTrip(req) diff --git a/cmd/swarm/swarm-snapshot/create_test.go b/cmd/swarm/swarm-snapshot/create_test.go index b2e30c2016..2f071f09d8 100644 --- a/cmd/swarm/swarm-snapshot/create_test.go +++ b/cmd/swarm/swarm-snapshot/create_test.go @@ -137,7 +137,6 @@ func TestSnapshotCreate(t *testing.T) { t.Errorf("got services %v for node %v, want %v", gotServices, i, wantServices) } } - }) } } diff --git a/cmd/swarm/upload_test.go b/cmd/swarm/upload_test.go index 616486e37c..ebdd54c1b3 100644 --- a/cmd/swarm/upload_test.go +++ b/cmd/swarm/upload_test.go @@ -93,14 +93,16 @@ func testDefault(toEncrypt bool, t *testing.T) { flags := []string{ "--bzzapi", cluster.Nodes[0].URL, "up", - tmpFileName} + tmpFileName, + } if toEncrypt { hashRegexp = `[a-f\d]{128}` flags = []string{ "--bzzapi", cluster.Nodes[0].URL, "up", "--encrypt", - tmpFileName} + tmpFileName, + } } // upload the file with 'swarm up' and expect a hash log.Info(fmt.Sprintf("uploading file with 'swarm up'")) @@ -131,7 +133,7 @@ func testDefault(toEncrypt bool, t *testing.T) { t.Fatalf("expected HTTP body %q, got %q", data, reply) } log.Debug("verifying uploaded file using `swarm down`") - //try to get the content with `swarm down` + // try to get the content with `swarm down` tmpDownload, err := ioutil.TempDir("", "swarm-test") tmpDownload = path.Join(tmpDownload, "tmpfile.tmp") if err != nil { @@ -207,7 +209,8 @@ func testRecursive(toEncrypt bool, t *testing.T) { "--bzzapi", cluster.Nodes[0].URL, "--recursive", "up", - tmpUploadDir} + tmpUploadDir, + } if toEncrypt { hashRegexp = `[a-f\d]{128}` flags = []string{ @@ -215,7 +218,8 @@ func testRecursive(toEncrypt bool, t *testing.T) { "--recursive", "up", "--encrypt", - tmpUploadDir} + tmpUploadDir, + } } // upload the file with 'swarm up' and expect a hash log.Info(fmt.Sprintf("uploading file with 'swarm up'")) @@ -228,7 +232,7 @@ func testRecursive(toEncrypt bool, t *testing.T) { // get the file from the HTTP API of each node for _, node := range cluster.Nodes { log.Info("getting file from node", "node", node.Name) - //try to get the content with `swarm down` + // try to get the content with `swarm down` tmpDownload, err := ioutil.TempDir("", "swarm-test") if err != nil { t.Fatal(err) diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 74a8c7f394..57349f5c05 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -39,9 +39,7 @@ import ( "github.com/ethereum/go-ethereum/rlp" ) -const ( - importBatchSize = 2500 -) +const importBatchSize = 2500 // Fatalf formats a message to standard error and exits the program. // The message is also printed to standard output if standard error diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index f5f4cde5b4..36f8bbce1f 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -60,8 +60,7 @@ import ( cli "gopkg.in/urfave/cli.v1" ) -var ( - CommandHelpTemplate = `{{.cmd.Name}}{{if .cmd.Subcommands}} command{{end}}{{if .cmd.Flags}} [command options]{{end}} [arguments...] +var CommandHelpTemplate = `{{.cmd.Name}}{{if .cmd.Subcommands}} command{{end}}{{if .cmd.Flags}} [command options]{{end}} [arguments...] {{if .cmd.Description}}{{.cmd.Description}} {{end}}{{if .cmd.Subcommands}} SUBCOMMANDS: @@ -71,7 +70,6 @@ SUBCOMMANDS: {{range $categorized.Flags}}{{"\t"}}{{.}} {{end}} {{end}}{{end}}` -) func init() { cli.AppHelpTemplate = `{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...] @@ -95,7 +93,7 @@ func NewApp(gitCommit, usage string) *cli.App { app := cli.NewApp() app.Name = filepath.Base(os.Args[0]) app.Author = "" - //app.Authors = nil + // app.Authors = nil app.Email = "" app.Version = params.VersionWithMeta if len(gitCommit) >= 8 { diff --git a/cmd/wnode/main.go b/cmd/wnode/main.go index 97e5852013..40dfc6419e 100644 --- a/cmd/wnode/main.go +++ b/cmd/wnode/main.go @@ -661,7 +661,7 @@ func writeMessageToFile(dir string, msg *whisper.ReceivedMessage, show bool) { } // this is a sample code; uncomment if you don't want to save your own messages. - //if whisper.IsPubKeyEqual(msg.Src, &asymKey.PublicKey) { + // if whisper.IsPubKeyEqual(msg.Src, &asymKey.PublicKey) { // fmt.Printf("\n%s <%x>: message from myself received, not saved: '%s'\n", timestamp, address, name) // return //} diff --git a/common/compiler/solidity_test.go b/common/compiler/solidity_test.go index 6be2bda52c..6eb3a7b2b7 100644 --- a/common/compiler/solidity_test.go +++ b/common/compiler/solidity_test.go @@ -21,8 +21,7 @@ import ( "testing" ) -const ( - testSource = ` +const testSource = ` pragma solidity >0.0.0; contract test { /// @notice Will multiply ` + "`a`" + ` by 7. @@ -31,7 +30,6 @@ contract test { } } ` -) func skipWithoutSolc(t *testing.T) { if _, err := exec.LookPath("solc"); err != nil { diff --git a/common/math/big_test.go b/common/math/big_test.go index be9810dc8c..abf0e86989 100644 --- a/common/math/big_test.go +++ b/common/math/big_test.go @@ -171,7 +171,6 @@ func BenchmarkByteAt(b *testing.B) { } func BenchmarkByteAtOld(b *testing.B) { - bigint := MustParseBig256("0x18F8F8F1000111000110011100222004330052300000000000000000FEFCF3CC") for i := 0; i < b.N; i++ { PaddedBigBytes(bigint, 32) @@ -237,6 +236,7 @@ func TestBigEndianByteAt(t *testing.T) { } } + func TestLittleEndianByteAt(t *testing.T) { tests := []struct { x string diff --git a/common/math/integer_test.go b/common/math/integer_test.go index b31c7c26c2..737c792973 100644 --- a/common/math/integer_test.go +++ b/common/math/integer_test.go @@ -16,9 +16,7 @@ package math -import ( - "testing" -) +import "testing" type operation byte diff --git a/common/prque/prque.go b/common/prque/prque.go index 9fd31a2e5d..1182e5fe3c 100755 --- a/common/prque/prque.go +++ b/common/prque/prque.go @@ -2,9 +2,7 @@ package prque -import ( - "container/heap" -) +import "container/heap" // Priority queue data structure. type Prque struct { diff --git a/common/size.go b/common/size.go index 6381499a48..3bfbc1acc3 100644 --- a/common/size.go +++ b/common/size.go @@ -16,9 +16,7 @@ package common -import ( - "fmt" -) +import "fmt" // StorageSize is a wrapper around a float value that supports user friendly // formatting. diff --git a/common/size_test.go b/common/size_test.go index 0938d483c4..e485e27a3e 100644 --- a/common/size_test.go +++ b/common/size_test.go @@ -16,9 +16,7 @@ package common -import ( - "testing" -) +import "testing" func TestStorageSizeString(t *testing.T) { tests := []struct { diff --git a/common/types_test.go b/common/types_test.go index fffd673c6e..5d8b9f7362 100644 --- a/common/types_test.go +++ b/common/types_test.go @@ -153,7 +153,6 @@ func BenchmarkAddressHex(b *testing.B) { } func TestMixedcaseAccount_Address(t *testing.T) { - // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md // Note: 0X{checksum_addr} is not valid according to spec above @@ -176,7 +175,7 @@ func TestMixedcaseAccount_Address(t *testing.T) { } } - //These should throw exceptions: + // These should throw exceptions: var r2 []MixedcaseAddress for _, r := range []string{ `["0x11111111111111111111122222222222233333"]`, // Too short @@ -185,14 +184,12 @@ func TestMixedcaseAccount_Address(t *testing.T) { `["0x111111111111111111111222222222222333332344"]`, // Too long `["1111111111111111111112222222222223333323"]`, // Missing 0x `["x1111111111111111111112222222222223333323"]`, // Missing 0 - `["0xG111111111111111111112222222222223333323"]`, //Non-hex + `["0xG111111111111111111112222222222223333323"]`, // Non-hex } { if err := json.Unmarshal([]byte(r), &r2); err == nil { t.Errorf("Expected failure, input %v", r) } - } - } func TestHash_Scan(t *testing.T) { diff --git a/consensus/ethash/algorithm.go b/consensus/ethash/algorithm.go index d6c871092e..bc75bc33a2 100644 --- a/consensus/ethash/algorithm.go +++ b/consensus/ethash/algorithm.go @@ -814,7 +814,8 @@ var datasetSizes = [maxEpoch]uint64{ 18102613376, 18111004544, 18119388544, 18127781248, 18136170368, 18144558976, 18152947328, 18161336192, 18169724288, 18178108544, 18186498944, 18194886784, 18203275648, 18211666048, 18220048768, - 18228444544, 18236833408, 18245220736} + 18228444544, 18236833408, 18245220736, +} // cacheSizes is a lookup table for the ethash verification cache size for the // first 2048 epochs (i.e. 61440000 blocks). @@ -1145,4 +1146,5 @@ var cacheSizes = [maxEpoch]uint64{ 282590272, 282720832, 282853184, 282983744, 283115072, 283246144, 283377344, 283508416, 283639744, 283770304, 283901504, 284032576, 284163136, 284294848, 284426176, 284556992, 284687296, 284819264, - 284950208, 285081536} + 284950208, 285081536, +} diff --git a/consensus/ethash/sealer.go b/consensus/ethash/sealer.go index 3a0919ca99..b4d3b20d06 100644 --- a/consensus/ethash/sealer.go +++ b/consensus/ethash/sealer.go @@ -36,10 +36,8 @@ import ( "github.com/ethereum/go-ethereum/log" ) -const ( - // staleThreshold is the maximum depth of the acceptable stale but valid ethash solution. - staleThreshold = 7 -) +// staleThreshold is the maximum depth of the acceptable stale but valid ethash solution. +const staleThreshold = 7 var ( errNoMiningWork = errors.New("no mining work available yet") diff --git a/console/console.go b/console/console.go index 5326ed2c87..0bc430319b 100644 --- a/console/console.go +++ b/console/console.go @@ -157,7 +157,7 @@ func (c *Console) init(preload []string) error { return fmt.Errorf("namespace flattening: %v", err) } // Initialize the global name register (disabled for now) - //c.jsre.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `); registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`) + // c.jsre.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `); registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`) // If the console is in interactive mode, instrument password related methods to query the user if c.prompter != nil { diff --git a/console/console_test.go b/console/console_test.go index 55d799725a..bb7ef59659 100644 --- a/console/console_test.go +++ b/console/console_test.go @@ -63,6 +63,7 @@ func (p *hookedPrompter) PromptInput(prompt string) (string, error) { func (p *hookedPrompter) PromptPassword(prompt string) (string, error) { return "", errors.New("not implemented") } + func (p *hookedPrompter) PromptConfirm(prompt string) (bool, error) { return false, errors.New("not implemented") } diff --git a/contracts/chequebook/cheque.go b/contracts/chequebook/cheque.go index 32e8406768..c2a98b9cc2 100644 --- a/contracts/chequebook/cheque.go +++ b/contracts/chequebook/cheque.go @@ -55,10 +55,8 @@ import ( // * depositing ether to the chequebook // * watching incoming ether -var ( - gasToCash = uint64(2000000) // gas cost of a cash transaction using chequebook - // gasToDeploy = uint64(3000000) -) +var gasToCash = uint64(2000000) // gas cost of a cash transaction using chequebook +// gasToDeploy = uint64(3000000) // Backend wraps all methods required for chequebook operation. type Backend interface { @@ -100,7 +98,7 @@ type Chequebook struct { // persisted fields balance *big.Int // not synced with blockchain contractAddr common.Address // contract address - sent map[common.Address]*big.Int //tallies for beneficiaries + sent map[common.Address]*big.Int // tallies for beneficiaries txhash string // tx hash of last deposit tx threshold *big.Int // threshold that triggers autodeposit if not nil diff --git a/contracts/chequebook/cheque_test.go b/contracts/chequebook/cheque_test.go index 4bd2e176b1..317fe6cfd1 100644 --- a/contracts/chequebook/cheque_test.go +++ b/contracts/chequebook/cheque_test.go @@ -105,7 +105,6 @@ func TestIssueAndReceive(t *testing.T) { if received.Cmp(big.NewInt(43)) != 0 { t.Errorf("expected: %v, got %v", "43", received) } - } func TestCheckbookFile(t *testing.T) { @@ -216,7 +215,6 @@ func TestVerifyErrors(t *testing.T) { if err == nil { t.Fatalf("expected incorrect amount error, got none and value %v", received) } - } func TestDeposit(t *testing.T) { @@ -355,7 +353,6 @@ func TestDeposit(t *testing.T) { if chbook.Balance().Cmp(exp) != 0 { t.Fatalf("expected balance %v, got %v", exp, chbook.Balance()) } - } func TestCash(t *testing.T) { @@ -483,5 +480,4 @@ func TestCash(t *testing.T) { t.Fatalf("expected no error, got %v", err) } backend.Commit() - } diff --git a/contracts/chequebook/contract/chequebook.go b/contracts/chequebook/contract/chequebook.go index 3129b811c6..190113f648 100644 --- a/contracts/chequebook/contract/chequebook.go +++ b/contracts/chequebook/contract/chequebook.go @@ -180,9 +180,9 @@ func (_Chequebook *ChequebookTransactorRaw) Transact(opts *bind.TransactOpts, me // // Solidity: function sent( address) constant returns(uint256) func (_Chequebook *ChequebookCaller) Sent(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var ( - ret0 = new(*big.Int) - ) + + var ret0 = new(*big.Int) + out := ret0 err := _Chequebook.contract.Call(opts, out, "sent", arg0) return *ret0, err @@ -321,7 +321,6 @@ type ChequebookOverdraft struct { // // Solidity: event Overdraft(deadbeat address) func (_Chequebook *ChequebookFilterer) FilterOverdraft(opts *bind.FilterOpts) (*ChequebookOverdraftIterator, error) { - logs, sub, err := _Chequebook.contract.FilterLogs(opts, "Overdraft") if err != nil { return nil, err @@ -333,7 +332,6 @@ func (_Chequebook *ChequebookFilterer) FilterOverdraft(opts *bind.FilterOpts) (* // // Solidity: event Overdraft(deadbeat address) func (_Chequebook *ChequebookFilterer) WatchOverdraft(opts *bind.WatchOpts, sink chan<- *ChequebookOverdraft) (event.Subscription, error) { - logs, sub, err := _Chequebook.contract.WatchLogs(opts, "Overdraft") if err != nil { return nil, err diff --git a/contracts/ens/cid.go b/contracts/ens/cid.go index 673e8203e4..eecae1bda1 100644 --- a/contracts/ens/cid.go +++ b/contracts/ens/cid.go @@ -80,7 +80,7 @@ func extractContentHash(buf []byte) (common.Hash, error) { return common.Hash{}, errors.New("unknown storage system") } - //todo: for the time being we implement loose enforcement for the EIP rules until ENS manager is updated + // todo: for the time being we implement loose enforcement for the EIP rules until ENS manager is updated /*if contentType != swarmTypecode { return common.Hash{}, errors.New("unknown content type") } @@ -103,11 +103,11 @@ func extractContentHash(buf []byte) (common.Hash, error) { func EncodeSwarmHash(hash common.Hash) ([]byte, error) { var cidBytes []byte var headerBytes = []byte{ - nsSwarm, //swarm namespace + nsSwarm, // swarm namespace cidv1, // CIDv1 swarmTypecode, // swarm hash swarmHashtype, // keccak256 hash - hashLength, //hash length. 32 bytes + hashLength, // hash length. 32 bytes } varintbuf := make([]byte, binary.MaxVarintLen64) diff --git a/contracts/ens/cid_test.go b/contracts/ens/cid_test.go index 7d0e67851a..eeb94b91d6 100644 --- a/contracts/ens/cid_test.go +++ b/contracts/ens/cid_test.go @@ -64,8 +64,8 @@ func TestEIPSpecCidDecode(t *testing.T) { if !bytes.Equal(hashBytes, decodedHashBytes) { t.Fatal("should be equal") } - } + func TestManualCidDecode(t *testing.T) { // call cid encode method with hash. expect byte slice returned, compare according to spec diff --git a/contracts/ens/contract/ens.go b/contracts/ens/contract/ens.go index 7c0aed342e..41462d021f 100644 --- a/contracts/ens/contract/ens.go +++ b/contracts/ens/contract/ens.go @@ -192,9 +192,9 @@ func (_ENS *ENSTransactorRaw) Transact(opts *bind.TransactOpts, method string, p // // Solidity: function owner(bytes32 node) constant returns(address) func (_ENS *ENSCaller) Owner(opts *bind.CallOpts, node [32]byte) (common.Address, error) { - var ( - ret0 = new(common.Address) - ) + + var ret0 = new(common.Address) + out := ret0 err := _ENS.contract.Call(opts, out, "owner", node) return *ret0, err @@ -218,9 +218,9 @@ func (_ENS *ENSCallerSession) Owner(node [32]byte) (common.Address, error) { // // Solidity: function resolver(bytes32 node) constant returns(address) func (_ENS *ENSCaller) Resolver(opts *bind.CallOpts, node [32]byte) (common.Address, error) { - var ( - ret0 = new(common.Address) - ) + + var ret0 = new(common.Address) + out := ret0 err := _ENS.contract.Call(opts, out, "resolver", node) return *ret0, err @@ -244,9 +244,9 @@ func (_ENS *ENSCallerSession) Resolver(node [32]byte) (common.Address, error) { // // Solidity: function ttl(bytes32 node) constant returns(uint64) func (_ENS *ENSCaller) Ttl(opts *bind.CallOpts, node [32]byte) (uint64, error) { - var ( - ret0 = new(uint64) - ) + + var ret0 = new(uint64) + out := ret0 err := _ENS.contract.Call(opts, out, "ttl", node) return *ret0, err @@ -429,7 +429,6 @@ type ENSNewOwner struct { // // Solidity: event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner) func (_ENS *ENSFilterer) FilterNewOwner(opts *bind.FilterOpts, node [][32]byte, label [][32]byte) (*ENSNewOwnerIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -450,7 +449,6 @@ func (_ENS *ENSFilterer) FilterNewOwner(opts *bind.FilterOpts, node [][32]byte, // // Solidity: event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner) func (_ENS *ENSFilterer) WatchNewOwner(opts *bind.WatchOpts, sink chan<- *ENSNewOwner, node [][32]byte, label [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -570,7 +568,6 @@ type ENSNewResolver struct { // // Solidity: event NewResolver(bytes32 indexed node, address resolver) func (_ENS *ENSFilterer) FilterNewResolver(opts *bind.FilterOpts, node [][32]byte) (*ENSNewResolverIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -587,7 +584,6 @@ func (_ENS *ENSFilterer) FilterNewResolver(opts *bind.FilterOpts, node [][32]byt // // Solidity: event NewResolver(bytes32 indexed node, address resolver) func (_ENS *ENSFilterer) WatchNewResolver(opts *bind.WatchOpts, sink chan<- *ENSNewResolver, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -703,7 +699,6 @@ type ENSNewTTL struct { // // Solidity: event NewTTL(bytes32 indexed node, uint64 ttl) func (_ENS *ENSFilterer) FilterNewTTL(opts *bind.FilterOpts, node [][32]byte) (*ENSNewTTLIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -720,7 +715,6 @@ func (_ENS *ENSFilterer) FilterNewTTL(opts *bind.FilterOpts, node [][32]byte) (* // // Solidity: event NewTTL(bytes32 indexed node, uint64 ttl) func (_ENS *ENSFilterer) WatchNewTTL(opts *bind.WatchOpts, sink chan<- *ENSNewTTL, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -836,7 +830,6 @@ type ENSTransfer struct { // // Solidity: event Transfer(bytes32 indexed node, address owner) func (_ENS *ENSFilterer) FilterTransfer(opts *bind.FilterOpts, node [][32]byte) (*ENSTransferIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -853,7 +846,6 @@ func (_ENS *ENSFilterer) FilterTransfer(opts *bind.FilterOpts, node [][32]byte) // // Solidity: event Transfer(bytes32 indexed node, address owner) func (_ENS *ENSFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *ENSTransfer, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) diff --git a/contracts/ens/contract/ensregistry.go b/contracts/ens/contract/ensregistry.go index ca89a87bc2..f6a266d86b 100644 --- a/contracts/ens/contract/ensregistry.go +++ b/contracts/ens/contract/ensregistry.go @@ -192,9 +192,9 @@ func (_ENSRegistry *ENSRegistryTransactorRaw) Transact(opts *bind.TransactOpts, // // Solidity: function owner(bytes32 node) constant returns(address) func (_ENSRegistry *ENSRegistryCaller) Owner(opts *bind.CallOpts, node [32]byte) (common.Address, error) { - var ( - ret0 = new(common.Address) - ) + + var ret0 = new(common.Address) + out := ret0 err := _ENSRegistry.contract.Call(opts, out, "owner", node) return *ret0, err @@ -218,9 +218,9 @@ func (_ENSRegistry *ENSRegistryCallerSession) Owner(node [32]byte) (common.Addre // // Solidity: function resolver(bytes32 node) constant returns(address) func (_ENSRegistry *ENSRegistryCaller) Resolver(opts *bind.CallOpts, node [32]byte) (common.Address, error) { - var ( - ret0 = new(common.Address) - ) + + var ret0 = new(common.Address) + out := ret0 err := _ENSRegistry.contract.Call(opts, out, "resolver", node) return *ret0, err @@ -244,9 +244,9 @@ func (_ENSRegistry *ENSRegistryCallerSession) Resolver(node [32]byte) (common.Ad // // Solidity: function ttl(bytes32 node) constant returns(uint64) func (_ENSRegistry *ENSRegistryCaller) Ttl(opts *bind.CallOpts, node [32]byte) (uint64, error) { - var ( - ret0 = new(uint64) - ) + + var ret0 = new(uint64) + out := ret0 err := _ENSRegistry.contract.Call(opts, out, "ttl", node) return *ret0, err @@ -429,7 +429,6 @@ type ENSRegistryNewOwner struct { // // Solidity: event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner) func (_ENSRegistry *ENSRegistryFilterer) FilterNewOwner(opts *bind.FilterOpts, node [][32]byte, label [][32]byte) (*ENSRegistryNewOwnerIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -450,7 +449,6 @@ func (_ENSRegistry *ENSRegistryFilterer) FilterNewOwner(opts *bind.FilterOpts, n // // Solidity: event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner) func (_ENSRegistry *ENSRegistryFilterer) WatchNewOwner(opts *bind.WatchOpts, sink chan<- *ENSRegistryNewOwner, node [][32]byte, label [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -570,7 +568,6 @@ type ENSRegistryNewResolver struct { // // Solidity: event NewResolver(bytes32 indexed node, address resolver) func (_ENSRegistry *ENSRegistryFilterer) FilterNewResolver(opts *bind.FilterOpts, node [][32]byte) (*ENSRegistryNewResolverIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -587,7 +584,6 @@ func (_ENSRegistry *ENSRegistryFilterer) FilterNewResolver(opts *bind.FilterOpts // // Solidity: event NewResolver(bytes32 indexed node, address resolver) func (_ENSRegistry *ENSRegistryFilterer) WatchNewResolver(opts *bind.WatchOpts, sink chan<- *ENSRegistryNewResolver, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -703,7 +699,6 @@ type ENSRegistryNewTTL struct { // // Solidity: event NewTTL(bytes32 indexed node, uint64 ttl) func (_ENSRegistry *ENSRegistryFilterer) FilterNewTTL(opts *bind.FilterOpts, node [][32]byte) (*ENSRegistryNewTTLIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -720,7 +715,6 @@ func (_ENSRegistry *ENSRegistryFilterer) FilterNewTTL(opts *bind.FilterOpts, nod // // Solidity: event NewTTL(bytes32 indexed node, uint64 ttl) func (_ENSRegistry *ENSRegistryFilterer) WatchNewTTL(opts *bind.WatchOpts, sink chan<- *ENSRegistryNewTTL, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -836,7 +830,6 @@ type ENSRegistryTransfer struct { // // Solidity: event Transfer(bytes32 indexed node, address owner) func (_ENSRegistry *ENSRegistryFilterer) FilterTransfer(opts *bind.FilterOpts, node [][32]byte) (*ENSRegistryTransferIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -853,7 +846,6 @@ func (_ENSRegistry *ENSRegistryFilterer) FilterTransfer(opts *bind.FilterOpts, n // // Solidity: event Transfer(bytes32 indexed node, address owner) func (_ENSRegistry *ENSRegistryFilterer) WatchTransfer(opts *bind.WatchOpts, sink chan<- *ENSRegistryTransfer, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) diff --git a/contracts/ens/contract/publicresolver.go b/contracts/ens/contract/publicresolver.go index 01bfce5e15..db8c4100d0 100644 --- a/contracts/ens/contract/publicresolver.go +++ b/contracts/ens/contract/publicresolver.go @@ -222,9 +222,9 @@ func (_PublicResolver *PublicResolverCallerSession) ABI(node [32]byte, contentTy // // Solidity: function addr(bytes32 node) constant returns(address) func (_PublicResolver *PublicResolverCaller) Addr(opts *bind.CallOpts, node [32]byte) (common.Address, error) { - var ( - ret0 = new(common.Address) - ) + + var ret0 = new(common.Address) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "addr", node) return *ret0, err @@ -248,9 +248,9 @@ func (_PublicResolver *PublicResolverCallerSession) Addr(node [32]byte) (common. // // Solidity: function contenthash(bytes32 node) constant returns(bytes) func (_PublicResolver *PublicResolverCaller) Contenthash(opts *bind.CallOpts, node [32]byte) ([]byte, error) { - var ( - ret0 = new([]byte) - ) + + var ret0 = new([]byte) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "contenthash", node) return *ret0, err @@ -274,9 +274,9 @@ func (_PublicResolver *PublicResolverCallerSession) Contenthash(node [32]byte) ( // // Solidity: function name(bytes32 node) constant returns(string) func (_PublicResolver *PublicResolverCaller) Name(opts *bind.CallOpts, node [32]byte) (string, error) { - var ( - ret0 = new(string) - ) + + var ret0 = new(string) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "name", node) return *ret0, err @@ -336,9 +336,9 @@ func (_PublicResolver *PublicResolverCallerSession) Pubkey(node [32]byte) (struc // // Solidity: function supportsInterface(bytes4 interfaceID) constant returns(bool) func (_PublicResolver *PublicResolverCaller) SupportsInterface(opts *bind.CallOpts, interfaceID [4]byte) (bool, error) { - var ( - ret0 = new(bool) - ) + + var ret0 = new(bool) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "supportsInterface", interfaceID) return *ret0, err @@ -362,9 +362,9 @@ func (_PublicResolver *PublicResolverCallerSession) SupportsInterface(interfaceI // // Solidity: function text(bytes32 node, string key) constant returns(string) func (_PublicResolver *PublicResolverCaller) Text(opts *bind.CallOpts, node [32]byte, key string) (string, error) { - var ( - ret0 = new(string) - ) + + var ret0 = new(string) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "text", node, key) return *ret0, err @@ -588,7 +588,6 @@ type PublicResolverABIChanged struct { // // Solidity: event ABIChanged(bytes32 indexed node, uint256 indexed contentType) func (_PublicResolver *PublicResolverFilterer) FilterABIChanged(opts *bind.FilterOpts, node [][32]byte, contentType []*big.Int) (*PublicResolverABIChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -609,7 +608,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterABIChanged(opts *bind.Filte // // Solidity: event ABIChanged(bytes32 indexed node, uint256 indexed contentType) func (_PublicResolver *PublicResolverFilterer) WatchABIChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverABIChanged, node [][32]byte, contentType []*big.Int) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -729,7 +727,6 @@ type PublicResolverAddrChanged struct { // // Solidity: event AddrChanged(bytes32 indexed node, address a) func (_PublicResolver *PublicResolverFilterer) FilterAddrChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverAddrChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -746,7 +743,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterAddrChanged(opts *bind.Filt // // Solidity: event AddrChanged(bytes32 indexed node, address a) func (_PublicResolver *PublicResolverFilterer) WatchAddrChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverAddrChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -862,7 +858,6 @@ type PublicResolverContenthashChanged struct { // // Solidity: event ContenthashChanged(bytes32 indexed node, bytes hash) func (_PublicResolver *PublicResolverFilterer) FilterContenthashChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverContenthashChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -879,7 +874,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterContenthashChanged(opts *bi // // Solidity: event ContenthashChanged(bytes32 indexed node, bytes hash) func (_PublicResolver *PublicResolverFilterer) WatchContenthashChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverContenthashChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -995,7 +989,6 @@ type PublicResolverNameChanged struct { // // Solidity: event NameChanged(bytes32 indexed node, string name) func (_PublicResolver *PublicResolverFilterer) FilterNameChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverNameChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1012,7 +1005,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterNameChanged(opts *bind.Filt // // Solidity: event NameChanged(bytes32 indexed node, string name) func (_PublicResolver *PublicResolverFilterer) WatchNameChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverNameChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1129,7 +1121,6 @@ type PublicResolverPubkeyChanged struct { // // Solidity: event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y) func (_PublicResolver *PublicResolverFilterer) FilterPubkeyChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverPubkeyChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1146,7 +1137,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterPubkeyChanged(opts *bind.Fi // // Solidity: event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y) func (_PublicResolver *PublicResolverFilterer) WatchPubkeyChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverPubkeyChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1263,7 +1253,6 @@ type PublicResolverTextChanged struct { // // Solidity: event TextChanged(bytes32 indexed node, string indexedKey, string key) func (_PublicResolver *PublicResolverFilterer) FilterTextChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverTextChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1280,7 +1269,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterTextChanged(opts *bind.Filt // // Solidity: event TextChanged(bytes32 indexed node, string indexedKey, string key) func (_PublicResolver *PublicResolverFilterer) WatchTextChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverTextChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) diff --git a/contracts/ens/fallback_contract/publicresolver.go b/contracts/ens/fallback_contract/publicresolver.go index a2a4be1c16..cd68eddafd 100644 --- a/contracts/ens/fallback_contract/publicresolver.go +++ b/contracts/ens/fallback_contract/publicresolver.go @@ -216,9 +216,9 @@ func (_PublicResolver *PublicResolverCallerSession) ABI(node [32]byte, contentTy // // Solidity: function addr(node bytes32) constant returns(ret address) func (_PublicResolver *PublicResolverCaller) Addr(opts *bind.CallOpts, node [32]byte) (common.Address, error) { - var ( - ret0 = new(common.Address) - ) + + var ret0 = new(common.Address) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "addr", node) return *ret0, err @@ -242,9 +242,9 @@ func (_PublicResolver *PublicResolverCallerSession) Addr(node [32]byte) (common. // // Solidity: function content(node bytes32) constant returns(ret bytes32) func (_PublicResolver *PublicResolverCaller) Content(opts *bind.CallOpts, node [32]byte) ([32]byte, error) { - var ( - ret0 = new([32]byte) - ) + + var ret0 = new([32]byte) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "content", node) return *ret0, err @@ -268,9 +268,9 @@ func (_PublicResolver *PublicResolverCallerSession) Content(node [32]byte) ([32] // // Solidity: function name(node bytes32) constant returns(ret string) func (_PublicResolver *PublicResolverCaller) Name(opts *bind.CallOpts, node [32]byte) (string, error) { - var ( - ret0 = new(string) - ) + + var ret0 = new(string) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "name", node) return *ret0, err @@ -330,9 +330,9 @@ func (_PublicResolver *PublicResolverCallerSession) Pubkey(node [32]byte) (struc // // Solidity: function supportsInterface(interfaceID bytes4) constant returns(bool) func (_PublicResolver *PublicResolverCaller) SupportsInterface(opts *bind.CallOpts, interfaceID [4]byte) (bool, error) { - var ( - ret0 = new(bool) - ) + + var ret0 = new(bool) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "supportsInterface", interfaceID) return *ret0, err @@ -356,9 +356,9 @@ func (_PublicResolver *PublicResolverCallerSession) SupportsInterface(interfaceI // // Solidity: function text(node bytes32, key string) constant returns(ret string) func (_PublicResolver *PublicResolverCaller) Text(opts *bind.CallOpts, node [32]byte, key string) (string, error) { - var ( - ret0 = new(string) - ) + + var ret0 = new(string) + out := ret0 err := _PublicResolver.contract.Call(opts, out, "text", node, key) return *ret0, err @@ -582,7 +582,6 @@ type PublicResolverABIChanged struct { // // Solidity: event ABIChanged(node indexed bytes32, contentType indexed uint256) func (_PublicResolver *PublicResolverFilterer) FilterABIChanged(opts *bind.FilterOpts, node [][32]byte, contentType []*big.Int) (*PublicResolverABIChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -603,7 +602,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterABIChanged(opts *bind.Filte // // Solidity: event ABIChanged(node indexed bytes32, contentType indexed uint256) func (_PublicResolver *PublicResolverFilterer) WatchABIChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverABIChanged, node [][32]byte, contentType []*big.Int) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -723,7 +721,6 @@ type PublicResolverAddrChanged struct { // // Solidity: event AddrChanged(node indexed bytes32, a address) func (_PublicResolver *PublicResolverFilterer) FilterAddrChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverAddrChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -740,7 +737,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterAddrChanged(opts *bind.Filt // // Solidity: event AddrChanged(node indexed bytes32, a address) func (_PublicResolver *PublicResolverFilterer) WatchAddrChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverAddrChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -856,7 +852,6 @@ type PublicResolverContentChanged struct { // // Solidity: event ContentChanged(node indexed bytes32, hash bytes32) func (_PublicResolver *PublicResolverFilterer) FilterContentChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverContentChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -873,7 +868,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterContentChanged(opts *bind.F // // Solidity: event ContentChanged(node indexed bytes32, hash bytes32) func (_PublicResolver *PublicResolverFilterer) WatchContentChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverContentChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -989,7 +983,6 @@ type PublicResolverNameChanged struct { // // Solidity: event NameChanged(node indexed bytes32, name string) func (_PublicResolver *PublicResolverFilterer) FilterNameChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverNameChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1006,7 +999,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterNameChanged(opts *bind.Filt // // Solidity: event NameChanged(node indexed bytes32, name string) func (_PublicResolver *PublicResolverFilterer) WatchNameChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverNameChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1123,7 +1115,6 @@ type PublicResolverPubkeyChanged struct { // // Solidity: event PubkeyChanged(node indexed bytes32, x bytes32, y bytes32) func (_PublicResolver *PublicResolverFilterer) FilterPubkeyChanged(opts *bind.FilterOpts, node [][32]byte) (*PublicResolverPubkeyChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1140,7 +1131,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterPubkeyChanged(opts *bind.Fi // // Solidity: event PubkeyChanged(node indexed bytes32, x bytes32, y bytes32) func (_PublicResolver *PublicResolverFilterer) WatchPubkeyChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverPubkeyChanged, node [][32]byte) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1257,7 +1247,6 @@ type PublicResolverTextChanged struct { // // Solidity: event TextChanged(node indexed bytes32, indexedKey indexed string, key string) func (_PublicResolver *PublicResolverFilterer) FilterTextChanged(opts *bind.FilterOpts, node [][32]byte, indexedKey []string) (*PublicResolverTextChangedIterator, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) @@ -1278,7 +1267,6 @@ func (_PublicResolver *PublicResolverFilterer) FilterTextChanged(opts *bind.Filt // // Solidity: event TextChanged(node indexed bytes32, indexedKey indexed string, key string) func (_PublicResolver *PublicResolverFilterer) WatchTextChanged(opts *bind.WatchOpts, sink chan<- *PublicResolverTextChanged, node [][32]byte, indexedKey []string) (event.Subscription, error) { - var nodeRule []interface{} for _, nodeItem := range node { nodeRule = append(nodeRule, nodeItem) diff --git a/core/bench_test.go b/core/bench_test.go index e0ccef788d..783d68eb7f 100644 --- a/core/bench_test.go +++ b/core/bench_test.go @@ -37,36 +37,47 @@ import ( func BenchmarkInsertChain_empty_memdb(b *testing.B) { benchInsertChain(b, false, nil) } + func BenchmarkInsertChain_empty_diskdb(b *testing.B) { benchInsertChain(b, true, nil) } + func BenchmarkInsertChain_valueTx_memdb(b *testing.B) { benchInsertChain(b, false, genValueTx(0)) } + func BenchmarkInsertChain_valueTx_diskdb(b *testing.B) { benchInsertChain(b, true, genValueTx(0)) } + func BenchmarkInsertChain_valueTx_100kB_memdb(b *testing.B) { benchInsertChain(b, false, genValueTx(100*1024)) } + func BenchmarkInsertChain_valueTx_100kB_diskdb(b *testing.B) { benchInsertChain(b, true, genValueTx(100*1024)) } + func BenchmarkInsertChain_uncles_memdb(b *testing.B) { benchInsertChain(b, false, genUncles) } + func BenchmarkInsertChain_uncles_diskdb(b *testing.B) { benchInsertChain(b, true, genUncles) } + func BenchmarkInsertChain_ring200_memdb(b *testing.B) { benchInsertChain(b, false, genTxRing(200)) } + func BenchmarkInsertChain_ring200_diskdb(b *testing.B) { benchInsertChain(b, true, genTxRing(200)) } + func BenchmarkInsertChain_ring1000_memdb(b *testing.B) { benchInsertChain(b, false, genTxRing(1000)) } + func BenchmarkInsertChain_ring1000_diskdb(b *testing.B) { benchInsertChain(b, true, genTxRing(1000)) } @@ -187,36 +198,47 @@ func benchInsertChain(b *testing.B, disk bool, gen func(int, *BlockGen)) { func BenchmarkChainRead_header_10k(b *testing.B) { benchReadChain(b, false, 10000) } + func BenchmarkChainRead_full_10k(b *testing.B) { benchReadChain(b, true, 10000) } + func BenchmarkChainRead_header_100k(b *testing.B) { benchReadChain(b, false, 100000) } + func BenchmarkChainRead_full_100k(b *testing.B) { benchReadChain(b, true, 100000) } + func BenchmarkChainRead_header_500k(b *testing.B) { benchReadChain(b, false, 500000) } + func BenchmarkChainRead_full_500k(b *testing.B) { benchReadChain(b, true, 500000) } + func BenchmarkChainWrite_header_10k(b *testing.B) { benchWriteChain(b, false, 10000) } + func BenchmarkChainWrite_full_10k(b *testing.B) { benchWriteChain(b, true, 10000) } + func BenchmarkChainWrite_header_100k(b *testing.B) { benchWriteChain(b, false, 100000) } + func BenchmarkChainWrite_full_100k(b *testing.B) { benchWriteChain(b, true, 100000) } + func BenchmarkChainWrite_header_500k(b *testing.B) { benchWriteChain(b, false, 500000) } + func BenchmarkChainWrite_full_500k(b *testing.B) { benchWriteChain(b, true, 500000) } diff --git a/core/blockchain.go b/core/blockchain.go index 4a347ec81d..f36079ae07 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -1098,9 +1098,9 @@ func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) { defer bc.blockProcFeed.Send(false) // Remove already known canon-blocks - var ( - block, prev *types.Block - ) + + var block, prev *types.Block + // Do a sanity check that the provided chain is actually ordered and linked for i := 1; i < len(chain); i++ { block = chain[i] diff --git a/core/blockchain_test.go b/core/blockchain_test.go index d6be6c7e84..0dcaad9b8c 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -1200,7 +1200,6 @@ done: t.Errorf("unexpected event fired: %v", e) case <-time.After(250 * time.Millisecond): } - } // Tests if the canonical block can be fetched from the database during chain insertion. @@ -1592,7 +1591,7 @@ func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks in for txi := 0; txi < numTxs; txi++ { uniq := uint64(i*numTxs + txi) recipient := recipientFn(uniq) - //recipient := common.BigToAddress(big.NewInt(0).SetUint64(1337 + uniq)) + // recipient := common.BigToAddress(big.NewInt(0).SetUint64(1337 + uniq)) tx, err := types.SignTx(types.NewTransaction(uniq, recipient, big.NewInt(1), params.TxGas, big.NewInt(1), nil), signer, testBankKey) if err != nil { b.Error(err) @@ -1620,10 +1619,10 @@ func benchmarkLargeNumberOfValueToNonexisting(b *testing.B, numTxs, numBlocks in b.StopTimer() if got := chain.CurrentBlock().Transactions().Len(); got != numTxs*numBlocks { b.Fatalf("Transactions were not included, expected %d, got %d", numTxs*numBlocks, got) - } } } + func BenchmarkBlockChain_1x1000ValueTransferToNonexisting(b *testing.B) { var ( numTxs = 1000 @@ -1639,6 +1638,7 @@ func BenchmarkBlockChain_1x1000ValueTransferToNonexisting(b *testing.B) { benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn) } + func BenchmarkBlockChain_1x1000ValueTransferToExisting(b *testing.B) { var ( numTxs = 1000 @@ -1656,6 +1656,7 @@ func BenchmarkBlockChain_1x1000ValueTransferToExisting(b *testing.B) { benchmarkLargeNumberOfValueToNonexisting(b, numTxs, numBlocks, recipientFn, dataFn) } + func BenchmarkBlockChain_1x1000Executions(b *testing.B) { var ( numTxs = 1000 @@ -1735,7 +1736,6 @@ func TestLowDiffLongChain(t *testing.T) { // - A common ancestor is placed at prune-point + blocksBetweenCommonAncestorAndPruneblock // - The sidechain S is prepended with numCanonBlocksInSidechain blocks from the canon chain func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommonAncestorAndPruneblock int) { - // Generate a canonical chain to act as the main dataset engine := ethash.NewFaker() db := rawdb.NewMemoryDatabase() @@ -1801,9 +1801,9 @@ func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommon // [ Cn, Cn+1, Cc, Sn+3 ... Sm] // ^ ^ ^ pruned func TestPrunedImportSide(t *testing.T) { - //glogger := log.NewGlogHandler(log.StreamHandler(os.Stdout, log.TerminalFormat(false))) - //glogger.Verbosity(3) - //log.Root().SetHandler(log.Handler(glogger)) + // glogger := log.NewGlogHandler(log.StreamHandler(os.Stdout, log.TerminalFormat(false))) + // glogger.Verbosity(3) + // log.Root().SetHandler(log.Handler(glogger)) testSideImport(t, 3, 3) testSideImport(t, 3, -3) testSideImport(t, 10, 0) diff --git a/core/bloombits/scheduler.go b/core/bloombits/scheduler.go index 6449c7465a..eeb58a9cb0 100644 --- a/core/bloombits/scheduler.go +++ b/core/bloombits/scheduler.go @@ -16,9 +16,7 @@ package bloombits -import ( - "sync" -) +import "sync" // request represents a bloom retrieval task to prioritize and pull from the local // database or remotely from the network. diff --git a/core/chain_indexer_test.go b/core/chain_indexer_test.go index abf5b3cc14..5c10426c2c 100644 --- a/core/chain_indexer_test.go +++ b/core/chain_indexer_test.go @@ -221,7 +221,7 @@ func (b *testChainIndexBackend) Process(ctx context.Context, header *types.Heade if b.headerCnt > b.indexer.sectionSize { b.t.Error("Processing too many headers") } - //t.processCh <- header.Number.Uint64() + // t.processCh <- header.Number.Uint64() select { case <-time.After(10 * time.Second): b.t.Fatal("Unexpected call to Process") diff --git a/core/genesis.go b/core/genesis.go index 1f34a3a9ea..0e744dd699 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -153,6 +153,7 @@ func (e *GenesisMismatchError) Error() string { func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) { return SetupGenesisBlockWithOverride(db, genesis, nil) } + func SetupGenesisBlockWithOverride(db ethdb.Database, genesis *Genesis, constantinopleOverride *big.Int) (*params.ChainConfig, common.Hash, error) { if genesis != nil && genesis.Config == nil { return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig diff --git a/core/rawdb/table.go b/core/rawdb/table.go index e19649dd46..972128dc10 100644 --- a/core/rawdb/table.go +++ b/core/rawdb/table.go @@ -16,9 +16,7 @@ package rawdb -import ( - "github.com/ethereum/go-ethereum/ethdb" -) +import "github.com/ethereum/go-ethereum/ethdb" // table is a wrapper around a database that prefixes each key access with a pre- // configured string. diff --git a/core/state/database.go b/core/state/database.go index 8798b73806..454c76fcdd 100644 --- a/core/state/database.go +++ b/core/state/database.go @@ -25,10 +25,8 @@ import ( lru "github.com/hashicorp/golang-lru" ) -const ( - // Number of codehash->size associations to keep. - codeSizeCacheSize = 100000 -) +// Number of codehash->size associations to keep. +const codeSizeCacheSize = 100000 // Database wraps access to tries and contract code. type Database interface { diff --git a/core/state/state_object.go b/core/state/state_object.go index 7fbb45b3df..dbd8c137db 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -34,7 +34,7 @@ var emptyCodeHash = crypto.Keccak256(nil) type Code []byte func (self Code) String() string { - return string(self) //strings.Join(Disassemble(self), " ") + return string(self) // strings.Join(Disassemble(self), " ") } type Storage map[common.Hash]common.Hash diff --git a/core/state/state_test.go b/core/state/state_test.go index 606f2a6f6e..5632e49ba9 100644 --- a/core/state/state_test.go +++ b/core/state/state_test.go @@ -95,7 +95,7 @@ func (s *StateSuite) SetUpTest(c *checker.C) { func (s *StateSuite) TestNull(c *checker.C) { address := common.HexToAddress("0x823140710bf13990e4500136726d8b55") s.state.CreateAccount(address) - //value := common.FromHex("0x823140710bf13990e4500136726d8b55") + // value := common.FromHex("0x823140710bf13990e4500136726d8b55") var value common.Hash s.state.SetState(address, common.Hash{}, value) diff --git a/core/state_transition.go b/core/state_transition.go index fda081b7d1..50512b5a33 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -27,9 +27,7 @@ import ( "github.com/ethereum/go-ethereum/params" ) -var ( - errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas") -) +var errInsufficientBalanceForGas = errors.New("insufficient balance to pay for gas") /* The State Transitioning Model @@ -63,7 +61,7 @@ type StateTransition struct { // Message represents a message sent to a contract. type Message interface { From() common.Address - //FromFrontier() (common.Address, error) + // FromFrontier() (common.Address, error) To() *common.Address GasPrice() *big.Int diff --git a/core/tx_pool.go b/core/tx_pool.go index 411143aeae..ee61aaf4ca 100644 --- a/core/tx_pool.go +++ b/core/tx_pool.go @@ -35,10 +35,8 @@ import ( "github.com/ethereum/go-ethereum/params" ) -const ( - // chainHeadChanSize is the size of channel listening to ChainHeadEvent. - chainHeadChanSize = 10 -) +// chainHeadChanSize is the size of channel listening to ChainHeadEvent. +const chainHeadChanSize = 10 var ( // ErrInvalidSender is returned if the transaction contains an invalid signature. diff --git a/core/tx_pool_test.go b/core/tx_pool_test.go index 50c73cf535..6bd0fef2ce 100644 --- a/core/tx_pool_test.go +++ b/core/tx_pool_test.go @@ -573,7 +573,6 @@ func TestTransactionPostponing(t *testing.T) { // Add a batch consecutive pending transactions for validation txs := []*types.Transaction{} for i, key := range keys { - for j := 0; j < 100; j++ { var tx *types.Transaction if (i+j)%2 == 0 { @@ -761,6 +760,7 @@ func TestTransactionQueueAccountLimiting(t *testing.T) { func TestTransactionQueueGlobalLimiting(t *testing.T) { testTransactionQueueGlobalLimiting(t, false) } + func TestTransactionQueueGlobalLimitingNoLocals(t *testing.T) { testTransactionQueueGlobalLimiting(t, true) } diff --git a/core/types/block_test.go b/core/types/block_test.go index bdd0b65717..9bf1c80b2e 100644 --- a/core/types/block_test.go +++ b/core/types/block_test.go @@ -77,6 +77,7 @@ func TestUncleHash(t *testing.T) { t.Fatalf("empty uncle hash is wrong, got %x != %x", h, exp) } } + func BenchmarkUncleHash(b *testing.B) { uncles := make([]*Header, 0) b.ResetTimer() diff --git a/core/types/bloom9.go b/core/types/bloom9.go index d045c9e667..e9c19f2abd 100644 --- a/core/types/bloom9.go +++ b/core/types/bloom9.go @@ -78,7 +78,6 @@ func (b Bloom) Test(test *big.Int) bool { func (b Bloom) TestBytes(test []byte) bool { return b.Test(new(big.Int).SetBytes(test)) - } // MarshalText encodes b as a hex string with 0x prefix. diff --git a/core/types/transaction.go b/core/types/transaction.go index ba3d5de91d..7d44499a73 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -31,9 +31,7 @@ import ( //go:generate gencodec -type txdata -field-override txdataMarshaling -out gen_tx_json.go -var ( - ErrInvalidSig = errors.New("invalid transaction v, r, s values") -) +var ErrInvalidSig = errors.New("invalid transaction v, r, s values") type Transaction struct { data txdata diff --git a/core/types/transaction_signing.go b/core/types/transaction_signing.go index 63132048ee..95e7765620 100644 --- a/core/types/transaction_signing.go +++ b/core/types/transaction_signing.go @@ -27,9 +27,7 @@ import ( "github.com/ethereum/go-ethereum/params" ) -var ( - ErrInvalidChainId = errors.New("invalid chain id for signer") -) +var ErrInvalidChainId = errors.New("invalid chain id for signer") // sigCache is used to cache the derived sender and contains // the signer used to derive it. diff --git a/core/vm/analysis.go b/core/vm/analysis.go index 0ccf47b979..d83c39d8e2 100644 --- a/core/vm/analysis.go +++ b/core/vm/analysis.go @@ -24,6 +24,7 @@ type bitvec []byte func (bits *bitvec) set(pos uint64) { (*bits)[pos/8] |= 0x80 >> (pos % 8) } + func (bits *bitvec) set8(pos uint64) { (*bits)[pos/8] |= 0xFF >> (pos % 8) (*bits)[pos/8+1] |= ^(0xFF >> (pos % 8)) diff --git a/core/vm/analysis_test.go b/core/vm/analysis_test.go index fd2d744d87..85c19ed527 100644 --- a/core/vm/analysis_test.go +++ b/core/vm/analysis_test.go @@ -64,6 +64,7 @@ func BenchmarkJumpdestAnalysis_1200k(bench *testing.B) { } bench.StopTimer() } + func BenchmarkJumpdestHashing_1200k(bench *testing.B) { // 4 ms code := make([]byte, 1200000) diff --git a/core/vm/contracts.go b/core/vm/contracts.go index 20b741f8f1..f1c7e9bbbd 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -111,6 +111,7 @@ type sha256hash struct{} func (c *sha256hash) RequiredGas(input []byte) uint64 { return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas } + func (c *sha256hash) Run(input []byte) ([]byte, error) { h := sha256.Sum256(input) return h[:], nil @@ -126,6 +127,7 @@ type ripemd160hash struct{} func (c *ripemd160hash) RequiredGas(input []byte) uint64 { return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas } + func (c *ripemd160hash) Run(input []byte) ([]byte, error) { ripemd := ripemd160.New() ripemd.Write(input) @@ -142,6 +144,7 @@ type dataCopy struct{} func (c *dataCopy) RequiredGas(input []byte) uint64 { return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas } + func (c *dataCopy) Run(in []byte) ([]byte, error) { return in, nil } diff --git a/core/vm/contracts_test.go b/core/vm/contracts_test.go index 96083337c9..4564a9f35e 100644 --- a/core/vm/contracts_test.go +++ b/core/vm/contracts_test.go @@ -374,7 +374,7 @@ func benchmarkPrecompiled(addr string, test precompiledTest, bench *testing.B) { res, err = RunPrecompiledContract(p, data, contract) } bench.StopTimer() - //Check if it is correct + // Check if it is correct if err != nil { bench.Error(err) return diff --git a/core/vm/evm.go b/core/vm/evm.go index 70e1cd1b87..7a741d4d0f 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -442,7 +442,6 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err) } return ret, address, contract.Gas, err - } // Create creates a new contract using code as deployment code. diff --git a/core/vm/instructions_test.go b/core/vm/instructions_test.go index 50d0a9ddae..2ec1b016f7 100644 --- a/core/vm/instructions_test.go +++ b/core/vm/instructions_test.go @@ -44,7 +44,6 @@ var commonParams []*twoOperandParams var twoOpMethods map[string]executionFunc func init() { - // Params is a list of common edgecases that should be used for some common tests params := []string{ "0000000000000000000000000000000000000000000000000000000000000000", // 0 @@ -90,7 +89,6 @@ func init() { } func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFunc, name string) { - var ( env = NewEVM(Context{}, nil, params.TestChainConfig, Config{}) stack = newstack() @@ -422,11 +420,13 @@ func BenchmarkOpEq(b *testing.B) { opBenchmark(b, opEq, x, y) } + func BenchmarkOpEq2(b *testing.B) { x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff" y := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201fffffffe" opBenchmark(b, opEq, x, y) } + func BenchmarkOpAnd(b *testing.B) { x := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff" y := "ABCDEF090807060504030201ffffffffffffffffffffffffffffffffffffffff" @@ -477,18 +477,21 @@ func BenchmarkOpSHL(b *testing.B) { opBenchmark(b, opSHL, x, y) } + func BenchmarkOpSHR(b *testing.B) { x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff" y := "ff" opBenchmark(b, opSHR, x, y) } + func BenchmarkOpSAR(b *testing.B) { x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff" y := "ff" opBenchmark(b, opSAR, x, y) } + func BenchmarkOpIsZero(b *testing.B) { x := "FBCDEF090807060504030201ffffffffFBCDEF090807060504030201ffffffff" opBenchmark(b, opIszero, x) diff --git a/core/vm/intpool_test.go b/core/vm/intpool_test.go index 6c0d00f3ce..78ac181dc0 100644 --- a/core/vm/intpool_test.go +++ b/core/vm/intpool_test.go @@ -16,9 +16,7 @@ package vm -import ( - "testing" -) +import "testing" func TestIntPoolPoolGet(t *testing.T) { poolOfIntPools.pools = make([]*intPool, 0, poolDefaultCap) diff --git a/core/vm/memory_table.go b/core/vm/memory_table.go index 4fcb41442c..c77ada4889 100644 --- a/core/vm/memory_table.go +++ b/core/vm/memory_table.go @@ -70,6 +70,7 @@ func memoryCall(stack *Stack) (uint64, bool) { } return y, false } + func memoryDelegateCall(stack *Stack) (uint64, bool) { x, overflow := calcMemSize64(stack.Back(4), stack.Back(5)) if overflow { diff --git a/core/vm/opcodes.go b/core/vm/opcodes.go index 4349ffd295..8e48f648ad 100644 --- a/core/vm/opcodes.go +++ b/core/vm/opcodes.go @@ -16,9 +16,7 @@ package vm -import ( - "fmt" -) +import "fmt" // OpCode is an EVM opcode type OpCode byte @@ -280,8 +278,8 @@ var opCodeToString = map[OpCode]string{ // 0x50 range - 'storage' and execution. POP: "POP", - //DUP: "DUP", - //SWAP: "SWAP", + // DUP: "DUP", + // SWAP: "SWAP", MLOAD: "MLOAD", MSTORE: "MSTORE", MSTORE8: "MSTORE8", diff --git a/core/vm/runtime/runtime_test.go b/core/vm/runtime/runtime_test.go index 15f545ddca..4dd5b2e2b6 100644 --- a/core/vm/runtime/runtime_test.go +++ b/core/vm/runtime/runtime_test.go @@ -149,6 +149,7 @@ func BenchmarkCall(b *testing.B) { } } } + func benchmarkEVM_Create(bench *testing.B, code string) { var ( statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase())) @@ -191,14 +192,17 @@ func BenchmarkEVM_CREATE_500(bench *testing.B) { // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056") } + func BenchmarkEVM_CREATE2_500(bench *testing.B) { // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056") } + func BenchmarkEVM_CREATE_1200(bench *testing.B) { // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056") } + func BenchmarkEVM_CREATE2_1200(bench *testing.B) { // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056") diff --git a/core/vm/stack.go b/core/vm/stack.go index 4c1b9e8037..9967da7184 100644 --- a/core/vm/stack.go +++ b/core/vm/stack.go @@ -39,10 +39,11 @@ func (st *Stack) Data() []*big.Int { func (st *Stack) push(d *big.Int) { // NOTE push limit (1024) is checked in baseCheck - //stackItem := new(big.Int).Set(d) - //st.data = append(st.data, stackItem) + // stackItem := new(big.Int).Set(d) + // st.data = append(st.data, stackItem) st.data = append(st.data, d) } + func (st *Stack) pushN(ds ...*big.Int) { st.data = append(st.data, ds...) } diff --git a/core/vm/stack_table.go b/core/vm/stack_table.go index 10c12901af..1728db7309 100644 --- a/core/vm/stack_table.go +++ b/core/vm/stack_table.go @@ -16,13 +16,12 @@ package vm -import ( - "github.com/ethereum/go-ethereum/params" -) +import "github.com/ethereum/go-ethereum/params" func minSwapStack(n int) int { return minStack(n, n) } + func maxSwapStack(n int) int { return maxStack(n, n) } @@ -30,6 +29,7 @@ func maxSwapStack(n int) int { func minDupStack(n int) int { return minStack(n, n+1) } + func maxDupStack(n int) int { return maxStack(n, n+1) } @@ -37,6 +37,7 @@ func maxDupStack(n int) int { func maxStack(pop, push int) int { return int(params.StackLimit) + pop - push } + func minStack(pops, push int) int { return pops } diff --git a/dashboard/assets.go b/dashboard/assets.go index 1ce18b285e..681386da3c 100644 --- a/dashboard/assets.go +++ b/dashboard/assets.go @@ -32,23 +32,28 @@ type bindataFileInfo struct { func (fi bindataFileInfo) Name() string { return fi.name } + func (fi bindataFileInfo) Size() int64 { return fi.size } + func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } + func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } + func (fi bindataFileInfo) IsDir() bool { return false } + func (fi bindataFileInfo) Sys() interface{} { return nil } -//nolint:misspell +// nolint:misspell var _indexHtml = []byte(`
@@ -92,7 +97,7 @@ func indexHtml() (*asset, error) { return a, nil } -//nolint:misspell +// nolint:misspell var _bundleJs = []byte((((`!function(e) { var t = {}; function n(r) { @@ -30224,8 +30229,8 @@ func bundleJs() (*asset, error) { return a, nil } -//nolint:misspell -//nolint:misspell +// nolint:misspell +// nolint:misspell var _bundleJsMap = []byte(((((((((((((`{ "version": 3, "sources": [ diff --git a/dashboard/dashboard.go b/dashboard/dashboard.go index d69a750f10..50ece3399d 100644 --- a/dashboard/dashboard.go +++ b/dashboard/dashboard.go @@ -43,9 +43,7 @@ import ( "golang.org/x/net/websocket" ) -const ( - sampleLimit = 200 // Maximum number of data samples -) +const sampleLimit = 200 // Maximum number of data samples // Dashboard contains the dashboard internals. type Dashboard struct { diff --git a/dashboard/message.go b/dashboard/message.go index 797b210fa8..b6f2f424a4 100644 --- a/dashboard/message.go +++ b/dashboard/message.go @@ -16,9 +16,7 @@ package dashboard -import ( - "encoding/json" -) +import "encoding/json" type Message struct { General *GeneralMessage `json:"general,omitempty"` diff --git a/eth/bloombits.go b/eth/bloombits.go index 9a31997d60..cdd83b1f25 100644 --- a/eth/bloombits.go +++ b/eth/bloombits.go @@ -79,11 +79,9 @@ func (eth *Ethereum) startBloomHandlers(sectionSize uint64) { } } -const ( - // bloomThrottling is the time to wait between processing two consecutive index - // sections. It's useful during chain upgrades to prevent disk overload. - bloomThrottling = 100 * time.Millisecond -) +// bloomThrottling is the time to wait between processing two consecutive index +// sections. It's useful during chain upgrades to prevent disk overload. +const bloomThrottling = 100 * time.Millisecond // BloomIndexer implements a core.ChainIndexer, building up a rotated bloom bits index // for the Ethereum header bloom filters, permitting blazing fast filtering. diff --git a/eth/downloader/downloader.go b/eth/downloader/downloader.go index d926d7aad0..aa08ceef14 100644 --- a/eth/downloader/downloader.go +++ b/eth/downloader/downloader.go @@ -1130,7 +1130,6 @@ func (d *Downloader) fetchParts(errCancel error, deliveryCh chan dataPack, deliv expire func() map[string]int, pending func() int, inFlight func() bool, throttle func() bool, reserve func(*peerConnection, int) (*fetchRequest, bool, error), fetchHook func([]*types.Header), fetch func(*peerConnection, *fetchRequest) error, cancel func(*fetchRequest), capacity func(*peerConnection) int, idle func() ([]*peerConnection, int), setIdle func(*peerConnection, int), kind string) error { - // Create a ticker to detect expired retrieval tasks ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() diff --git a/eth/downloader/downloader_test.go b/eth/downloader/downloader_test.go index bee6438bfd..f50d69b26e 100644 --- a/eth/downloader/downloader_test.go +++ b/eth/downloader/downloader_test.go @@ -1453,12 +1453,15 @@ func (ftp *floodingTestPeer) Head() (common.Hash, *big.Int) { return ftp.peer.He func (ftp *floodingTestPeer) RequestHeadersByHash(hash common.Hash, count int, skip int, reverse bool) error { return ftp.peer.RequestHeadersByHash(hash, count, skip, reverse) } + func (ftp *floodingTestPeer) RequestBodies(hashes []common.Hash) error { return ftp.peer.RequestBodies(hashes) } + func (ftp *floodingTestPeer) RequestReceipts(hashes []common.Hash) error { return ftp.peer.RequestReceipts(hashes) } + func (ftp *floodingTestPeer) RequestNodeData(hashes []common.Hash) error { return ftp.peer.RequestNodeData(hashes) } @@ -1502,33 +1505,41 @@ func TestRemoteHeaderRequestSpan(t *testing.T) { expected []int }{ // Remote is way higher. We should ask for the remote head and go backwards - {1500, 1000, + { + 1500, 1000, []int{1323, 1339, 1355, 1371, 1387, 1403, 1419, 1435, 1451, 1467, 1483, 1499}, }, - {15000, 13006, + { + 15000, 13006, []int{14823, 14839, 14855, 14871, 14887, 14903, 14919, 14935, 14951, 14967, 14983, 14999}, }, - //Remote is pretty close to us. We don't have to fetch as many - {1200, 1150, + // Remote is pretty close to us. We don't have to fetch as many + { + 1200, 1150, []int{1149, 1154, 1159, 1164, 1169, 1174, 1179, 1184, 1189, 1194, 1199}, }, // Remote is equal to us (so on a fork with higher td) // We should get the closest couple of ancestors - {1500, 1500, + { + 1500, 1500, []int{1497, 1499}, }, // We're higher than the remote! Odd - {1000, 1500, + { + 1000, 1500, []int{997, 999}, }, // Check some weird edgecases that it behaves somewhat rationally - {0, 1500, + { + 0, 1500, []int{0, 2}, }, - {6000000, 0, + { + 6000000, 0, []int{5999823, 5999839, 5999855, 5999871, 5999887, 5999903, 5999919, 5999935, 5999951, 5999967, 5999983, 5999999}, }, - {0, 0, + { + 0, 0, []int{0, 2}, }, } diff --git a/eth/downloader/metrics.go b/eth/downloader/metrics.go index d4eb337946..b6b42a6fd4 100644 --- a/eth/downloader/metrics.go +++ b/eth/downloader/metrics.go @@ -18,9 +18,7 @@ package downloader -import ( - "github.com/ethereum/go-ethereum/metrics" -) +import "github.com/ethereum/go-ethereum/metrics" var ( headerInMeter = metrics.NewRegisteredMeter("eth/downloader/headers/in", nil) diff --git a/eth/downloader/peer.go b/eth/downloader/peer.go index 60f86d0e14..6fb341ba38 100644 --- a/eth/downloader/peer.go +++ b/eth/downloader/peer.go @@ -99,15 +99,19 @@ func (w *lightPeerWrapper) Head() (common.Hash, *big.Int) { return w.peer.Head() func (w *lightPeerWrapper) RequestHeadersByHash(h common.Hash, amount int, skip int, reverse bool) error { return w.peer.RequestHeadersByHash(h, amount, skip, reverse) } + func (w *lightPeerWrapper) RequestHeadersByNumber(i uint64, amount int, skip int, reverse bool) error { return w.peer.RequestHeadersByNumber(i, amount, skip, reverse) } + func (w *lightPeerWrapper) RequestBodies([]common.Hash) error { panic("RequestBodies not supported in light client mode sync") } + func (w *lightPeerWrapper) RequestReceipts([]common.Hash) error { panic("RequestReceipts not supported in light client mode sync") } + func (w *lightPeerWrapper) RequestNodeData([]common.Hash) error { panic("RequestNodeData not supported in light client mode sync") } diff --git a/eth/downloader/queue.go b/eth/downloader/queue.go index 7c33953811..2d62add72a 100644 --- a/eth/downloader/queue.go +++ b/eth/downloader/queue.go @@ -803,7 +803,6 @@ func (q *queue) DeliverReceipts(id string, receiptList [][]*types.Receipt) (int, func (q *queue) deliver(id string, taskPool map[common.Hash]*types.Header, taskQueue *prque.Prque, pendPool map[string]*fetchRequest, donePool map[common.Hash]struct{}, reqTimer metrics.Timer, results int, reconstruct func(header *types.Header, index int, result *fetchResult) error) (int, error) { - // Short circuit if the data was never requested request := pendPool[id] if request == nil { diff --git a/eth/fetcher/fetcher.go b/eth/fetcher/fetcher.go index 94f05f9674..164ae983dd 100644 --- a/eth/fetcher/fetcher.go +++ b/eth/fetcher/fetcher.go @@ -39,9 +39,7 @@ const ( blockLimit = 64 // Maximum number of unique blocks a peer may have delivered ) -var ( - errTerminated = errors.New("terminated") -) +var errTerminated = errors.New("terminated") // blockRetrievalFn is a callback type for retrieving a block from the local chain. type blockRetrievalFn func(common.Hash) *types.Block diff --git a/eth/fetcher/metrics.go b/eth/fetcher/metrics.go index d68d12f000..e62258988b 100644 --- a/eth/fetcher/metrics.go +++ b/eth/fetcher/metrics.go @@ -18,9 +18,7 @@ package fetcher -import ( - "github.com/ethereum/go-ethereum/metrics" -) +import "github.com/ethereum/go-ethereum/metrics" var ( propAnnounceInMeter = metrics.NewRegisteredMeter("eth/fetcher/prop/announces/in", nil) diff --git a/eth/filters/api.go b/eth/filters/api.go index 5ed80a8875..d6aa947c70 100644 --- a/eth/filters/api.go +++ b/eth/filters/api.go @@ -34,9 +34,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" ) -var ( - deadline = 5 * time.Minute // consider a filter inactive if it has not been polled for within deadline -) +var deadline = 5 * time.Minute // consider a filter inactive if it has not been polled for within deadline // filter is a helper struct that holds meta information over the filter type // and associated subscription in the event system. @@ -251,7 +249,6 @@ func (api *PublicFilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*rpc } go func() { - for { select { case logs := <-matchedLogs: diff --git a/eth/filters/bench_test.go b/eth/filters/bench_test.go index 434e6a44c9..4136639bad 100644 --- a/eth/filters/bench_test.go +++ b/eth/filters/bench_test.go @@ -110,7 +110,7 @@ func benchmarkBloomBits(b *testing.B, sectionSize uint64) { compSize += uint64(len(comp)) rawdb.WriteBloomBits(db, uint(i), sectionIdx, sectionHead, comp) } - //if sectionIdx%50 == 0 { + // if sectionIdx%50 == 0 { // fmt.Println(" section", sectionIdx, "/", cnt) //} } diff --git a/eth/filters/filter_system.go b/eth/filters/filter_system.go index 70139c1a96..a0adac1a6c 100644 --- a/eth/filters/filter_system.go +++ b/eth/filters/filter_system.go @@ -70,9 +70,7 @@ const ( chainEvChanSize = 10 ) -var ( - ErrInvalidSubscriptionID = errors.New("invalid id") -) +var ErrInvalidSubscriptionID = errors.New("invalid id") type subscription struct { id rpc.ID diff --git a/eth/handler.go b/eth/handler.go index b42612a566..1da2da49bf 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -54,9 +54,7 @@ const ( minBroadcastPeers = 4 ) -var ( - daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge -) +var daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge // errIncompatibleConfig is returned if the requested protocols and configs are // not compatible (low protocol version restrictions and high requirements). diff --git a/eth/tracers/internal/tracers/assets.go b/eth/tracers/internal/tracers/assets.go index d0a0bf7c1a..152146bd8b 100644 --- a/eth/tracers/internal/tracers/assets.go +++ b/eth/tracers/internal/tracers/assets.go @@ -61,18 +61,23 @@ type bindataFileInfo struct { func (fi bindataFileInfo) Name() string { return fi.name } + func (fi bindataFileInfo) Size() int64 { return fi.size } + func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } + func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } + func (fi bindataFileInfo) IsDir() bool { return false } + func (fi bindataFileInfo) Sys() interface{} { return nil } diff --git a/ethclient/signer.go b/ethclient/signer.go index 74a93f1e2f..8fcea3a8b5 100644 --- a/ethclient/signer.go +++ b/ethclient/signer.go @@ -54,6 +54,7 @@ func (s *senderFromServer) Sender(tx *types.Transaction) (common.Address, error) func (s *senderFromServer) Hash(tx *types.Transaction) common.Hash { panic("can't sign with senderFromServer") } + func (s *senderFromServer) SignatureValues(tx *types.Transaction, sig []byte) (R, S, V *big.Int, err error) { panic("can't sign with senderFromServer") } diff --git a/graphql/graphql_test.go b/graphql/graphql_test.go index d63418398a..0704fb4704 100644 --- a/graphql/graphql_test.go +++ b/graphql/graphql_test.go @@ -16,9 +16,7 @@ package graphql -import ( - "testing" -) +import "testing" func TestBuildSchema(t *testing.T) { // Make sure the schema can be parsed and matched up to the object model. diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index 473026606f..980517460e 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -48,9 +48,7 @@ import ( "github.com/tyler-smith/go-bip39" ) -const ( - defaultGasPrice = params.GWei -) +const defaultGasPrice = params.GWei // PublicEthereumAPI provides an API to access Ethereum related information. // It offers only methods that operate on public data that is freely available to anyone. @@ -553,6 +551,7 @@ type AccountResult struct { StorageHash common.Hash `json:"storageHash"` StorageProof []StorageResult `json:"storageProof"` } + type StorageResult struct { Key string `json:"key"` Value *hexutil.Big `json:"value"` @@ -1334,7 +1333,6 @@ func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (c // SendTransaction creates a transaction for the given argument, sign it and submit it to the // transaction pool. func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) { - // Look up the wallet containing the requested signer account := accounts.Account{Address: args.From} diff --git a/internal/jsre/deps/bindata.go b/internal/jsre/deps/bindata.go index 7454c7cfcb..f6785998e8 100644 --- a/internal/jsre/deps/bindata.go +++ b/internal/jsre/deps/bindata.go @@ -52,18 +52,23 @@ type bindataFileInfo struct { func (fi bindataFileInfo) Name() string { return fi.name } + func (fi bindataFileInfo) Size() int64 { return fi.size } + func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } + func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } + func (fi bindataFileInfo) IsDir() bool { return false } + func (fi bindataFileInfo) Sys() interface{} { return nil } diff --git a/les/api_test.go b/les/api_test.go index cec9459625..f40463c1cd 100644 --- a/les/api_test.go +++ b/les/api_test.go @@ -315,7 +315,7 @@ func getHead(ctx context.Context, t *testing.T, client *rpc.Client) (uint64, com } func testRequest(ctx context.Context, t *testing.T, client *rpc.Client) bool { - //res := make(map[string]interface{}) + // res := make(map[string]interface{}) var res string var addr common.Address rand.Read(addr[:]) diff --git a/les/execqueue_test.go b/les/execqueue_test.go index cd45b03f22..757ebfb16e 100644 --- a/les/execqueue_test.go +++ b/les/execqueue_test.go @@ -16,9 +16,7 @@ package les -import ( - "testing" -) +import "testing" func TestExecQueue(t *testing.T) { var ( diff --git a/les/fetcher.go b/les/fetcher.go index 057552f532..d3bcfcfeea 100644 --- a/les/fetcher.go +++ b/les/fetcher.go @@ -455,7 +455,7 @@ func (f *lightFetcher) findBestRequest() (bestHash common.Hash, bestAmount uint6 continue } - //if ulc mode is disabled, isTrustedHash returns true + // if ulc mode is disabled, isTrustedHash returns true amount := f.requestAmount(p, n) if (bestTd == nil || n.td.Cmp(bestTd) > 0 || amount < bestAmount) && (f.isTrustedHash(hash) || f.maxConfirmedTd.Int64() == 0) { bestHash = hash @@ -508,7 +508,7 @@ func (f *lightFetcher) newFetcherDistReqForSync(bestHash common.Hash) *distReq { }, request: func(dp distPeer) func() { if f.pm.isULCEnabled() { - //keep last trusted header before sync + // keep last trusted header before sync f.setLastTrustedHeader(f.chain.CurrentHeader()) } go func() { @@ -718,13 +718,13 @@ func (f *lightFetcher) checkSyncedHeaders(p *peer) { var unapprovedHashes []common.Hash // Overwrite last announced for ULC mode h, unapprovedHashes = f.lastTrustedTreeNode(p) - //rollback untrusted blocks + // rollback untrusted blocks f.chain.Rollback(unapprovedHashes) - //overwrite to last trusted + // overwrite to last trusted n = fp.nodeByHash[h.Hash()] } - //find last valid block + // find last valid block for n != nil { if td = f.chain.GetTd(n.hash, n.number); td != nil { break diff --git a/les/flowcontrol/manager.go b/les/flowcontrol/manager.go index 532e6a4050..e41009a71f 100644 --- a/les/flowcontrol/manager.go +++ b/les/flowcontrol/manager.go @@ -281,7 +281,6 @@ func (cm *ClientManager) updateNodeRc(node *ClientNode, bvc int64, params *Serve cm.updateCapFactor(now, true) cm.sumRecharge = sumRecharge } - } // updateCapFactor updates the total capacity factor. The capacity factor allows diff --git a/les/flowcontrol/manager_test.go b/les/flowcontrol/manager_test.go index 4e7746d400..b4ccd24aba 100644 --- a/les/flowcontrol/manager_test.go +++ b/les/flowcontrol/manager_test.go @@ -63,7 +63,7 @@ func testConstantTotalCapacity(t *testing.T, nodeCount, maxCapacityNodes, random } m := NewClientManager(PieceWiseLinear{{0, totalCapacity}}, clock) for _, n := range nodes { - n.bufLimit = n.capacity * 6000 //uint64(2000+rand.Intn(10000)) + n.bufLimit = n.capacity * 6000 // uint64(2000+rand.Intn(10000)) n.node = NewClientNode(m, ServerParams{BufLimit: n.bufLimit, MinRecharge: n.capacity}) } maxNodes := make([]int, maxCapacityNodes) @@ -101,7 +101,6 @@ func testConstantTotalCapacity(t *testing.T, nodeCount, maxCapacityNodes, random if ratio < 0.98 || ratio > 1.02 { t.Errorf("totalCost/totalCapacity/testLength ratio incorrect (expected: 1, got: %f)", ratio) } - } func (n *testNode) send(t *testing.T, now mclock.AbsTime) bool { @@ -117,7 +116,7 @@ func (n *testNode) send(t *testing.T, now mclock.AbsTime) bool { if bv < testMaxCost { n.waitUntil = now + mclock.AbsTime((testMaxCost-bv)*1001000/n.capacity) } - //n.waitUntil = now + mclock.AbsTime(float64(testMaxCost)*1001000/float64(n.capacity)*(1-float64(bv)/float64(n.bufLimit))) + // n.waitUntil = now + mclock.AbsTime(float64(testMaxCost)*1001000/float64(n.capacity)*(1-float64(bv)/float64(n.bufLimit))) n.totalCost += rcost return true } diff --git a/les/handler.go b/les/handler.go index 9c72c6b133..0d8381f7f4 100644 --- a/les/handler.go +++ b/les/handler.go @@ -894,7 +894,6 @@ func (pm *ProtocolManager) handleMsg(p *peer) error { return errResp(ErrRequestRejected, "") } go func() { - var ( lastIdx uint64 lastType uint diff --git a/les/odr_test.go b/les/odr_test.go index bc587a1832..5caed32f9b 100644 --- a/les/odr_test.go +++ b/les/odr_test.go @@ -129,7 +129,7 @@ func odrContractCall(ctx context.Context, db ethdb.Database, config *params.Chai context := core.NewEVMContext(msg, header, bc, nil) vmenv := vm.NewEVM(context, statedb, config, vm.Config{}) - //vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{}) + // vmenv := core.NewEnv(statedb, config, bc, msg, header, vm.Config{}) gp := new(core.GasPool).AddGas(math.MaxUint64) ret, _, _, _ := core.ApplyMessage(vmenv, msg, gp) res = append(res, ret...) diff --git a/les/peer.go b/les/peer.go index bf3f0f7621..45810d68b1 100644 --- a/les/peer.go +++ b/les/peer.go @@ -456,7 +456,7 @@ func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis send = send.add("genesisHash", genesis) if server != nil { if !server.onlyAnnounce { - //only announce server. It sends only announse requests + // only announce server. It sends only announse requests send = send.add("serveHeaders", nil) send = send.add("serveChainSince", uint64(0)) send = send.add("serveStateSince", uint64(0)) @@ -474,7 +474,7 @@ func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis p.fcCosts = costList.decode() p.fcParams = server.defParams } else { - //on client node + // on client node p.announceType = announceTypeSimple if p.isTrusted { p.announceType = announceTypeSigned @@ -530,12 +530,12 @@ func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis return errResp(ErrUselessPeer, "wanted client, got server") }*/ if recv.get("announceType", &p.announceType) != nil { - //set default announceType on server side + // set default announceType on server side p.announceType = announceTypeSimple } p.fcClient = flowcontrol.NewClientNode(server.fcManager, server.defParams) } else { - //mark OnlyAnnounce server if "serveHeaders", "serveChainSince", "serveStateSince" or "txRelay" fields don't exist + // mark OnlyAnnounce server if "serveHeaders", "serveChainSince", "serveStateSince" or "txRelay" fields don't exist if recv.get("serveChainSince", nil) != nil { p.isOnlyAnnounce = true } diff --git a/les/peer_test.go b/les/peer_test.go index 8b12dd291c..205ccc988b 100644 --- a/les/peer_test.go +++ b/les/peer_test.go @@ -23,18 +23,18 @@ var ( td = big.NewInt(123) ) -//ulc connects to trusted peer and send announceType=announceTypeSigned +// ulc connects to trusted peer and send announceType=announceTypeSigned func TestPeerHandshakeSetAnnounceTypeToAnnounceTypeSignedForTrustedPeer(t *testing.T) { id := newNodeID(t).ID() - //peer to connect(on ulc side) + // peer to connect(on ulc side) p := peer{ Peer: p2p.NewPeer(id, "test peer", []p2p.Cap{}), version: protocol_version, isTrusted: true, rw: &rwStub{ WriteHook: func(recvList keyValueList) { - //checking that ulc sends to peer allowedRequests=onlyAnnounceRequests and announceType = announceTypeSigned + // checking that ulc sends to peer allowedRequests=onlyAnnounceRequests and announceType = announceTypeSigned recv, _ := recvList.decode() var reqType uint64 @@ -79,7 +79,7 @@ func TestPeerHandshakeAnnounceTypeSignedForTrustedPeersPeerNotInTrusted(t *testi version: protocol_version, rw: &rwStub{ WriteHook: func(recvList keyValueList) { - //checking that ulc sends to peer allowedRequests=noRequests and announceType != announceTypeSigned + // checking that ulc sends to peer allowedRequests=noRequests and announceType != announceTypeSigned recv, _ := recvList.decode() var reqType uint64 @@ -179,6 +179,7 @@ func TestPeerHandshakeServerSendOnlyAnnounceRequestsHeaders(t *testing.T) { t.Fatal(err) } } + func TestPeerHandshakeClientReceiveOnlyAnnounceRequestsHeaders(t *testing.T) { id := newNodeID(t).ID() diff --git a/les/protocol.go b/les/protocol.go index 86e450d01c..293c3c2815 100644 --- a/les/protocol.go +++ b/les/protocol.go @@ -32,9 +32,8 @@ import ( ) // Constants to match up protocol versions and messages -const ( - lpv2 = 2 -) + +const lpv2 = 2 // Supported versions of the les protocol (first is primary) var ( diff --git a/les/randselect.go b/les/randselect.go index 8efe0c94d3..114e253820 100644 --- a/les/randselect.go +++ b/les/randselect.go @@ -16,9 +16,7 @@ package les -import ( - "math/rand" -) +import "math/rand" // wrsItem interface should be implemented by any entries that are to be selected from // a weightedRandomSelect set. Note that recalculating monotonously decreasing item diff --git a/les/server.go b/les/server.go index 6c2b227f42..ef6516d66d 100644 --- a/les/server.go +++ b/les/server.go @@ -189,7 +189,7 @@ func (s *LesServer) Start(srvr *p2p.Server) { s.maxPeers = s.config.LightPeers totalRecharge := s.costTracker.totalRecharge() if s.maxPeers > 0 { - s.freeClientCap = minCapacity //totalRecharge / uint64(s.maxPeers) + s.freeClientCap = minCapacity // totalRecharge / uint64(s.maxPeers) if s.freeClientCap < minCapacity { s.freeClientCap = minCapacity } diff --git a/les/serverpool.go b/les/serverpool.go index 668f39c562..344e500e86 100644 --- a/les/serverpool.go +++ b/les/serverpool.go @@ -492,7 +492,7 @@ func (pool *serverPool) loadNodes() { // added to either the known or new selection pools. They are connected/reconnected // by p2p.Server whenever possible. func (pool *serverPool) connectToTrustedNodes() { - //connect to trusted nodes + // connect to trusted nodes for _, node := range pool.trustedNodes { pool.server.AddTrustedPeer(node) pool.server.AddPeer(node) diff --git a/les/sync.go b/les/sync.go index 1ac6455852..a33426fe08 100644 --- a/les/sync.go +++ b/les/sync.go @@ -29,12 +29,12 @@ import ( // downloading hashes and blocks as well as handling the announcement handler. func (pm *ProtocolManager) syncer() { // Start and ensure cleanup of sync mechanisms - //pm.fetcher.Start() - //defer pm.fetcher.Stop() + // pm.fetcher.Start() + // defer pm.fetcher.Stop() defer pm.downloader.Terminate() // Wait for different events to fire synchronisation operations - //forceSync := time.Tick(forceSyncCycle) + // forceSync := time.Tick(forceSyncCycle) for { select { case <-pm.newPeerCh: diff --git a/les/ulc_test.go b/les/ulc_test.go index 81986fa1e8..f7245102f6 100644 --- a/les/ulc_test.go +++ b/les/ulc_test.go @@ -61,7 +61,7 @@ func TestULCReceiveAnnounce(t *testing.T) { l.PM.synchronise(fPeer) - //check that the sync is finished correctly + // check that the sync is finished correctly if !reflect.DeepEqual(f.PM.blockchain.CurrentHeader().Hash(), l.PM.blockchain.CurrentHeader().Hash()) { t.Fatal("sync doesn't work") } @@ -73,7 +73,7 @@ func TestULCReceiveAnnounce(t *testing.T) { l.PM.peers.lock.Unlock() time.Sleep(time.Second) - //send a signed announce message(payload doesn't matter) + // send a signed announce message(payload doesn't matter) td := f.PM.blockchain.GetTd(l.PM.blockchain.CurrentHeader().Hash(), l.PM.blockchain.CurrentHeader().Number.Uint64()) announce := announceData{ Number: l.PM.blockchain.CurrentHeader().Number.Uint64() + 1, diff --git a/light/odr_util.go b/light/odr_util.go index 00103a76bd..2ff4bc8fb8 100644 --- a/light/odr_util.go +++ b/light/odr_util.go @@ -221,8 +221,10 @@ func GetBloomBits(ctx context.Context, odr OdrBackend, bitIdx uint, sectionIdxLi return result, nil } - r := &BloomRequest{BloomTrieRoot: GetBloomTrieRoot(db, bloomTrieCount-1, sectionHead), BloomTrieNum: bloomTrieCount - 1, - BitIdx: bitIdx, SectionIndexList: reqList, Config: odr.IndexerConfig()} + r := &BloomRequest{ + BloomTrieRoot: GetBloomTrieRoot(db, bloomTrieCount-1, sectionHead), BloomTrieNum: bloomTrieCount - 1, + BitIdx: bitIdx, SectionIndexList: reqList, Config: odr.IndexerConfig(), + } if err := odr.Retrieve(ctx, r); err != nil { return nil, err } else { diff --git a/light/txpool.go b/light/txpool.go index e945ef2ec1..0594238684 100644 --- a/light/txpool.go +++ b/light/txpool.go @@ -34,10 +34,8 @@ import ( "github.com/ethereum/go-ethereum/rlp" ) -const ( - // chainHeadChanSize is the size of channel listening to ChainHeadEvent. - chainHeadChanSize = 10 -) +// chainHeadChanSize is the size of channel listening to ChainHeadEvent. +const chainHeadChanSize = 10 // txPermanent is the number of mined blocks after a mined transaction is // considered permanent and no rollback is expected @@ -436,7 +434,7 @@ func (pool *TxPool) Add(ctx context.Context, tx *types.Transaction) error { if err := pool.add(ctx, tx); err != nil { return err } - //fmt.Println("Send", tx.Hash()) + // fmt.Println("Send", tx.Hash()) pool.relay.Send(types.Transactions{tx}) pool.chainDb.Put(tx.Hash().Bytes(), data) diff --git a/log/root.go b/log/root.go index 9fb4c5ae0b..7304f7179f 100644 --- a/log/root.go +++ b/log/root.go @@ -1,8 +1,6 @@ package log -import ( - "os" -) +import "os" var ( root = &logger{[]interface{}{}, new(swapHandler)} diff --git a/metrics/counter.go b/metrics/counter.go index 2f78c90d5c..2ccb9fd9a3 100644 --- a/metrics/counter.go +++ b/metrics/counter.go @@ -1,8 +1,6 @@ package metrics -import ( - "sync/atomic" -) +import "sync/atomic" // Counters hold an int64 value that can be incremented and decremented. type Counter interface { diff --git a/metrics/debug.go b/metrics/debug.go index de4a2739fe..dc9d0a7dd3 100644 --- a/metrics/debug.go +++ b/metrics/debug.go @@ -11,7 +11,7 @@ var ( LastGC Gauge NumGC Gauge Pause Histogram - //PauseQuantiles Histogram + // PauseQuantiles Histogram PauseTotal Gauge } ReadGCStats Timer @@ -46,7 +46,7 @@ func CaptureDebugGCStatsOnce(r Registry) { if lastGC != gcStats.LastGC && 0 < len(gcStats.Pause) { debugMetrics.GCStats.Pause.Update(int64(gcStats.Pause[0])) } - //debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles) + // debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles) debugMetrics.GCStats.PauseTotal.Update(int64(gcStats.PauseTotal)) } @@ -57,14 +57,14 @@ func RegisterDebugGCStats(r Registry) { debugMetrics.GCStats.LastGC = NewGauge() debugMetrics.GCStats.NumGC = NewGauge() debugMetrics.GCStats.Pause = NewHistogram(NewExpDecaySample(1028, 0.015)) - //debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015)) + // debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015)) debugMetrics.GCStats.PauseTotal = NewGauge() debugMetrics.ReadGCStats = NewTimer() r.Register("debug.GCStats.LastGC", debugMetrics.GCStats.LastGC) r.Register("debug.GCStats.NumGC", debugMetrics.GCStats.NumGC) r.Register("debug.GCStats.Pause", debugMetrics.GCStats.Pause) - //r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles) + // r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles) r.Register("debug.GCStats.PauseTotal", debugMetrics.GCStats.PauseTotal) r.Register("debug.ReadGCStats", debugMetrics.ReadGCStats) } diff --git a/metrics/exp/exp.go b/metrics/exp/exp.go index 325a193c77..cc6c315f62 100644 --- a/metrics/exp/exp.go +++ b/metrics/exp/exp.go @@ -87,6 +87,7 @@ func (exp *exp) publishGauge(name string, metric metrics.Gauge) { v := exp.getInt(name) v.Set(metric.Value()) } + func (exp *exp) publishGaugeFloat64(name string, metric metrics.GaugeFloat64) { exp.getFloat(name).Set(metric.Value()) } diff --git a/metrics/librato/librato.go b/metrics/librato/librato.go index 2138e01ae8..314c9d93d6 100644 --- a/metrics/librato/librato.go +++ b/metrics/librato/librato.go @@ -69,6 +69,7 @@ func sumSquares(s metrics.Sample) float64 { } return sumSquares } + func sumSquaresTimer(t metrics.Timer) float64 { count := float64(t.Count()) sumSquared := math.Pow(count*t.Mean(), 2) diff --git a/metrics/log.go b/metrics/log.go index 0c8ea7c971..c3ead7ea92 100644 --- a/metrics/log.go +++ b/metrics/log.go @@ -1,8 +1,6 @@ package metrics -import ( - "time" -) +import "time" type Logger interface { Printf(format string, v ...interface{}) diff --git a/metrics/metrics_test.go b/metrics/metrics_test.go index df36da0ade..d8417d8c22 100644 --- a/metrics/metrics_test.go +++ b/metrics/metrics_test.go @@ -53,11 +53,11 @@ func BenchmarkMetrics(b *testing.B) { wgR.Add(1) go func() { defer wgR.Done() - //log.Println("go CaptureRuntimeMemStats") + // log.Println("go CaptureRuntimeMemStats") for { select { case <-ch: - //log.Println("done CaptureRuntimeMemStats") + // log.Println("done CaptureRuntimeMemStats") return default: CaptureRuntimeMemStatsOnce(r) @@ -89,7 +89,7 @@ func BenchmarkMetrics(b *testing.B) { for i := 0; i < FANOUT; i++ { go func(i int) { defer wg.Done() - //log.Println("go", i) + // log.Println("go", i) for i := 0; i < b.N; i++ { c.Inc(1) g.Update(int64(i)) @@ -98,7 +98,7 @@ func BenchmarkMetrics(b *testing.B) { m.Mark(1) t.Update(1) } - //log.Println("done", i) + // log.Println("done", i) }(i) } wg.Wait() diff --git a/metrics/registry_test.go b/metrics/registry_test.go index a63e485fe9..65cea7b932 100644 --- a/metrics/registry_test.go +++ b/metrics/registry_test.go @@ -1,8 +1,6 @@ package metrics -import ( - "testing" -) +import "testing" func BenchmarkRegistry(b *testing.B) { r := NewRegistry() @@ -278,7 +276,7 @@ func TestChildPrefixedRegistryOfChildRegister(t *testing.T) { r2.Each(func(name string, m interface{}) { i++ if name != "prefix.prefix2.baz" { - //t.Fatal(name) + // t.Fatal(name) } }) if i != 1 { @@ -301,5 +299,4 @@ func TestWalkRegistries(t *testing.T) { if "prefix.prefix2." != prefix { t.Fatal(prefix) } - } diff --git a/metrics/sample_test.go b/metrics/sample_test.go index d60e99c5bb..66b58ca57b 100644 --- a/metrics/sample_test.go +++ b/metrics/sample_test.go @@ -21,6 +21,7 @@ func BenchmarkCompute1000(b *testing.B) { SampleVariance(s) } } + func BenchmarkCompute1000000(b *testing.B) { s := make([]int64, 1000000) for i := 0; i < len(s); i++ { @@ -31,6 +32,7 @@ func BenchmarkCompute1000000(b *testing.B) { SampleVariance(s) } } + func BenchmarkCopy1000(b *testing.B) { s := make([]int64, 1000) for i := 0; i < len(s); i++ { @@ -42,6 +44,7 @@ func BenchmarkCopy1000(b *testing.B) { copy(sCopy, s) } } + func BenchmarkCopy1000000(b *testing.B) { s := make([]int64, 1000000) for i := 0; i < len(s); i++ { diff --git a/miner/unconfirmed_test.go b/miner/unconfirmed_test.go index 42e77f3e64..acedec5c28 100644 --- a/miner/unconfirmed_test.go +++ b/miner/unconfirmed_test.go @@ -30,6 +30,7 @@ type noopChainRetriever struct{} func (r *noopChainRetriever) GetHeaderByNumber(number uint64) *types.Header { return nil } + func (r *noopChainRetriever) GetBlockByNumber(number uint64) *types.Block { return nil } diff --git a/miner/worker_test.go b/miner/worker_test.go index 99a671ae30..8653ea8ba0 100644 --- a/miner/worker_test.go +++ b/miner/worker_test.go @@ -142,6 +142,7 @@ func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consens func TestPendingStateAndBlockEthash(t *testing.T) { testPendingStateAndBlock(t, ethashChainConfig, ethash.NewFaker()) } + func TestPendingStateAndBlockClique(t *testing.T) { testPendingStateAndBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) } @@ -174,6 +175,7 @@ func testPendingStateAndBlock(t *testing.T, chainConfig *params.ChainConfig, eng func TestEmptyWorkEthash(t *testing.T) { testEmptyWork(t, ethashChainConfig, ethash.NewFaker()) } + func TestEmptyWorkClique(t *testing.T) { testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase())) } diff --git a/mobile/bind.go b/mobile/bind.go index d6e621a258..70b8064b70 100644 --- a/mobile/bind.go +++ b/mobile/bind.go @@ -84,7 +84,7 @@ func (opts *TransactOpts) GetGasLimit() int64 { return int64(opts.opts.GasLimi // GetContext cannot be reliably implemented without identity preservation (https://github.com/golang/go/issues/16876) // Even then it's awkward to unpack the subtleties of a Go context out to Java. -//func (opts *TransactOpts) GetContext() *Context { return &Context{opts.opts.Context} } +// func (opts *TransactOpts) GetContext() *Context { return &Context{opts.opts.Context} } func (opts *TransactOpts) SetFrom(from *Address) { opts.opts.From = from.address } func (opts *TransactOpts) SetNonce(nonce int64) { opts.opts.Nonce = big.NewInt(nonce) } diff --git a/mobile/ethclient.go b/mobile/ethclient.go index 662125c4ad..00bcb3a2b9 100644 --- a/mobile/ethclient.go +++ b/mobile/ethclient.go @@ -94,7 +94,6 @@ func (ec *EthereumClient) GetTransactionCount(ctx *Context, hash *Hash) (count i func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) { rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index)) return &Transaction{rawTx}, err - } // GetTransactionReceipt returns the receipt of a transaction by transaction hash. diff --git a/mobile/interface.go b/mobile/interface.go index ac0c26088a..12b553c1a8 100644 --- a/mobile/interface.go +++ b/mobile/interface.go @@ -101,12 +101,15 @@ func (i *Interface) GetInt64() int64 { return *i.object.(*int64) } func (i *Interface) GetUint8() *BigInt { return &BigInt{new(big.Int).SetUint64(uint64(*i.object.(*uint8)))} } + func (i *Interface) GetUint16() *BigInt { return &BigInt{new(big.Int).SetUint64(uint64(*i.object.(*uint16)))} } + func (i *Interface) GetUint32() *BigInt { return &BigInt{new(big.Int).SetUint64(uint64(*i.object.(*uint32)))} } + func (i *Interface) GetUint64() *BigInt { return &BigInt{new(big.Int).SetUint64(*i.object.(*uint64))} } diff --git a/node/node_test.go b/node/node_test.go index c464771cd8..838dfe8a04 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -29,9 +29,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" ) -var ( - testNodeKey, _ = crypto.GenerateKey() -) +var testNodeKey, _ = crypto.GenerateKey() func testNodeConfig() *Config { return &Config{ @@ -539,17 +537,20 @@ func TestAPIGather(t *testing.T) { Maker InstrumentingWrapper }{ "Zero APIs": { - []rpc.API{}, InstrumentedServiceMakerA}, + []rpc.API{}, InstrumentedServiceMakerA, + }, "Single API": { []rpc.API{ {Namespace: "single", Version: "1", Service: makeAPI("single.v1"), Public: true}, - }, InstrumentedServiceMakerB}, + }, InstrumentedServiceMakerB, + }, "Many APIs": { []rpc.API{ {Namespace: "multi", Version: "1", Service: makeAPI("multi.v1"), Public: true}, {Namespace: "multi.v2", Version: "2", Service: makeAPI("multi.v2"), Public: true}, {Namespace: "multi.v2.nested", Version: "2", Service: makeAPI("multi.v2.nested"), Public: true}, - }, InstrumentedServiceMakerC}, + }, InstrumentedServiceMakerC, + }, } for id, config := range services { diff --git a/p2p/dial.go b/p2p/dial.go index 075a0f9368..02bfbac259 100644 --- a/p2p/dial.go +++ b/p2p/dial.go @@ -382,6 +382,7 @@ func (t *discoverTask) String() string { func (t waitExpireTask) Do(*Server) { time.Sleep(t.Duration) } + func (t waitExpireTask) String() string { return fmt.Sprintf("wait for dial hist expire (%v)", t.Duration) } @@ -390,10 +391,11 @@ func (t waitExpireTask) String() string { func (h dialHistory) min() pastDial { return h[0] } + func (h *dialHistory) add(id enode.ID, exp time.Time) { heap.Push(h, pastDial{id, exp}) - } + func (h *dialHistory) remove(id enode.ID) bool { for i, v := range *h { if v.id == id { @@ -403,6 +405,7 @@ func (h *dialHistory) remove(id enode.ID) bool { } return false } + func (h dialHistory) contains(id enode.ID) bool { for _, v := range h { if v.id == id { @@ -411,6 +414,7 @@ func (h dialHistory) contains(id enode.ID) bool { } return false } + func (h *dialHistory) expire(now time.Time) { for h.Len() > 0 && h.min().exp.Before(now) { heap.Pop(h) @@ -424,6 +428,7 @@ func (h dialHistory) Swap(i, j int) { h[i], h[j] = h[j], h[i] } func (h *dialHistory) Push(x interface{}) { *h = append(*h, x.(pastDial)) } + func (h *dialHistory) Pop() interface{} { old := *h n := len(old) diff --git a/p2p/discv5/database_test.go b/p2p/discv5/database_test.go index 2b86dc9cec..20401f2a04 100644 --- a/p2p/discv5/database_test.go +++ b/p2p/discv5/database_test.go @@ -40,7 +40,8 @@ var nodeDBKeyTests = []struct { { id: MustHexID("0x1dd9d65c4552b5eb43d5ad55a2ee3f56c6cbc1c64a5c8d659f51fcd51bace24351232b8d7821617d2b29b54b81cdefb9b3e9c37d7fd5f63270bcc9e1a6f6a439"), field: ":discover", - key: []byte{0x6e, 0x3a, // prefix + key: []byte{ + 0x6e, 0x3a, // prefix 0x1d, 0xd9, 0xd6, 0x5c, 0x45, 0x52, 0xb5, 0xeb, // node id 0x43, 0xd5, 0xad, 0x55, 0xa2, 0xee, 0x3f, 0x56, // 0xc6, 0xcb, 0xc1, 0xc6, 0x4a, 0x5c, 0x8d, 0x65, // diff --git a/p2p/discv5/net.go b/p2p/discv5/net.go index de7d8de6aa..ecd8404cb0 100644 --- a/p2p/discv5/net.go +++ b/p2p/discv5/net.go @@ -48,9 +48,7 @@ const ( const testTopic = "foo" -const ( - printTestImgLogs = false -) +const printTestImgLogs = false // Network manages the table and all protocol interaction. type Network struct { @@ -419,7 +417,7 @@ loop: // Ingress packet handling. case pkt := <-net.read: - //fmt.Println("read", pkt.ev) + // fmt.Println("read", pkt.ev) log.Trace("<-net.read") n := net.internNode(&pkt) prestate := n.state @@ -513,7 +511,7 @@ loop: case <-nextRegisterTime: log.Trace("<-nextRegisterTime") net.ticketStore.ticketRegistered(*nextTicket) - //fmt.Println("sendTopicRegister", nextTicket.t.node.addr().String(), nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong) + // fmt.Println("sendTopicRegister", nextTicket.t.node.addr().String(), nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong) net.conn.sendTopicRegister(nextTicket.t.node, nextTicket.t.topics, nextTicket.idx, nextTicket.t.pong) case req := <-net.topicSearchReq: @@ -1027,10 +1025,10 @@ func init() { // handle processes packets sent by n and events related to n. func (net *Network) handle(n *Node, ev nodeEvent, pkt *ingressPacket) error { - //fmt.Println("handle", n.addr().String(), n.state, ev) + // fmt.Println("handle", n.addr().String(), n.state, ev) if pkt != nil { if err := net.checkPacket(n, ev, pkt); err != nil { - //fmt.Println("check err:", err) + // fmt.Println("check err:", err) return err } // Start the background expiration goroutine after the first @@ -1047,7 +1045,7 @@ func (net *Network) handle(n *Node, ev nodeEvent, pkt *ingressPacket) error { } next, err := n.state.handle(net, n, ev, pkt) net.transition(n, next) - //fmt.Println("new state:", n.state) + // fmt.Println("new state:", n.state) return err } @@ -1103,9 +1101,9 @@ func (net *Network) abortTimedEvent(n *Node, ev nodeEvent) { } func (net *Network) ping(n *Node, addr *net.UDPAddr) { - //fmt.Println("ping", n.addr().String(), n.ID.String(), n.sha.Hex()) + // fmt.Println("ping", n.addr().String(), n.ID.String(), n.sha.Hex()) if n.pingEcho != nil || n.ID == net.tab.self.ID { - //fmt.Println(" not sent") + // fmt.Println(" not sent") return } log.Trace("Pinging remote node", "node", n.ID) @@ -1173,11 +1171,11 @@ func (net *Network) handleQueryEvent(n *Node, ev nodeEvent, pkt *ingressPacket) net.conn.sendNeighbours(n, results) return n.state, nil case topicRegisterPacket: - //fmt.Println("got topicRegisterPacket") + // fmt.Println("got topicRegisterPacket") regdata := pkt.data.(*topicRegister) pong, err := net.checkTopicRegister(regdata) if err != nil { - //fmt.Println(err) + // fmt.Println(err) return n.state, fmt.Errorf("bad waiting ticket: %v", err) } net.topictab.useTicket(n, pong.TicketSerial, regdata.Topics, int(regdata.Idx), pong.Expiration, pong.WaitPeriods) diff --git a/p2p/discv5/sim_test.go b/p2p/discv5/sim_test.go index 543faecd48..4d981360dd 100644 --- a/p2p/discv5/sim_test.go +++ b/p2p/discv5/sim_test.go @@ -84,14 +84,14 @@ func TestSimTopics(t *testing.T) { stop := make(chan struct{}) go net.RegisterTopic(testTopic, stop) go func() { - //time.Sleep(time.Second * 36000) + // time.Sleep(time.Second * 36000) time.Sleep(time.Second * 40000) close(stop) }() time.Sleep(time.Millisecond * 100) } // time.Sleep(time.Second * 10) - //time.Sleep(time.Second) + // time.Sleep(time.Second) /*if i%500 == 499 { time.Sleep(time.Second * 9501) } else { @@ -125,10 +125,10 @@ func TestSimTopics(t *testing.T) { }() */ time.Sleep(55000 * time.Second) - //launcher.Stop() + // launcher.Stop() sim.shutdown() - //sim.printStats() - //printNet.log.printLogs() + // sim.printStats() + // printNet.log.printLogs() } /*func testHierarchicalTopics(i int) []Topic { @@ -170,9 +170,9 @@ func TestSimTopicHierarchy(t *testing.T) { stop := make(chan struct{}) for i, net := range nets { - //if i < 256 { + // if i < 256 { for _, topic := range testHierarchicalTopics(i)[:5] { - //fmt.Println("reg", topic) + // fmt.Println("reg", topic) go net.RegisterTopic(topic, stop) } time.Sleep(time.Millisecond * 100) @@ -252,7 +252,6 @@ func (s *simulation) printStats() { fmt.Printf("*** Node %x\n", n.tab.self.ID[:8]) n.log.printLogs() }*/ - } func (s *simulation) randomNode() *Network { @@ -388,7 +387,7 @@ func (st *simTransport) sendFindnodeHash(remote *Node, target common.Hash) { } func (st *simTransport) sendTopicRegister(remote *Node, topics []Topic, idx int, pong []byte) { - //fmt.Println("send", topics, pong) + // fmt.Println("send", topics, pong) st.sendPacket(remote.ID, ingressPacket{ remoteID: st.sender, remoteAddr: st.senderAddr, diff --git a/p2p/discv5/table.go b/p2p/discv5/table.go index 4f4b2426f4..f28fe1527c 100644 --- a/p2p/discv5/table.go +++ b/p2p/discv5/table.go @@ -187,7 +187,7 @@ func (tab *Table) closest(target common.Hash, nresults int) *nodesByDistance { // bucket has space available, adding the node succeeds immediately. // Otherwise, the node is added to the replacement cache for the bucket. func (tab *Table) add(n *Node) (contested *Node) { - //fmt.Println("add", n.addr().String(), n.ID.String(), n.sha.Hex()) + // fmt.Println("add", n.addr().String(), n.ID.String(), n.sha.Hex()) if n.ID == tab.self.ID { return } @@ -244,7 +244,7 @@ outer: // delete removes an entry from the node table (used to evacuate // failed/non-bonded discovery peers). func (tab *Table) delete(node *Node) { - //fmt.Println("delete", node.addr().String(), node.ID.String(), node.sha.Hex()) + // fmt.Println("delete", node.addr().String(), node.ID.String(), node.sha.Hex()) bucket := tab.buckets[logdist(tab.self.sha, node.sha)] for i := range bucket.entries { if bucket.entries[i].ID == node.ID { diff --git a/p2p/discv5/table_test.go b/p2p/discv5/table_test.go index a29943dab9..a5ed10f8c8 100644 --- a/p2p/discv5/table_test.go +++ b/p2p/discv5/table_test.go @@ -172,6 +172,7 @@ func (t *pingRecorder) close() {} func (t *pingRecorder) waitping(from NodeID) error { return nil // remote always pings } + func (t *pingRecorder) ping(toid NodeID, toaddr *net.UDPAddr) error { t.pinged[toid] = true if t.responding[toid] { diff --git a/p2p/discv5/ticket.go b/p2p/discv5/ticket.go index ae4b18e7cd..65c8288132 100644 --- a/p2p/discv5/ticket.go +++ b/p2p/discv5/ticket.go @@ -336,7 +336,7 @@ func (s *ticketStore) addTicketRef(r ticketRef) { } tickets.nextLookup += mclock.AbsTime(collectFrequency) - //s.removeExcessTickets(topic) + // s.removeExcessTickets(topic) } func (s *ticketStore) nextFilteredTicket() (*ticketRef, time.Duration) { @@ -392,13 +392,13 @@ func (s *ticketStore) nextRegisterableTicket() (*ticketRef, time.Duration) { nextTicket ticketRef // uninitialized if this bucket is empty ) for _, tickets := range s.tickets { - //s.removeExcessTickets(topic) + // s.removeExcessTickets(topic) if len(tickets.buckets) != 0 { empty = false list := tickets.buckets[bucket] for _, ref := range list { - //debugLog(fmt.Sprintf(" nrt bucket = %d node = %x sn = %v wait = %v", bucket, ref.t.node.ID[:8], ref.t.serial, time.Duration(ref.topicRegTime()-now))) + // debugLog(fmt.Sprintf(" nrt bucket = %d node = %x sn = %v wait = %v", bucket, ref.t.node.ID[:8], ref.t.serial, time.Duration(ref.topicRegTime()-now))) if nextTicket.t == nil || ref.topicRegTime() < nextTicket.topicRegTime() { nextTicket = ref } @@ -554,7 +554,7 @@ func (s *ticketStore) addTicket(localTime mclock.AbsTime, pingHash []byte, ticke } if float64(wait) < float64(keepTicketConst)+float64(keepTicketExp)*rnd { // use the ticket to register this topic - //fmt.Println("addTicket", ticket.node.ID[:8], ticket.node.addr().String(), ticket.serial, ticket.pong) + // fmt.Println("addTicket", ticket.node.ID[:8], ticket.node.addr().String(), ticket.serial, ticket.pong) s.addTicketRef(ticketRef{ticket, topicIdx}) } } @@ -618,7 +618,7 @@ func (s *ticketStore) cleanupTopicQueries(now mclock.AbsTime) { func (s *ticketStore) gotTopicNodes(from *Node, hash common.Hash, nodes []rpcNode) (timeout bool) { now := mclock.Now() - //fmt.Println("got", from.addr().String(), hash, len(nodes)) + // fmt.Println("got", from.addr().String(), hash, len(nodes)) qq := s.queriesSent[from] if qq == nil { return true @@ -634,7 +634,7 @@ func (s *ticketStore) gotTopicNodes(from *Node, hash common.Hash, nodes []rpcNod s.radius[q.lookup.topic].adjust(now, q.lookup.target, from.sha, inside) chn := s.searchTopicMap[q.lookup.topic].foundChn if chn == nil { - //fmt.Println("no channel") + // fmt.Println("no channel") return false } for _, node := range nodes { @@ -834,9 +834,9 @@ func (r *topicRadius) recalcRadius() (radius uint64, radiusLookup int) { r.buckets[i].update(now) v += r.buckets[i].weights[trOutside] - r.buckets[i].weights[trInside] r.buckets[i].value = v - //fmt.Printf("%v %v | ", v, r.buckets[i].weights[trNoAdjust]) + // fmt.Printf("%v %v | ", v, r.buckets[i].weights[trNoAdjust]) } - //fmt.Println() + // fmt.Println() slopeCross := -1 for i, b := range r.buckets { v := b.value @@ -884,7 +884,7 @@ func (r *topicRadius) recalcRadius() (radius uint64, radiusLookup int) { } } - //fmt.Println("mb", maxBucket, "sc", slopeCross, "mrb", minRadBucket, "ll", lookupLeft, "lr", lookupRight, "mv", maxValue) + // fmt.Println("mb", maxBucket, "sc", slopeCross, "mrb", minRadBucket, "ll", lookupLeft, "lr", lookupRight, "mv", maxValue) if radiusLookup == -1 { // no more radius lookups needed at the moment, return a radius @@ -945,7 +945,7 @@ func (r *topicRadius) adjustWithTicket(now mclock.AbsTime, targetHash common.Has func (r *topicRadius) adjust(now mclock.AbsTime, targetHash, addrHash common.Hash, inside float64) { bucket := r.getBucketIdx(addrHash) - //fmt.Println("adjust", bucket, len(r.buckets), inside) + // fmt.Println("adjust", bucket, len(r.buckets), inside) if bucket >= len(r.buckets) { return } diff --git a/p2p/discv5/topic.go b/p2p/discv5/topic.go index 609a41297f..94c45a3429 100644 --- a/p2p/discv5/topic.go +++ b/p2p/discv5/topic.go @@ -121,7 +121,7 @@ func (t *topicTable) checkDeleteTopic(topic Topic) { func (t *topicTable) getOrNewNode(node *Node) *nodeInfo { n := t.nodes[node] if n == nil { - //fmt.Printf("newNode %016x %016x\n", t.self.sha[:8], node.sha[:8]) + // fmt.Printf("newNode %016x %016x\n", t.self.sha[:8], node.sha[:8]) var issued, used uint32 if t.db != nil { issued, used = t.db.fetchTopicRegTickets(node.ID) @@ -138,7 +138,7 @@ func (t *topicTable) getOrNewNode(node *Node) *nodeInfo { func (t *topicTable) checkDeleteNode(node *Node) { if n, ok := t.nodes[node]; ok && len(n.entries) == 0 && n.noRegUntil < mclock.Now() { - //fmt.Printf("deleteNode %016x %016x\n", t.self.sha[:8], node.sha[:8]) + // fmt.Printf("deleteNode %016x %016x\n", t.self.sha[:8], node.sha[:8]) delete(t.nodes, node) } } @@ -237,7 +237,7 @@ func (t *topicTable) deleteEntry(e *topicEntry) { // It is assumed that topics and waitPeriods have the same length. func (t *topicTable) useTicket(node *Node, serialNo uint32, topics []Topic, idx int, issueTime uint64, waitPeriods []uint32) (registered bool) { log.Trace("Using discovery ticket", "serial", serialNo, "topics", topics, "waits", waitPeriods) - //fmt.Println("useTicket", serialNo, topics, waitPeriods) + // fmt.Println("useTicket", serialNo, topics, waitPeriods) t.collectGarbage() n := t.getOrNewNode(node) diff --git a/p2p/discv5/udp.go b/p2p/discv5/udp.go index ff5ed983ba..9a23542519 100644 --- a/p2p/discv5/udp.go +++ b/p2p/discv5/udp.go @@ -328,10 +328,10 @@ func (t *udp) sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node) } func (t *udp) sendPacket(toid NodeID, toaddr *net.UDPAddr, ptype byte, req interface{}) (hash []byte, err error) { - //fmt.Println("sendPacket", nodeEvent(ptype), toaddr.String(), toid.String()) + // fmt.Println("sendPacket", nodeEvent(ptype), toaddr.String(), toid.String()) packet, hash, err := encodePacket(t.priv, ptype, req) if err != nil { - //fmt.Println(err) + // fmt.Println(err) return hash, err } log.Trace(fmt.Sprintf(">>> %v to %x@%v", nodeEvent(ptype), toid[:8], toaddr)) @@ -340,7 +340,7 @@ func (t *udp) sendPacket(toid NodeID, toaddr *net.UDPAddr, ptype byte, req inter } else { egressTrafficMeter.Mark(int64(nbytes)) } - //fmt.Println(err) + // fmt.Println(err) return hash, err } @@ -395,7 +395,7 @@ func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error { pkt := ingressPacket{remoteAddr: from} if err := decodePacket(buf, &pkt); err != nil { log.Debug(fmt.Sprintf("Bad packet from %v: %v", from, err)) - //fmt.Println("bad packet", err) + // fmt.Println("bad packet", err) return err } t.net.reqReadPacket(pkt) diff --git a/p2p/discv5/udp_test.go b/p2p/discv5/udp_test.go index 62184aa9d3..5f6226c2ea 100644 --- a/p2p/discv5/udp_test.go +++ b/p2p/discv5/udp_test.go @@ -36,9 +36,8 @@ func init() { } // shared test variables -var ( - testLocal = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6} -) + +var testLocal = rpcEndpoint{IP: net.ParseIP("3.3.3.3").To4(), UDP: 5, TCP: 6} // type udpTest struct { // t *testing.T diff --git a/p2p/peer.go b/p2p/peer.go index af019d07a8..9578c35ba5 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -33,9 +33,7 @@ import ( "github.com/ethereum/go-ethereum/rlp" ) -var ( - ErrShuttingDown = errors.New("shutting down") -) +var ErrShuttingDown = errors.New("shutting down") const ( baseProtocolVersion = 5 diff --git a/p2p/protocols/accounting_api.go b/p2p/protocols/accounting_api.go index 48e2af9fea..bb83e2ac3e 100644 --- a/p2p/protocols/accounting_api.go +++ b/p2p/protocols/accounting_api.go @@ -1,8 +1,6 @@ package protocols -import ( - "errors" -) +import "errors" // Textual version number of accounting API const AccountingVersion = "1.0" diff --git a/p2p/protocols/accounting_simulation_test.go b/p2p/protocols/accounting_simulation_test.go index 464b598920..36c7f4f7a8 100644 --- a/p2p/protocols/accounting_simulation_test.go +++ b/p2p/protocols/accounting_simulation_test.go @@ -41,9 +41,7 @@ import ( "github.com/ethereum/go-ethereum/p2p/simulations/adapters" ) -const ( - content = "123456789" -) +const content = "123456789" var ( nodes = flag.Int("nodes", 30, "number of nodes to create (default 30)") @@ -58,31 +56,31 @@ func init() { log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*loglevel), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(!*rawlog)))) } -//TestAccountingSimulation runs a p2p/simulations simulation -//It creates a *nodes number of nodes, connects each one with each other, -//then sends out a random selection of messages up to *msgs amount of messages -//from the test protocol spec. -//The spec has some accounted messages defined through the Prices interface. -//The test does accounting for all the message exchanged, and then checks -//that every node has the same balance with a peer, but with opposite signs. -//Balance(AwithB) = 0 - Balance(BwithA) or Abs|Balance(AwithB)| == Abs|Balance(BwithA)| +// TestAccountingSimulation runs a p2p/simulations simulation +// It creates a *nodes number of nodes, connects each one with each other, +// then sends out a random selection of messages up to *msgs amount of messages +// from the test protocol spec. +// The spec has some accounted messages defined through the Prices interface. +// The test does accounting for all the message exchanged, and then checks +// that every node has the same balance with a peer, but with opposite signs. +// Balance(AwithB) = 0 - Balance(BwithA) or Abs|Balance(AwithB)| == Abs|Balance(BwithA)| func TestAccountingSimulation(t *testing.T) { - //setup the balances objects for every node + // setup the balances objects for every node bal := newBalances(*nodes) - //setup the metrics system or tests will fail trying to write metrics + // setup the metrics system or tests will fail trying to write metrics dir, err := ioutil.TempDir("", "account-sim") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) SetupAccountingMetrics(1*time.Second, filepath.Join(dir, "metrics.db")) - //define the node.Service for this test + // define the node.Service for this test services := adapters.Services{ "accounting": func(ctx *adapters.ServiceContext) (node.Service, error) { return bal.newNode(), nil }, } - //setup the simulation + // setup the simulation adapter := adapters.NewSimAdapter(services) net := simulations.NewNetwork(adapter, &simulations.NetworkConfig{DefaultService: "accounting"}) defer net.Shutdown() @@ -159,8 +157,8 @@ func TestAccountingSimulation(t *testing.T) { // (n entries in the array will not be filled - // the balance of a node with itself) type matrix struct { - n int //number of nodes - m []int64 //array of balances + n int // number of nodes + m []int64 // array of balances lock sync.Mutex } @@ -187,9 +185,9 @@ func (m *matrix) add(i, j int, v int64) error { // check that the balances are symmetric: // balance of node i with node j is the same as j with i but with inverted signs func (m *matrix) symmetric() error { - //iterate all nodes + // iterate all nodes for i := 0; i < m.n; i++ { - //iterate starting +1 + // iterate starting +1 for j := i + 1; j < m.n; j++ { log.Debug("bal", "1", i, "2", j, "i,j", m.m[i*m.n+j], "j,i", m.m[j*m.n+i]) if m.m[i*m.n+j] != -m.m[j*m.n+i] { @@ -222,7 +220,7 @@ func (b *balances) newNode() *testNode { return &testNode{ bal: b, i: b.i, - peers: make([]*testPeer, b.n), //a node will be connected to n-1 peers + peers: make([]*testPeer, b.n), // a node will be connected to n-1 peers } } @@ -237,26 +235,26 @@ type testNode struct { // do the accounting for the peer's test protocol // testNode implements protocols.Balance func (t *testNode) Add(a int64, p *Peer) error { - //get the index for the remote peer + // get the index for the remote peer remote := t.bal.id2n[p.ID()] log.Debug("add", "local", t.i, "remote", remote, "amount", a) return t.bal.add(t.i, remote, a) } -//run the p2p protocol -//for every node, represented by testNode, create a remote testPeer +// run the p2p protocol +// for every node, represented by testNode, create a remote testPeer func (t *testNode) run(p *p2p.Peer, rw p2p.MsgReadWriter) error { spec := createTestSpec() - //create accounting hook + // create accounting hook spec.Hook = NewAccounting(t, &dummyPrices{}) - //create a peer for this node + // create a peer for this node tp := &testPeer{NewPeer(p, rw, spec), t.i, t.bal.id2n[p.ID()], t.bal.wg} t.lock.Lock() t.peers[t.bal.id2n[p.ID()]] = tp t.peerCount++ if t.peerCount == t.bal.n-1 { - //when all peer connections are established, start sending messages from this peer + // when all peer connections are established, start sending messages from this peer go t.send() } t.lock.Unlock() @@ -279,7 +277,7 @@ type testPeer struct { func (t *testNode) send() { log.Debug("start sending") for i := 0; i < *msgs; i++ { - //determine randomly to which peer to send + // determine randomly to which peer to send whom := rand.Intn(t.bal.n - 1) if whom >= t.i { whom++ @@ -288,7 +286,7 @@ func (t *testNode) send() { p := t.peers[whom] t.lock.Unlock() - //determine a random message from the spec's messages to be sent + // determine a random message from the spec's messages to be sent which := rand.Intn(len(p.spec.Messages)) msg := p.spec.Messages[which] switch msg.(type) { diff --git a/p2p/protocols/accounting_test.go b/p2p/protocols/accounting_test.go index 3810ae2c9b..389be90277 100644 --- a/p2p/protocols/accounting_test.go +++ b/p2p/protocols/accounting_test.go @@ -24,65 +24,65 @@ import ( "github.com/ethereum/go-ethereum/rlp" ) -//dummy Balance implementation +// dummy Balance implementation type dummyBalance struct { amount int64 peer *Peer } -//dummy Prices implementation +// dummy Prices implementation type dummyPrices struct{} -//a dummy message which needs size based accounting -//sender pays +// a dummy message which needs size based accounting +// sender pays type perBytesMsgSenderPays struct { Content string } -//a dummy message which needs size based accounting -//receiver pays +// a dummy message which needs size based accounting +// receiver pays type perBytesMsgReceiverPays struct { Content string } -//a dummy message which is paid for per unit -//sender pays +// a dummy message which is paid for per unit +// sender pays type perUnitMsgSenderPays struct{} -//receiver pays +// receiver pays type perUnitMsgReceiverPays struct{} -//a dummy message which has zero as its price +// a dummy message which has zero as its price type zeroPriceMsg struct{} -//a dummy message which has no accounting +// a dummy message which has no accounting type nilPriceMsg struct{} -//return the price for the defined messages +// return the price for the defined messages func (d *dummyPrices) Price(msg interface{}) *Price { switch msg.(type) { - //size based message cost, receiver pays + // size based message cost, receiver pays case *perBytesMsgReceiverPays: return &Price{ PerByte: true, Value: uint64(100), Payer: Receiver, } - //size based message cost, sender pays + // size based message cost, sender pays case *perBytesMsgSenderPays: return &Price{ PerByte: true, Value: uint64(100), Payer: Sender, } - //unitary cost, receiver pays + // unitary cost, receiver pays case *perUnitMsgReceiverPays: return &Price{ PerByte: false, Value: uint64(99), Payer: Receiver, } - //unitary cost, sender pays + // unitary cost, sender pays case *perUnitMsgSenderPays: return &Price{ PerByte: false, @@ -101,7 +101,7 @@ func (d *dummyPrices) Price(msg interface{}) *Price { return nil } -//dummy accounting implementation, only stores values for later check +// dummy accounting implementation, only stores values for later check func (d *dummyBalance) Add(amount int64, peer *Peer) error { d.amount = amount d.peer = peer @@ -115,20 +115,20 @@ type testCase struct { recvResult int64 } -//lowest level unit test +// lowest level unit test func TestBalance(t *testing.T) { - //create instances + // create instances balance := &dummyBalance{} prices := &dummyPrices{} - //create the spec + // create the spec spec := createTestSpec() - //create the accounting hook for the spec + // create the accounting hook for the spec acc := NewAccounting(balance, prices) - //create a peer + // create a peer id := adapters.RandomNodeConfig().ID p := p2p.NewPeer(id, "testPeer", nil) peer := NewPeer(p, &dummyRW{}, spec) - //price depends on size, receiver pays + // price depends on size, receiver pays msg := &perBytesMsgReceiverPays{Content: "testBalance"} size, _ := rlp.EncodeToBytes(msg) @@ -178,7 +178,7 @@ func checkAccountingTestCases(t *testing.T, cases []testCase, acc *Accounting, p for _, c := range cases { var err error var expectedResult int64 - //reset balance before every check + // reset balance before every check balance.amount = 0 if send { err = acc.Send(peer, c.size, c.msg) @@ -204,7 +204,7 @@ func checkResults(t *testing.T, err error, balance *dummyBalance, peer *Peer, re } } -//create a test spec +// create a test spec func createTestSpec() *Spec { spec := &Spec{ Name: "test", diff --git a/p2p/protocols/protocol.go b/p2p/protocols/protocol.go index 1600a11f99..68b925b02c 100644 --- a/p2p/protocols/protocol.go +++ b/p2p/protocols/protocol.go @@ -122,13 +122,13 @@ type WrappedMsg struct { Payload []byte } -//For accounting, the design is to allow the Spec to describe which and how its messages are priced -//To access this functionality, we provide a Hook interface which will call accounting methods -//NOTE: there could be more such (horizontal) hooks in the future +// For accounting, the design is to allow the Spec to describe which and how its messages are priced +// To access this functionality, we provide a Hook interface which will call accounting methods +// NOTE: there could be more such (horizontal) hooks in the future type Hook interface { - //A hook for sending messages + // A hook for sending messages Send(peer *Peer, size uint32, msg interface{}) error - //A hook for receiving messages + // A hook for receiving messages Receive(peer *Peer, size uint32, msg interface{}) error } @@ -151,7 +151,7 @@ type Spec struct { // each message must have a single unique data type Messages []interface{} - //hook for accounting (could be extended to multiple hooks in the future) + // hook for accounting (could be extended to multiple hooks in the future) Hook Hook initOnce sync.Once @@ -287,7 +287,7 @@ func (p *Peer) Send(ctx context.Context, msg interface{}) error { Payload: r, } - //if the accounting hook is set, call it + // if the accounting hook is set, call it if p.spec.Hook != nil { err := p.spec.Hook.Send(p, wmsg.Size, msg) if err != nil { @@ -358,7 +358,7 @@ func (p *Peer) handleIncoming(handle func(ctx context.Context, msg interface{}) return errorf(ErrDecode, "<= %v: %v", msg, err) } - //if the accounting hook is set, call it + // if the accounting hook is set, call it if p.spec.Hook != nil { err := p.spec.Hook.Receive(p, wmsg.Size, val) if err != nil { diff --git a/p2p/protocols/protocol_test.go b/p2p/protocols/protocol_test.go index 9ac76ea2fd..a27f721d50 100644 --- a/p2p/protocols/protocol_test.go +++ b/p2p/protocols/protocol_test.go @@ -153,7 +153,6 @@ func protocolTester(pp *p2ptest.TestPeerPool) *p2ptest.ProtocolTester { } func protoHandshakeExchange(id enode.ID, proto *protoHandshake) []p2ptest.Exchange { - return []p2ptest.Exchange{ { Expects: []p2ptest.Expect{ @@ -251,7 +250,8 @@ func TestProtocolHook(t *testing.T) { peer := NewPeer(p, rw, spec) ctx := context.TODO() err := peer.Send(ctx, &dummyMsg{ - Content: "handshake"}) + Content: "handshake", + }) if err != nil { t.Fatal(err) @@ -294,7 +294,7 @@ func TestProtocolHook(t *testing.T) { if peerId := testHook.peer.ID(); peerId != tester.Nodes[0].ID() && peerId != tester.Nodes[1].ID() { t.Fatalf("Expected peer ID to be set correctly, but it is not (got %v, exp %v or %v", peerId, tester.Nodes[0].ID(), tester.Nodes[1].ID()) } - if testHook.size != 11 { //11 is the length of the encoded message + if testHook.size != 11 { // 11 is the length of the encoded message t.Fatalf("Expected size to be %d, but it is %d ", 1, testHook.size) } testHook.mu.Unlock() @@ -325,7 +325,7 @@ func TestProtocolHook(t *testing.T) { if testHook.peer == nil || testHook.peer.ID() != tester.Nodes[1].ID() { t.Fatal("Expected peer ID to be set correctly, but it is not") } - if testHook.size != 10 { //11 is the length of the encoded message + if testHook.size != 10 { // 11 is the length of the encoded message t.Fatalf("Expected size to be %d, but it is %d ", 1, testHook.size) } testHook.mu.Unlock() @@ -350,25 +350,25 @@ func TestProtocolHook(t *testing.T) { } } -//We need to test that if the hook is not defined, then message infrastructure +// We need to test that if the hook is not defined, then message infrastructure //(send,receive) still works func TestNoHook(t *testing.T) { - //create a test spec + // create a test spec spec := createTestSpec() - //a random node + // a random node id := adapters.RandomNodeConfig().ID - //a peer + // a peer p := p2p.NewPeer(id, "testPeer", nil) rw := &dummyRW{} peer := NewPeer(p, rw, spec) ctx := context.TODO() msg := &perBytesMsgSenderPays{Content: "testBalance"} - //send a message + // send a message if err := peer.Send(ctx, msg); err != nil { t.Fatal(err) } - //simulate receiving a message + // simulate receiving a message rw.msg = msg handler := func(ctx context.Context, msg interface{}) error { return nil @@ -392,7 +392,6 @@ func TestProtoHandshakeSuccess(t *testing.T) { } func moduleHandshakeExchange(id enode.ID, resp uint) []p2ptest.Exchange { - return []p2ptest.Exchange{ { Expects: []p2ptest.Expect{ @@ -447,7 +446,6 @@ func TestModuleHandshakeSuccess(t *testing.T) { // testing complex interactions over multiple peers, relaying, dropping func testMultiPeerSetup(a, b enode.ID) []p2ptest.Exchange { - return []p2ptest.Exchange{ { Label: "primary handshake", @@ -492,10 +490,13 @@ func testMultiPeerSetup(a, b enode.ID) []p2ptest.Exchange { }, }, - {Label: "alternative module handshake", Triggers: []p2ptest.Trigger{{Code: 1, Msg: &hs0{41}, Peer: a}, - {Code: 1, Msg: &hs0{41}, Peer: b}}}, + {Label: "alternative module handshake", Triggers: []p2ptest.Trigger{ + {Code: 1, Msg: &hs0{41}, Peer: a}, + {Code: 1, Msg: &hs0{41}, Peer: b}, + }}, {Label: "repeated module handshake", Triggers: []p2ptest.Trigger{{Code: 1, Msg: &hs0{1}, Peer: a}}}, - {Label: "receiving repeated module handshake", Expects: []p2ptest.Expect{{Code: 1, Msg: &hs0{43}, Peer: a}}}} + {Label: "receiving repeated module handshake", Expects: []p2ptest.Expect{{Code: 1, Msg: &hs0{43}, Peer: a}}}, + } } func runMultiplePeers(t *testing.T, peer int, errs ...error) { @@ -570,8 +571,8 @@ WAIT: if pp.Has(s.Nodes[peer].ID()) { t.Fatalf("peer test-%v not dropped: %v (%v)", peer, pp, s.Nodes) } - } + func TestMultiplePeersDropSelf(t *testing.T) { runMultiplePeers(t, 0, fmt.Errorf("subprotocol error"), @@ -586,9 +587,9 @@ func TestMultiplePeersDropOther(t *testing.T) { ) } -//dummy implementation of a MsgReadWriter -//this allows for quick and easy unit tests without -//having to build up the complete protocol +// dummy implementation of a MsgReadWriter +// this allows for quick and easy unit tests without +// having to build up the complete protocol type dummyRW struct { msg interface{} size uint32 diff --git a/p2p/protocols/reporter.go b/p2p/protocols/reporter.go index 9612b4a4d5..409ef4f1cb 100644 --- a/p2p/protocols/reporter.go +++ b/p2p/protocols/reporter.go @@ -26,14 +26,14 @@ import ( "github.com/syndtr/goleveldb/leveldb" ) -//AccountMetrics abstracts away the metrics DB and -//the reporter to persist metrics +// AccountMetrics abstracts away the metrics DB and +// the reporter to persist metrics type AccountingMetrics struct { reporter *reporter } -//Close will be called when the node is being shutdown -//for a graceful cleanup +// Close will be called when the node is being shutdown +// for a graceful cleanup func (am *AccountingMetrics) Close() { close(am.reporter.quit) // wait for reporter loop to finish saving metrics @@ -46,32 +46,32 @@ func (am *AccountingMetrics) Close() { am.reporter.db.Close() } -//reporter is an internal structure used to write p2p accounting related -//metrics to a LevelDB. It will periodically write the accrued metrics to the DB. +// reporter is an internal structure used to write p2p accounting related +// metrics to a LevelDB. It will periodically write the accrued metrics to the DB. type reporter struct { - reg metrics.Registry //the registry for these metrics (independent of other metrics) - interval time.Duration //duration at which the reporter will persist metrics - db *leveldb.DB //the actual DB - quit chan struct{} //quit the reporter loop - done chan struct{} //signal that reporter loop is done + reg metrics.Registry // the registry for these metrics (independent of other metrics) + interval time.Duration // duration at which the reporter will persist metrics + db *leveldb.DB // the actual DB + quit chan struct{} // quit the reporter loop + done chan struct{} // signal that reporter loop is done } -//NewMetricsDB creates a new LevelDB instance used to persist metrics defined -//inside p2p/protocols/accounting.go +// NewMetricsDB creates a new LevelDB instance used to persist metrics defined +// inside p2p/protocols/accounting.go func NewAccountingMetrics(r metrics.Registry, d time.Duration, path string) *AccountingMetrics { var val = make([]byte, 8) var err error - //Create the LevelDB + // Create the LevelDB db, err := leveldb.OpenFile(path, nil) if err != nil { log.Error(err.Error()) return nil } - //Check for all defined metrics that there is a value in the DB - //If there is, assign it to the metric. This means that the node - //has been running before and that metrics have been persisted. + // Check for all defined metrics that there is a value in the DB + // If there is, assign it to the metric. This means that the node + // has been running before and that metrics have been persisted. metricsMap := map[string]metrics.Counter{ "account.balance.credit": mBalanceCredit, "account.balance.debit": mBalanceDebit, @@ -82,19 +82,19 @@ func NewAccountingMetrics(r metrics.Registry, d time.Duration, path string) *Acc "account.peerdrops": mPeerDrops, "account.selfdrops": mSelfDrops, } - //iterate the map and get the values + // iterate the map and get the values for key, metric := range metricsMap { val, err = db.Get([]byte(key), nil) - //until the first time a value is being written, - //this will return an error. - //it could be beneficial though to log errors later, - //but that would require a different logic + // until the first time a value is being written, + // this will return an error. + // it could be beneficial though to log errors later, + // but that would require a different logic if err == nil { metric.Inc(int64(binary.BigEndian.Uint64(val))) } } - //create the reporter + // create the reporter rep := &reporter{ reg: r, interval: d, @@ -103,7 +103,7 @@ func NewAccountingMetrics(r metrics.Registry, d time.Duration, path string) *Acc done: make(chan struct{}), } - //run the go routine + // run the go routine go rep.run() m := &AccountingMetrics{ @@ -113,7 +113,7 @@ func NewAccountingMetrics(r metrics.Registry, d time.Duration, path string) *Acc return m } -//run is the goroutine which periodically sends the metrics to the configured LevelDB +// run is the goroutine which periodically sends the metrics to the configured LevelDB func (r *reporter) run() { // signal that the reporter loop is done defer close(r.done) @@ -123,16 +123,16 @@ func (r *reporter) run() { for { select { case <-intervalTicker.C: - //at each tick send the metrics + // at each tick send the metrics if err := r.save(); err != nil { log.Error("unable to send metrics to LevelDB", "err", err) - //If there is an error in writing, exit the routine; we assume here that the error is - //severe and don't attempt to write again. - //Also, this should prevent leaking when the node is stopped + // If there is an error in writing, exit the routine; we assume here that the error is + // severe and don't attempt to write again. + // Also, this should prevent leaking when the node is stopped return } case <-r.quit: - //graceful shutdown + // graceful shutdown if err := r.save(); err != nil { log.Error("unable to send metrics to LevelDB", "err", err) } @@ -141,15 +141,15 @@ func (r *reporter) run() { } } -//send the metrics to the DB +// send the metrics to the DB func (r *reporter) save() error { - //create a LevelDB Batch + // create a LevelDB Batch batch := leveldb.Batch{} - //for each metric in the registry (which is independent)... + // for each metric in the registry (which is independent)... r.reg.Each(func(name string, i interface{}) { metric, ok := i.(metrics.Counter) if ok { - //assuming every metric here to be a Counter (separate registry) + // assuming every metric here to be a Counter (separate registry) //...create a snapshot... ms := metric.Snapshot() byteVal := make([]byte, 8) diff --git a/p2p/protocols/reporter_test.go b/p2p/protocols/reporter_test.go index 9b0da09b79..1b8c996df1 100644 --- a/p2p/protocols/reporter_test.go +++ b/p2p/protocols/reporter_test.go @@ -26,51 +26,51 @@ import ( "github.com/ethereum/go-ethereum/log" ) -//TestReporter tests that the metrics being collected for p2p accounting -//are being persisted and available after restart of a node. -//It simulates restarting by just recreating the DB as if the node had restarted. +// TestReporter tests that the metrics being collected for p2p accounting +// are being persisted and available after restart of a node. +// It simulates restarting by just recreating the DB as if the node had restarted. func TestReporter(t *testing.T) { - //create a test directory + // create a test directory dir, err := ioutil.TempDir("", "reporter-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) - //setup the metrics + // setup the metrics log.Debug("Setting up metrics first time") reportInterval := 2 * time.Millisecond metrics := SetupAccountingMetrics(reportInterval, filepath.Join(dir, "test.db")) log.Debug("Done.") - //change metrics + // change metrics mBalanceCredit.Inc(12) mBytesCredit.Inc(34) mMsgDebit.Inc(9) - //store expected metrics + // store expected metrics expectedBalanceCredit := mBalanceCredit.Count() expectedBytesCredit := mBytesCredit.Count() expectedMsgDebit := mMsgDebit.Count() - //give the reporter time to write the metrics to DB + // give the reporter time to write the metrics to DB time.Sleep(20 * time.Millisecond) - //close the DB also, or we can't create a new one + // close the DB also, or we can't create a new one metrics.Close() - //clear the metrics - this effectively simulates the node having shut down... + // clear the metrics - this effectively simulates the node having shut down... mBalanceCredit.Clear() mBytesCredit.Clear() mMsgDebit.Clear() - //setup the metrics again + // setup the metrics again log.Debug("Setting up metrics second time") metrics = SetupAccountingMetrics(reportInterval, filepath.Join(dir, "test.db")) defer metrics.Close() log.Debug("Done.") - //now check the metrics, they should have the same value as before "shutdown" + // now check the metrics, they should have the same value as before "shutdown" if mBalanceCredit.Count() != expectedBalanceCredit { t.Fatalf("Expected counter to be %d, but is %d", expectedBalanceCredit, mBalanceCredit.Count()) } diff --git a/p2p/server.go b/p2p/server.go index 566f01ffc5..b0ec3b9e1f 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -807,6 +807,7 @@ func (srv *Server) encHandshakeChecks(peers map[enode.ID]*Peer, inboundCount int func (srv *Server) maxInboundConns() int { return srv.MaxPeers - srv.maxDialedConns() } + func (srv *Server) maxDialedConns() int { if srv.NoDiscovery || srv.NoDial { return 0 diff --git a/p2p/server_test.go b/p2p/server_test.go index f665c14245..c6c91c8f21 100644 --- a/p2p/server_test.go +++ b/p2p/server_test.go @@ -331,11 +331,14 @@ type taskgen struct { func (tg taskgen) newTasks(running int, peers map[enode.ID]*Peer, now time.Time) []task { return tg.newFunc(running, peers) } + func (tg taskgen) taskDone(t task, now time.Time) { tg.doneFunc(t) } + func (tg taskgen) addStatic(*enode.Node) { } + func (tg taskgen) removeStatic(*enode.Node) { } @@ -589,6 +592,7 @@ func (c *setupTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, } return &c.phs, nil } + func (c *setupTransport) close(err error) { c.calls += "close," c.closeErr = err @@ -598,6 +602,7 @@ func (c *setupTransport) close(err error) { func (c *setupTransport) WriteMsg(Msg) error { panic("WriteMsg called on setupTransport") } + func (c *setupTransport) ReadMsg() (Msg, error) { panic("ReadMsg called on setupTransport") } diff --git a/p2p/simulations/connect.go b/p2p/simulations/connect.go index ede96b34c1..d77439d1de 100644 --- a/p2p/simulations/connect.go +++ b/p2p/simulations/connect.go @@ -23,9 +23,7 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" ) -var ( - ErrNodeNotFound = errors.New("node not found") -) +var ErrNodeNotFound = errors.New("node not found") // ConnectToLastNode connects the node with provided NodeID // to the last node that is up, and avoiding connection to self. diff --git a/p2p/simulations/events.go b/p2p/simulations/events.go index 984c2e088f..f9a2d223cb 100644 --- a/p2p/simulations/events.go +++ b/p2p/simulations/events.go @@ -59,7 +59,7 @@ type Event struct { // Msg is set if the type is EventTypeMsg Msg *Msg `json:"msg,omitempty"` - //Optionally provide data (currently for simulation frontends only) + // Optionally provide data (currently for simulation frontends only) Data interface{} `json:"data"` } diff --git a/p2p/simulations/http.go b/p2p/simulations/http.go index 1f44cc6675..225c074d0b 100644 --- a/p2p/simulations/http.go +++ b/p2p/simulations/http.go @@ -366,7 +366,6 @@ func (s *Server) StopMocker(w http.ResponseWriter, req *http.Request) { // GetMockerList returns a list of available mockers func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request) { - list := GetMockerList() s.JSON(w, http.StatusOK, list) } diff --git a/p2p/simulations/http_test.go b/p2p/simulations/http_test.go index ed43c0ed76..a333dfbef8 100644 --- a/p2p/simulations/http_test.go +++ b/p2p/simulations/http_test.go @@ -38,9 +38,7 @@ import ( "github.com/mattn/go-colorable" ) -var ( - loglevel = flag.Int("loglevel", 2, "verbosity of logs") -) +var loglevel = flag.Int("loglevel", 2, "verbosity of logs") func init() { flag.Parse() @@ -202,6 +200,7 @@ func (t *testService) RunDum(p *p2p.Peer, rw p2p.MsgReadWriter) error { } } } + func (t *testService) RunPrb(p *p2p.Peer, rw p2p.MsgReadWriter) error { peer := t.peer(p.ID()) diff --git a/p2p/simulations/mocker.go b/p2p/simulations/mocker.go index 8ce777a010..32ea764ede 100644 --- a/p2p/simulations/mocker.go +++ b/p2p/simulations/mocker.go @@ -29,20 +29,20 @@ import ( "github.com/ethereum/go-ethereum/p2p/simulations/adapters" ) -//a map of mocker names to its function +// a map of mocker names to its function var mockerList = map[string]func(net *Network, quit chan struct{}, nodeCount int){ "startStop": startStop, "probabilistic": probabilistic, "boot": boot, } -//Lookup a mocker by its name, returns the mockerFn +// Lookup a mocker by its name, returns the mockerFn func LookupMocker(mockerType string) func(net *Network, quit chan struct{}, nodeCount int) { return mockerList[mockerType] } -//Get a list of mockers (keys of the map) -//Useful for frontend to build available mocker selection +// Get a list of mockers (keys of the map) +// Useful for frontend to build available mocker selection func GetMockerList() []string { list := make([]string, 0, len(mockerList)) for k := range mockerList { @@ -51,7 +51,7 @@ func GetMockerList() []string { return list } -//The boot mockerFn only connects the node in a ring and doesn't do anything else +// The boot mockerFn only connects the node in a ring and doesn't do anything else func boot(net *Network, quit chan struct{}, nodeCount int) { _, err := connectNodesInRing(net, nodeCount) if err != nil { @@ -59,7 +59,7 @@ func boot(net *Network, quit chan struct{}, nodeCount int) { } } -//The startStop mockerFn stops and starts nodes in a defined period (ticker) +// The startStop mockerFn stops and starts nodes in a defined period (ticker) func startStop(net *Network, quit chan struct{}, nodeCount int) { nodes, err := connectNodesInRing(net, nodeCount) if err != nil { @@ -96,16 +96,16 @@ func startStop(net *Network, quit chan struct{}, nodeCount int) { } } -//The probabilistic mocker func has a more probabilistic pattern +// The probabilistic mocker func has a more probabilistic pattern //(the implementation could probably be improved): -//nodes are connected in a ring, then a varying number of random nodes is selected, -//mocker then stops and starts them in random intervals, and continues the loop +// nodes are connected in a ring, then a varying number of random nodes is selected, +// mocker then stops and starts them in random intervals, and continues the loop func probabilistic(net *Network, quit chan struct{}, nodeCount int) { nodes, err := connectNodesInRing(net, nodeCount) if err != nil { select { case <-quit: - //error may be due to abortion of mocking; so the quit channel is closed + // error may be due to abortion of mocking; so the quit channel is closed return default: panic("Could not startup node network for mocker") @@ -165,10 +165,9 @@ func probabilistic(net *Network, quit chan struct{}, nodeCount int) { } wg.Wait() } - } -//connect nodeCount number of nodes in a ring +// connect nodeCount number of nodes in a ring func connectNodesInRing(net *Network, nodeCount int) ([]enode.ID, error) { ids := make([]enode.ID, nodeCount) for i := 0; i < nodeCount; i++ { diff --git a/p2p/simulations/mocker_test.go b/p2p/simulations/mocker_test.go index 069040257e..cc08d2bade 100644 --- a/p2p/simulations/mocker_test.go +++ b/p2p/simulations/mocker_test.go @@ -31,19 +31,19 @@ import ( ) func TestMocker(t *testing.T) { - //start the simulation HTTP server + // start the simulation HTTP server _, s := testHTTPServer(t) defer s.Close() - //create a client + // create a client client := NewClient(s.URL) - //start the network + // start the network err := client.StartNetwork() if err != nil { t.Fatalf("Could not start test network: %s", err) } - //stop the network to terminate + // stop the network to terminate defer func() { err = client.StopNetwork() if err != nil { @@ -51,7 +51,7 @@ func TestMocker(t *testing.T) { } }() - //get the list of available mocker types + // get the list of available mocker types resp, err := http.Get(s.URL + "/mocker") if err != nil { t.Fatalf("Could not get mocker list: %s", err) @@ -62,7 +62,7 @@ func TestMocker(t *testing.T) { t.Fatalf("Invalid Status Code received, expected 200, got %d", resp.StatusCode) } - //check the list is at least 1 in size + // check the list is at least 1 in size var mockerlist []string err = json.NewDecoder(resp.Body).Decode(&mockerlist) if err != nil { @@ -80,8 +80,8 @@ func TestMocker(t *testing.T) { var opts SubscribeOpts sub, err := client.SubscribeNetwork(events, opts) defer sub.Unsubscribe() - //wait until all nodes are started and connected - //store every node up event in a map (value is irrelevant, mimic Set datatype) + // wait until all nodes are started and connected + // store every node up event in a map (value is irrelevant, mimic Set datatype) nodemap := make(map[enode.ID]bool) wg.Add(1) nodesComplete := false @@ -91,9 +91,9 @@ func TestMocker(t *testing.T) { select { case event := <-events: if isNodeUp(event) { - //add the correspondent node ID to the map + // add the correspondent node ID to the map nodemap[event.Node.Config.ID] = true - //this means all nodes got a nodeUp event, so we can continue the test + // this means all nodes got a nodeUp event, so we can continue the test if len(nodemap) == nodeCount { nodesComplete = true } @@ -111,16 +111,16 @@ func TestMocker(t *testing.T) { } }() - //take the last element of the mockerlist as the default mocker-type to ensure one is enabled + // take the last element of the mockerlist as the default mocker-type to ensure one is enabled mockertype := mockerlist[len(mockerlist)-1] - //still, use hardcoded "probabilistic" one if available ;) + // still, use hardcoded "probabilistic" one if available ;) for _, m := range mockerlist { if m == "probabilistic" { mockertype = m break } } - //start the mocker with nodeCount number of nodes + // start the mocker with nodeCount number of nodes resp, err = http.PostForm(s.URL+"/mocker/start", url.Values{"mocker-type": {mockertype}, "node-count": {strconv.Itoa(nodeCount)}}) if err != nil { t.Fatalf("Could not start mocker: %s", err) @@ -131,7 +131,7 @@ func TestMocker(t *testing.T) { wg.Wait() - //check there are nodeCount number of nodes in the network + // check there are nodeCount number of nodes in the network nodesInfo, err := client.GetNodes() if err != nil { t.Fatalf("Could not get nodes list: %s", err) @@ -141,7 +141,7 @@ func TestMocker(t *testing.T) { t.Fatalf("Expected %d number of nodes, got: %d", nodeCount, len(nodesInfo)) } - //stop the mocker + // stop the mocker resp, err = http.Post(s.URL+"/mocker/stop", "", nil) if err != nil { t.Fatalf("Could not stop mocker: %s", err) @@ -150,13 +150,13 @@ func TestMocker(t *testing.T) { t.Fatalf("Invalid Status Code received for stopping mocker, expected 200, got %d", resp.StatusCode) } - //reset the network + // reset the network _, err = http.Post(s.URL+"/reset", "", nil) if err != nil { t.Fatalf("Could not reset network: %s", err) } - //now the number of nodes in the network should be zero + // now the number of nodes in the network should be zero nodesInfo, err = client.GetNodes() if err != nil { t.Fatalf("Could not get nodes list: %s", err) diff --git a/p2p/simulations/network.go b/p2p/simulations/network.go index f03c953e89..90b02aa71d 100644 --- a/p2p/simulations/network.go +++ b/p2p/simulations/network.go @@ -613,7 +613,7 @@ func (net *Network) Reset() { net.lock.Lock() defer net.lock.Unlock() - //re-initialize the maps + // re-initialize the maps net.connMap = make(map[string]int) net.nodeMap = make(map[enode.ID]int) @@ -923,8 +923,8 @@ func (net *Network) Load(snap *Snapshot) error { for _, conn := range snap.Conns { if !net.GetNode(conn.One).Up() || !net.GetNode(conn.Other).Up() { - //in this case, at least one of the nodes of a connection is not up, - //so it would result in the snapshot `Load` to fail + // in this case, at least one of the nodes of a connection is not up, + // so it would result in the snapshot `Load` to fail continue } if err := net.Connect(conn.One, conn.Other); err != nil { diff --git a/p2p/simulations/network_test.go b/p2p/simulations/network_test.go index 01cd1000de..e52fc895de 100644 --- a/p2p/simulations/network_test.go +++ b/p2p/simulations/network_test.go @@ -35,7 +35,6 @@ import ( // Tests that a created snapshot with a minimal service only contains the expected connections // and that a network when loaded with this snapshot only contains those same connections func TestSnapshot(t *testing.T) { - // PART I // create snapshot from ring network @@ -420,7 +419,6 @@ func BenchmarkMinimalService(b *testing.B) { } func benchmarkMinimalServiceTmp(b *testing.B) { - // stop timer to discard setup time pollution args := strings.Split(b.Name(), "/") nodeCount, err := strconv.ParseInt(args[2], 10, 16) diff --git a/p2p/simulations/pipes/pipes.go b/p2p/simulations/pipes/pipes.go index 8532c1bcf0..72a3acf64a 100644 --- a/p2p/simulations/pipes/pipes.go +++ b/p2p/simulations/pipes/pipes.go @@ -16,9 +16,7 @@ package pipes -import ( - "net" -) +import "net" // NetPipe wraps net.Pipe in a signature returning an error func NetPipe() (net.Conn, net.Conn, error) { diff --git a/p2p/testing/peerpool.go b/p2p/testing/peerpool.go index 01ccce67eb..685738a1fd 100644 --- a/p2p/testing/peerpool.go +++ b/p2p/testing/peerpool.go @@ -44,7 +44,6 @@ func (p *TestPeerPool) Add(peer TestPeer) { defer p.lock.Unlock() log.Trace(fmt.Sprintf("pp add peer %v", peer.ID())) p.peers[peer.ID()] = peer - } func (p *TestPeerPool) Remove(peer TestPeer) { diff --git a/p2p/testing/protocolsession.go b/p2p/testing/protocolsession.go index 476c2a9840..0bb5a24c69 100644 --- a/p2p/testing/protocolsession.go +++ b/p2p/testing/protocolsession.go @@ -190,7 +190,6 @@ func (s *ProtocolSession) expect(exps []Expect) error { case <-alarm.C: errc <- errTimedOut } - }() } diff --git a/p2p/testing/protocoltester.go b/p2p/testing/protocoltester.go index 1e1752af8a..395fb01dc4 100644 --- a/p2p/testing/protocoltester.go +++ b/p2p/testing/protocoltester.go @@ -121,7 +121,6 @@ func (t *ProtocolTester) Connect(selfID enode.ID, peers ...*adapters.NodeConfig) panic(fmt.Sprintf("error connecting to peer %v: %v", peer.ID, err)) } } - } // testNode wraps a protocol run function and implements the node.Service diff --git a/params/version.go b/params/version.go index d3954e0bc3..f70b57832f 100644 --- a/params/version.go +++ b/params/version.go @@ -16,9 +16,7 @@ package params -import ( - "fmt" -) +import "fmt" const ( VersionMajor = 1 // Major version component of the current release diff --git a/rlp/decode_test.go b/rlp/decode_test.go index 4d8abd0012..ac481fb8e5 100644 --- a/rlp/decode_test.go +++ b/rlp/decode_test.go @@ -347,11 +347,9 @@ type tailUint struct { Tail []uint `rlp:"tail"` } -var ( - veryBigInt = big.NewInt(0).Add( - big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), - big.NewInt(0xFFFF), - ) +var veryBigInt = big.NewInt(0).Add( + big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), + big.NewInt(0xFFFF), ) type hasIgnoredField struct { diff --git a/rpc/client.go b/rpc/client.go index 02029dc8f6..7543994433 100644 --- a/rpc/client.go +++ b/rpc/client.go @@ -46,19 +46,17 @@ const ( subscribeTimeout = 5 * time.Second // overall timeout eth_subscribe, rpc_modules calls ) -const ( - // Subscriptions are removed when the subscriber cannot keep up. - // - // This can be worked around by supplying a channel with sufficiently sized buffer, - // but this can be inconvenient and hard to explain in the docs. Another issue with - // buffered channels is that the buffer is static even though it might not be needed - // most of the time. - // - // The approach taken here is to maintain a per-subscription linked list buffer - // shrinks on demand. If the buffer reaches the size below, the subscription is - // dropped. - maxClientSubscriptionBuffer = 20000 -) +// Subscriptions are removed when the subscriber cannot keep up. +// +// This can be worked around by supplying a channel with sufficiently sized buffer, +// but this can be inconvenient and hard to explain in the docs. Another issue with +// buffered channels is that the buffer is static even though it might not be needed +// most of the time. +// +// The approach taken here is to maintain a per-subscription linked list buffer +// shrinks on demand. If the buffer reaches the size below, the subscription is +// dropped. +const maxClientSubscriptionBuffer = 20000 // BatchElem is an element in a batch request. type BatchElem struct { diff --git a/rpc/endpoints.go b/rpc/endpoints.go index 8ca6d4eb0c..54911a8b8d 100644 --- a/rpc/endpoints.go +++ b/rpc/endpoints.go @@ -53,7 +53,6 @@ func StartHTTPEndpoint(endpoint string, apis []API, modules []string, cors []str // StartWSEndpoint starts a websocket endpoint func StartWSEndpoint(endpoint string, apis []API, modules []string, wsOrigins []string, exposeAll bool) (net.Listener, *Server, error) { - // Generate the whitelist based on the allowed modules whitelist := make(map[string]bool) for _, module := range modules { @@ -79,7 +78,6 @@ func StartWSEndpoint(endpoint string, apis []API, modules []string, wsOrigins [] } go NewWSServer(wsOrigins, handler).Serve(listener) return listener, handler, err - } // StartIPCEndpoint starts an IPC endpoint. diff --git a/signer/core/abihelper.go b/signer/core/abihelper.go index 88c1da0330..080b932996 100644 --- a/signer/core/abihelper.go +++ b/signer/core/abihelper.go @@ -33,6 +33,7 @@ type decodedArgument struct { soltype abi.Argument value interface{} } + type decodedCallData struct { signature string name string @@ -63,7 +64,6 @@ func (cd decodedCallData) String() string { // parseCallData matches the provided call data against the abi definition, // and returns a struct containing the actual go-typed values func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) { - if len(calldata) < 4 { return nil, fmt.Errorf("Invalid ABI-data, incomplete method signature of (%d bytes)", len(calldata)) } @@ -105,9 +105,8 @@ func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) { // original data. If we didn't do that, it would e.g. be possible to stuff extra data into the arguments, which // is not detected by merely decoding the data. - var ( - encoded []byte - ) + var encoded []byte + encoded, err = method.Inputs.PackValues(v) if err != nil { @@ -125,7 +124,6 @@ func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) { // MethodSelectorToAbi converts a method selector into an ABI struct. The returned data is a valid json string // which can be consumed by the standard abi package. func MethodSelectorToAbi(selector string) ([]byte, error) { - re := regexp.MustCompile(`^([^\)]+)\(([a-z0-9,\[\]]*)\)`) type fakeArg struct { @@ -152,7 +150,6 @@ func MethodSelectorToAbi(selector string) ([]byte, error) { name, "function", arguments, } return json.Marshal([]fakeABI{abicheat}) - } type AbiDb struct { @@ -186,7 +183,6 @@ func NewAbiDBFromFile(path string) (*AbiDb, error) { // NewAbiDBFromFiles loads both the standard signature database and a custom database. The latter will be used // to write new values into if they are submitted via the API func NewAbiDBFromFiles(standard, custom string) (*AbiDb, error) { - db := &AbiDb{make(map[string]string), make(map[string]string), custom} db.customdbPath = custom @@ -226,6 +222,7 @@ func (db *AbiDb) LookupMethodSelector(id []byte) (string, error) { } return "", fmt.Errorf("Signature %v not found", sig) } + func (db *AbiDb) Size() int { return len(db.db) } @@ -234,7 +231,7 @@ func (db *AbiDb) Size() int { func (db *AbiDb) saveCustomAbi(selector, signature string) error { db.customdb[signature] = selector if db.customdbPath == "" { - return nil //Not an error per se, just not used + return nil // Not an error per se, just not used } d, err := json.Marshal(db.customdb) if err != nil { diff --git a/signer/core/abihelper_test.go b/signer/core/abihelper_test.go index 4a3a2f06d2..6e2af962f1 100644 --- a/signer/core/abihelper_test.go +++ b/signer/core/abihelper_test.go @@ -29,7 +29,6 @@ import ( ) func verify(t *testing.T, jsondata, calldata string, exp []interface{}) { - abispec, err := abi.JSON(strings.NewReader(jsondata)) if err != nil { t.Fatal(err) @@ -53,6 +52,7 @@ func verify(t *testing.T, jsondata, calldata string, exp []interface{}) { } } } + func TestNewUnpacker(t *testing.T) { type unpackTest struct { jsondata string @@ -96,11 +96,9 @@ func TestNewUnpacker(t *testing.T) { for _, c := range testcases { verify(t, c.jsondata, c.calldata, c.exp) } - } func TestCalldataDecoding(t *testing.T) { - // send(uint256) : a52c101e // compareAndApprove(address,uint256,uint256) : 751e1079 // issue(address[],uint256) : 42958b54 @@ -111,7 +109,7 @@ func TestCalldataDecoding(t *testing.T) { {"type":"function","name":"issue","inputs":[{"name":"a","type":"address[]"},{"name":"a","type":"uint256"}]}, {"type":"function","name":"sam","inputs":[{"name":"a","type":"bytes"},{"name":"a","type":"bool"},{"name":"a","type":"uint256[]"}]} ]` - //Expected failures + // Expected failures for i, hexdata := range []string{ "a52c101e00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000042", "a52c101e000000000000000000000000000000000000000000000000000000000000001200", @@ -122,9 +120,9 @@ func TestCalldataDecoding(t *testing.T) { // Too short "751e10790000000000000000000000000000000000000000000000000000000000000012", "751e1079FFffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - //Not valid multiple of 32 + // Not valid multiple of 32 "deadbeef00000000000000000000000000000000000000000000000000000000000000", - //Too short 'issue' + // Too short 'issue' "42958b5400000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000042", // Too short compareAndApprove "a52c101e00ff0000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000042", @@ -137,7 +135,7 @@ func TestCalldataDecoding(t *testing.T) { t.Errorf("test %d: expected decoding to fail: %s", i, hexdata) } } - //Expected success + // Expected success for i, hexdata := range []string{ // From https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI "a5643bf20000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000464617665000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003", @@ -147,7 +145,7 @@ func TestCalldataDecoding(t *testing.T) { "42958b54" + // start of dynamic type "0000000000000000000000000000000000000000000000000000000000000040" + - //uint256 + // uint256 "0000000000000000000000000000000000000000000000000000000000000001" + // length of array "0000000000000000000000000000000000000000000000000000000000000002" + @@ -196,7 +194,6 @@ func TestSelectorUnmarshalling(t *testing.T) { t.Errorf("Expected equality: %v != %v", m.Sig(), selector) } } - } func TestCustomABI(t *testing.T) { @@ -223,7 +220,7 @@ func TestCustomABI(t *testing.T) { if err != nil { t.Fatalf("Should find a match for abi signature, got: %v", err) } - //Check that it wrote to file + // Check that it wrote to file abidb2, err := NewAbiDBFromFile(filename) if err != nil { t.Fatalf("Failed to create new abidb: %v", err) diff --git a/signer/core/api.go b/signer/core/api.go index 9da6ee2a23..cba1dd25dd 100644 --- a/signer/core/api.go +++ b/signer/core/api.go @@ -184,7 +184,7 @@ type ( } // SignTxResponse result from SignTxRequest SignTxResponse struct { - //The UI may make changes to the TX + // The UI may make changes to the TX Transaction SendTxArgs `json:"transaction"` Approved bool `json:"approved"` } @@ -245,6 +245,7 @@ func NewSignerAPI(am *accounts.Manager, chainID int64, noUSB bool, ui UIClientAP } return signer } + func (api *SignerAPI) openTrezor(url accounts.URL) { resp, err := api.UI.OnInputRequired(UserInputRequest{ Prompt: "Pin required to open Trezor wallet\n" + @@ -273,7 +274,6 @@ func (api *SignerAPI) openTrezor(url accounts.URL) { log.Warn("failed to open wallet", "wallet", url, "err", err) return } - } // startUSBListener starts a listener for USB events, for hardware wallet interaction @@ -282,7 +282,6 @@ func (api *SignerAPI) startUSBListener() { am := api.am am.Subscribe(events) go func() { - // Open any wallets already attached for _, wallet := range am.Wallets() { if err := wallet.Open(""); err != nil { @@ -342,7 +341,6 @@ func (api *SignerAPI) List(ctx context.Context) ([]common.Address, error) { } if result.Accounts == nil { return nil, ErrRequestDenied - } addresses := make([]common.Address, 0) for _, acc := range result.Accounts { @@ -371,7 +369,8 @@ func (api *SignerAPI) New(ctx context.Context) (common.Address, error) { resp, err := api.UI.OnInputRequired(UserInputRequest{ "New account password", fmt.Sprintf("Please enter a password for the new account to be created (attempt %d of 3)", i), - true}) + true, + }) if err != nil { log.Warn("error obtaining password", "attempt", i, "error", err) continue @@ -437,6 +436,7 @@ func logDiff(original *SignTxRequest, new *SignTxResponse) bool { func (api *SignerAPI) lookupPassword(address common.Address) string { return api.credentials.Get(strings.ToLower(address.String())) } + func (api *SignerAPI) lookupOrQueryPassword(address common.Address, title, prompt string) (string, error) { if pw := api.lookupPassword(address); pw != "" { return pw, nil @@ -515,7 +515,6 @@ func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, meth api.UI.OnApprovedTx(response) // ...and to the external caller return &response, nil - } // Returns the external api version. This method does not require user acceptance. Available methods are diff --git a/signer/core/api_test.go b/signer/core/api_test.go index 3225c10ea6..a6d049886e 100644 --- a/signer/core/api_test.go +++ b/signer/core/api_test.go @@ -37,7 +37,7 @@ import ( "github.com/ethereum/go-ethereum/signer/storage" ) -//Used for testing +// Used for testing type headlessUi struct { approveCh chan string // to send approve/deny inputCh chan string // to send password @@ -53,7 +53,6 @@ func (ui *headlessUi) RegisterUIServer(api *UIServerAPI) {} func (ui *headlessUi) OnApprovedTx(tx ethapi.SignTransactionResult) {} func (ui *headlessUi) ApproveTx(request *SignTxRequest) (SignTxResponse, error) { - switch <-ui.approveCh { case "Y": return SignTxResponse{request.Transaction, true}, nil @@ -75,7 +74,7 @@ func (ui *headlessUi) ApproveSignData(request *SignDataRequest) (SignDataRespons func (ui *headlessUi) ApproveListing(request *ListRequest) (ListResponse, error) { approval := <-ui.approveCh - //fmt.Printf("approval %s\n", approval) + // fmt.Printf("approval %s\n", approval) switch approval { case "A": return ListResponse{request.Accounts}, nil @@ -96,12 +95,12 @@ func (ui *headlessUi) ApproveNewAccount(request *NewAccountRequest) (NewAccountR } func (ui *headlessUi) ShowError(message string) { - //stdout is used by communication + // stdout is used by communication fmt.Fprintln(os.Stderr, message) } func (ui *headlessUi) ShowInfo(message string) { - //stdout is used by communication + // stdout is used by communication fmt.Fprintln(os.Stderr, message) } @@ -126,8 +125,8 @@ func setup(t *testing.T) (*SignerAPI, *headlessUi) { am := StartClefAccountManager(tmpDirName(t), true, true) api := NewSignerAPI(am, 1337, true, ui, db, true, &storage.NoStorage{}) return api, ui - } + func createAccount(ui *headlessUi, api *SignerAPI, t *testing.T) { ui.approveCh <- "Y" ui.inputCh <- "a_long_password" @@ -140,7 +139,6 @@ func createAccount(ui *headlessUi, api *SignerAPI, t *testing.T) { } func failCreateAccountWithPassword(ui *headlessUi, api *SignerAPI, password string, t *testing.T) { - ui.approveCh <- "Y" // We will be asked three times to provide a suitable password ui.inputCh <- password @@ -170,7 +168,6 @@ func failCreateAccount(ui *headlessUi, api *SignerAPI, t *testing.T) { func list(ui *headlessUi, api *SignerAPI, t *testing.T) ([]common.Address, error) { ui.approveCh <- "A" return api.List(context.Background()) - } func TestNewAcc(t *testing.T) { @@ -235,7 +232,8 @@ func mkTestTx(from common.MixedcaseAddress) SendTxArgs { GasPrice: gasPrice, Value: value, Data: &data, - Nonce: nonce} + Nonce: nonce, + } return tx } @@ -286,7 +284,7 @@ func TestSignTx(t *testing.T) { parsedTx := &types.Transaction{} rlp.Decode(bytes.NewReader(res.Raw), parsedTx) - //The tx should NOT be modified by the UI + // The tx should NOT be modified by the UI if parsedTx.Value().Cmp(tx.Value.ToInt()) != 0 { t.Errorf("Expected value to be unchanged, expected %v got %v", tx.Value, parsedTx.Value()) } @@ -301,7 +299,7 @@ func TestSignTx(t *testing.T) { t.Error("Expected tx to be unmodified by UI") } - //The tx is modified by the UI + // The tx is modified by the UI control.approveCh <- "M" control.inputCh <- "a_long_password" @@ -312,12 +310,11 @@ func TestSignTx(t *testing.T) { parsedTx2 := &types.Transaction{} rlp.Decode(bytes.NewReader(res.Raw), parsedTx2) - //The tx should be modified by the UI + // The tx should be modified by the UI if parsedTx2.Value().Cmp(tx.Value.ToInt()) != 0 { t.Errorf("Expected value to be unchanged, got %v", parsedTx.Value()) } if bytes.Equal(res.Raw, res2.Raw) { t.Error("Expected tx to be modified by UI") } - } diff --git a/signer/core/auditlog.go b/signer/core/auditlog.go index 9593ad7a53..7005f4d0d8 100644 --- a/signer/core/auditlog.go +++ b/signer/core/auditlog.go @@ -89,7 +89,6 @@ func (l *AuditLogger) Version(ctx context.Context) (string, error) { data, err := l.api.Version(ctx) l.log.Info("Version", "type", "response", "data", data, "error", err) return data, err - } func NewAuditLogger(path string, api ExternalAPI) (*AuditLogger, error) { diff --git a/signer/core/cliui.go b/signer/core/cliui.go index cf7101441b..ad239ceaeb 100644 --- a/signer/core/cliui.go +++ b/signer/core/cliui.go @@ -87,7 +87,6 @@ func (ui *CommandlineUI) readPasswordText(inputstring string) string { } func (ui *CommandlineUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) { - fmt.Printf("## %s\n\n%s\n", info.Title, info.Prompt) if info.IsPassword { fmt.Printf("> ") @@ -141,7 +140,6 @@ func (ui *CommandlineUI) ApproveTx(request *SignTxRequest) (SignTxResponse, erro if request.Transaction.Data != nil { d := *request.Transaction.Data if len(d) > 0 { - fmt.Printf("data: %v\n", hexutil.Encode(d)) } } @@ -173,7 +171,7 @@ func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResp for _, nvt := range request.Message { fmt.Printf("%v\n", nvt.Pprint(1)) } - //fmt.Printf("message: \n%v\n", request.Message) + // fmt.Printf("message: \n%v\n", request.Message) fmt.Printf("raw data: \n%q\n", request.Rawdata) fmt.Printf("message hash: %v\n", request.Hash) fmt.Printf("-------------------------------------------\n") @@ -187,7 +185,6 @@ func (ui *CommandlineUI) ApproveSignData(request *SignDataRequest) (SignDataResp // ApproveListing prompt the user for confirmation to list accounts // the list of accounts to list can be modified by the UI func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, error) { - ui.mu.Lock() defer ui.mu.Unlock() @@ -208,7 +205,6 @@ func (ui *CommandlineUI) ApproveListing(request *ListRequest) (ListResponse, err // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller func (ui *CommandlineUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) { - ui.mu.Lock() defer ui.mu.Unlock() @@ -244,7 +240,6 @@ func (ui *CommandlineUI) OnApprovedTx(tx ethapi.SignTransactionResult) { } func (ui *CommandlineUI) OnSignerStartup(info StartupInfo) { - fmt.Printf("------- Signer info -------\n") for k, v := range info.Info { fmt.Printf("* %v : %v\n", k, v) diff --git a/signer/core/signed_data.go b/signer/core/signed_data.go index d264cbaa08..7e6e324d67 100644 --- a/signer/core/signed_data.go +++ b/signer/core/signed_data.go @@ -123,7 +123,6 @@ var typedDataReferenceTypeRegexp = regexp.MustCompile(`^[A-Z](\w*)(\[\])?$`) // Note, the produced signature conforms to the secp256k1 curve R, S and V values, // where the V value will be 27 or 28 for legacy reasons, if legacyV==true. func (api *SignerAPI) sign(addr common.MixedcaseAddress, req *SignDataRequest, legacyV bool) (hexutil.Bytes, error) { - // We make the request prior to looking up if we actually have the account, to prevent // account-enumeration via the API res, err := api.UI.ApproveSignData(req) @@ -267,7 +266,6 @@ func (api *SignerAPI) determineSignatureFormat(ctx context.Context, contentType req.Address = addr req.Meta = MetadataFromContext(ctx) return req, useEthereumV, nil - } // SignTextWithValidator signs the given message which can be further recovered @@ -465,7 +463,6 @@ func (typedData *TypedData) EncodeData(primaryType string, data map[string]inter // EncodePrimitiveValue deals with the primitive values found // while searching through the typed data func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interface{}, depth int) ([]byte, error) { - switch encType { case "address": stringValue, ok := encValue.(string) @@ -539,7 +536,6 @@ func (typedData *TypedData) EncodePrimitiveValue(encType string, encValue interf return abi.U256(bigIntValue), nil } return nil, fmt.Errorf("unrecognized type '%s'", encType) - } // dataMismatchError generates an error for a mismatch between diff --git a/signer/core/signed_data_test.go b/signer/core/signed_data_test.go index b1d8932218..e75d0d162c 100644 --- a/signer/core/signed_data_test.go +++ b/signer/core/signed_data_test.go @@ -176,7 +176,7 @@ var typedData = TypedData{ func TestSignData(t *testing.T) { api, control := setup(t) - //Create two accounts + // Create two accounts createAccount(control, api, t) createAccount(control, api, t) control.approveCh <- "1" @@ -792,7 +792,6 @@ func TestCustomTypeAsArray(t *testing.T) { } func TestFormatter(t *testing.T) { - var d TypedData err := json.Unmarshal([]byte(jsonTypedData), &d) if err != nil { diff --git a/signer/core/stdioui.go b/signer/core/stdioui.go index 0edb72def9..f071573bc8 100644 --- a/signer/core/stdioui.go +++ b/signer/core/stdioui.go @@ -100,6 +100,7 @@ func (ui *StdIOUI) ShowInfo(message string) { log.Info("Error calling 'ui_showInfo'", "exc", err.Error(), "msg", message) } } + func (ui *StdIOUI) OnApprovedTx(tx ethapi.SignTransactionResult) { err := ui.notify("ui_onApprovedTx", tx) if err != nil { @@ -113,6 +114,7 @@ func (ui *StdIOUI) OnSignerStartup(info StartupInfo) { log.Info("Error calling 'ui_onSignerStartup'", "exc", err.Error(), "info", info) } } + func (ui *StdIOUI) OnInputRequired(info UserInputRequest) (UserInputResponse, error) { var result UserInputResponse err := ui.dispatch("ui_onInputRequired", info, &result) diff --git a/signer/core/types.go b/signer/core/types.go index 8743746ba0..93a5440c54 100644 --- a/signer/core/types.go +++ b/signer/core/types.go @@ -31,6 +31,7 @@ type ValidationInfo struct { Typ string `json:"type"` Message string `json:"message"` } + type ValidationMessages struct { Messages []ValidationInfo } @@ -44,9 +45,11 @@ const ( func (vs *ValidationMessages) crit(msg string) { vs.Messages = append(vs.Messages, ValidationInfo{CRIT, msg}) } + func (vs *ValidationMessages) warn(msg string) { vs.Messages = append(vs.Messages, ValidationInfo{WARN, msg}) } + func (vs *ValidationMessages) info(msg string) { vs.Messages = append(vs.Messages, ValidationInfo{INFO, msg}) } diff --git a/signer/core/validation.go b/signer/core/validation.go index 7c3ec42741..c2dbf0f9c4 100644 --- a/signer/core/validation.go +++ b/signer/core/validation.go @@ -38,6 +38,7 @@ type Validator struct { func NewValidator(db *AbiDb) *Validator { return &Validator{db} } + func testSelector(selector string, data []byte) (*decodedCallData, error) { if selector == "" { return nil, fmt.Errorf("selector not found") @@ -51,7 +52,6 @@ func testSelector(selector string, data []byte) (*decodedCallData, error) { return nil, err } return info, nil - } // validateCallData checks if the ABI-data + methodselector (if given) can be parsed and seems to match @@ -77,7 +77,7 @@ func (v *Validator) validateCallData(msgs *ValidationMessages, data []byte, meth msgs.warn(fmt.Sprintf("Tx contains data, but provided ABI signature could not be matched: %v", err)) } else { msgs.info(info.String()) - //Successfull match. add to db if not there already (ignore errors there) + // Successfull match. add to db if not there already (ignore errors there) v.db.AddSignature(*methodSelector, data[:4]) } return @@ -103,9 +103,9 @@ func (v *Validator) validate(msgs *ValidationMessages, txargs *SendTxArgs, metho // This is a showstopper return errors.New(`Ambiguous request: both "data" and "input" are set and are not identical`) } - var ( - data []byte - ) + + var data []byte + // Place data on 'data', and nil 'input' if txargs.Input != nil { txargs.Data = txargs.Input @@ -116,7 +116,7 @@ func (v *Validator) validate(msgs *ValidationMessages, txargs *SendTxArgs, metho } if txargs.To == nil { - //Contract creation should contain sufficient data to deploy a contract + // Contract creation should contain sufficient data to deploy a contract // A typical error is omitting sender due to some quirk in the javascript call // e.g. https://github.com/ethereum/go-ethereum/issues/16106 if len(data) == 0 { @@ -126,7 +126,7 @@ func (v *Validator) validate(msgs *ValidationMessages, txargs *SendTxArgs, metho } // No value submitted at least msgs.crit("Tx will create contract with empty code!") - } else if len(data) < 40 { //Arbitrary limit + } else if len(data) < 40 { // Arbitrary limit msgs.warn(fmt.Sprintf("Tx will will create contract, but payload is suspiciously small (%d b)", len(data))) } // methodSelector should be nil for contract creation diff --git a/signer/core/validation_test.go b/signer/core/validation_test.go index 1e2e69ecd4..d8336b2a1f 100644 --- a/signer/core/validation_test.go +++ b/signer/core/validation_test.go @@ -28,14 +28,17 @@ import ( func mixAddr(a string) (*common.MixedcaseAddress, error) { return common.NewMixedcaseAddressFromString(a) } + func toHexBig(h string) hexutil.Big { b := big.NewInt(0).SetBytes(common.FromHex(h)) return hexutil.Big(*b) } + func toHexUint(h string) hexutil.Uint64 { b := big.NewInt(0).SetBytes(common.FromHex(h)) return hexutil.Uint64(b.Uint64()) } + func dummyTxArgs(t txtestcase) *SendTxArgs { to, _ := mixAddr(t.to) from, _ := mixAddr(t.from) @@ -43,9 +46,9 @@ func dummyTxArgs(t txtestcase) *SendTxArgs { gas := toHexUint(t.g) gasPrice := toHexBig(t.gp) value := toHexBig(t.value) - var ( - data, input *hexutil.Bytes - ) + + var data, input *hexutil.Bytes + if t.d != "" { a := hexutil.Bytes(common.FromHex(t.d)) data = &a @@ -81,32 +84,50 @@ func TestValidator(t *testing.T) { ) testcases := []txtestcase{ // Invalid to checksum - {from: "000000000000000000000000000000000000dead", to: "000000000000000000000000000000000000dead", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", numMessages: 1}, + { + from: "000000000000000000000000000000000000dead", to: "000000000000000000000000000000000000dead", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", numMessages: 1, + }, // valid 0x000000000000000000000000000000000000dEaD - {from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", numMessages: 0}, + { + from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", numMessages: 0, + }, // conflicting input and data - {from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", d: "0x01", i: "0x02", expectErr: true}, + { + from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", d: "0x01", i: "0x02", expectErr: true, + }, // Data can't be parsed - {from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", d: "0x0102", numMessages: 1}, + { + from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", d: "0x0102", numMessages: 1, + }, // Data (on Input) can't be parsed - {from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", i: "0x0102", numMessages: 1}, + { + from: "000000000000000000000000000000000000dead", to: "0x000000000000000000000000000000000000dEaD", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", i: "0x0102", numMessages: 1, + }, // Send to 0 - {from: "000000000000000000000000000000000000dead", to: "0x0000000000000000000000000000000000000000", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", numMessages: 1}, + { + from: "000000000000000000000000000000000000dead", to: "0x0000000000000000000000000000000000000000", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", numMessages: 1, + }, // Create empty contract (no value) - {from: "000000000000000000000000000000000000dead", to: "", - n: "0x01", g: "0x20", gp: "0x40", value: "0x00", numMessages: 1}, + { + from: "000000000000000000000000000000000000dead", to: "", + n: "0x01", g: "0x20", gp: "0x40", value: "0x00", numMessages: 1, + }, // Create empty contract (with value) - {from: "000000000000000000000000000000000000dead", to: "", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", expectErr: true}, + { + from: "000000000000000000000000000000000000dead", to: "", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", expectErr: true, + }, // Small payload for create - {from: "000000000000000000000000000000000000dead", to: "", - n: "0x01", g: "0x20", gp: "0x40", value: "0x01", d: "0x01", numMessages: 1}, + { + from: "000000000000000000000000000000000000dead", to: "", + n: "0x01", g: "0x20", gp: "0x40", value: "0x01", d: "0x01", numMessages: 1, + }, } for i, test := range testcases { msgs, err := v.ValidateTransaction(dummyTxArgs(test), nil) @@ -127,7 +148,7 @@ func TestValidator(t *testing.T) { } t.Errorf("Test %d, expected %d messages, got %d", i, test.numMessages, got) } else { - //Debug printout, remove later + // Debug printout, remove later for _, msg := range msgs.Messages { fmt.Printf("* [%d] %s: %s\n", i, msg.Typ, msg.Message) } @@ -157,7 +178,6 @@ func TestPasswordValidation(t *testing.T) { if err == nil && test.shouldFail { t.Errorf("password '%v' should fail validation", test.pw) } else if err != nil && !test.shouldFail { - t.Errorf("password '%v' shound not fail validation, but did: %v", test.pw, err) } } diff --git a/signer/rules/deps/bindata.go b/signer/rules/deps/bindata.go index 0b27f45172..7bf2e1c155 100644 --- a/signer/rules/deps/bindata.go +++ b/signer/rules/deps/bindata.go @@ -52,18 +52,23 @@ type bindataFileInfo struct { func (fi bindataFileInfo) Name() string { return fi.name } + func (fi bindataFileInfo) Size() int64 { return fi.size } + func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } + func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } + func (fi bindataFileInfo) IsDir() bool { return false } + func (fi bindataFileInfo) Sys() interface{} { return nil } diff --git a/signer/rules/rules.go b/signer/rules/rules.go index 5ebffa3af6..7333fb6673 100644 --- a/signer/rules/rules.go +++ b/signer/rules/rules.go @@ -30,9 +30,7 @@ import ( "github.com/robertkrimen/otto" ) -var ( - BigNumber_JS = deps.MustAsset("bignumber.js") -) +var BigNumber_JS = deps.MustAsset("bignumber.js") // consoleOutput is an override for the console.log and console.error methods to // stream the output into the configured output stream instead of stdout. @@ -62,6 +60,7 @@ func NewRuleEvaluator(next core.UIClientAPI, jsbackend storage.Storage) (*rulese return c, nil } + func (r *rulesetUI) RegisterUIServer(api *core.UIServerAPI) { // TODO, make it possible to query from js } @@ -70,8 +69,8 @@ func (r *rulesetUI) Init(javascriptRules string) error { r.jsRules = javascriptRules return nil } -func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (otto.Value, error) { +func (r *rulesetUI) execute(jsfunc string, jsarg interface{}) (otto.Value, error) { // Instantiate a fresh vm engine every time vm := otto.New() // Set the native callbacks @@ -150,7 +149,8 @@ func (r *rulesetUI) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, if approved { return core.SignTxResponse{ Transaction: request.Transaction, - Approved: true}, + Approved: true, + }, nil } return core.SignTxResponse{Approved: false}, err diff --git a/signer/rules/rules_test.go b/signer/rules/rules_test.go index 19d9049c72..b3fbcb160c 100644 --- a/signer/rules/rules_test.go +++ b/signer/rules/rules_test.go @@ -77,6 +77,7 @@ type alwaysDenyUI struct{} func (alwaysDenyUI) OnInputRequired(info core.UserInputRequest) (core.UserInputResponse, error) { return core.UserInputResponse{}, nil } + func (alwaysDenyUI) RegisterUIServer(api *core.UIServerAPI) { } @@ -151,7 +152,6 @@ func TestListRequest(t *testing.T) { } func TestSignTxRequest(t *testing.T) { - js := ` function ApproveTx(r){ console.log("transaction.from", r.transaction.from); @@ -182,7 +182,8 @@ func TestSignTxRequest(t *testing.T) { resp, err := r.ApproveTx(&core.SignTxRequest{ Transaction: core.SendTxArgs{ From: *from, - To: to}, + To: to, + }, Callinfo: nil, Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"}, }) @@ -242,9 +243,8 @@ func (d *dummyUI) OnApprovedTx(tx ethapi.SignTransactionResult) { func (d *dummyUI) OnSignerStartup(info core.StartupInfo) { } -//TestForwarding tests that the rule-engine correctly dispatches requests to the next caller +// TestForwarding tests that the rule-engine correctly dispatches requests to the next caller func TestForwarding(t *testing.T) { - js := "" ui := &dummyUI{make([]string, 0)} jsBackend := storage.NewEphemeralStorage() @@ -262,16 +262,13 @@ func TestForwarding(t *testing.T) { r.ShowError("test") r.ShowInfo("test") - //This one is not forwarded + // This one is not forwarded r.OnApprovedTx(ethapi.SignTransactionResult{}) expCalls := 6 if len(ui.calls) != expCalls { - t.Errorf("Expected %d forwarded calls, got %d: %s", expCalls, len(ui.calls), strings.Join(ui.calls, ",")) - } - } func TestMissingFunc(t *testing.T) { @@ -295,10 +292,9 @@ func TestMissingFunc(t *testing.T) { t.Errorf("Expected missing method to cause non-approval") } fmt.Printf("Err %v", err) - } -func TestStorage(t *testing.T) { +func TestStorage(t *testing.T) { js := ` function testStorage(){ storage.Put("mykey", "myvalue") @@ -348,7 +344,6 @@ func TestStorage(t *testing.T) { t.Errorf("Unexpected data, expected '%v', got '%v'", exp, retval) } fmt.Printf("Err %v", err) - } const ExampleTxWindow = ` @@ -426,7 +421,6 @@ const ExampleTxWindow = ` ` func dummyTx(value hexutil.Big) *core.SignTxRequest { - to, _ := mixAddr("000000000000000000000000000000000000dead") from, _ := mixAddr("000000000000000000000000000000000000dead") n := hexutil.Uint64(3) @@ -448,22 +442,22 @@ func dummyTx(value hexutil.Big) *core.SignTxRequest { Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"}, } } -func dummyTxWithV(value uint64) *core.SignTxRequest { +func dummyTxWithV(value uint64) *core.SignTxRequest { v := big.NewInt(0).SetUint64(value) h := hexutil.Big(*v) return dummyTx(h) } + func dummySigned(value *big.Int) *types.Transaction { to := common.HexToAddress("000000000000000000000000000000000000dead") gas := uint64(21000) gasPrice := big.NewInt(2000000) data := make([]byte, 0) return types.NewTransaction(3, to, value, gas, gasPrice, data) - } -func TestLimitWindow(t *testing.T) { +func TestLimitWindow(t *testing.T) { r, err := initRuleEngine(ExampleTxWindow) if err != nil { t.Errorf("Couldn't create evaluator %v", err) @@ -496,7 +490,6 @@ func TestLimitWindow(t *testing.T) { if resp.Approved { t.Errorf("Expected check to resolve to 'Reject'") } - } // dontCallMe is used as a next-handler that does not want to be called - it invokes test failure @@ -508,6 +501,7 @@ func (d *dontCallMe) OnInputRequired(info core.UserInputRequest) (core.UserInput d.t.Fatalf("Did not expect next-handler to be called") return core.UserInputResponse{}, nil } + func (d *dontCallMe) RegisterUIServer(api *core.UIServerAPI) { } @@ -546,11 +540,10 @@ func (d *dontCallMe) OnApprovedTx(tx ethapi.SignTransactionResult) { d.t.Fatalf("Did not expect next-handler to be called") } -//TestContextIsCleared tests that the rule-engine does not retain variables over several requests. +// TestContextIsCleared tests that the rule-engine does not retain variables over several requests. // if it does, that would be bad since developers may rely on that to store data, // instead of using the disk-based data storage func TestContextIsCleared(t *testing.T) { - js := ` function ApproveTx(){ if (typeof foobar == 'undefined') { @@ -582,7 +575,6 @@ func TestContextIsCleared(t *testing.T) { } func TestSignData(t *testing.T) { - js := `function ApproveListing(){ return "Approve" } diff --git a/signer/storage/aes_gcm_storage_test.go b/signer/storage/aes_gcm_storage_test.go index a421a8449d..28f314eb32 100644 --- a/signer/storage/aes_gcm_storage_test.go +++ b/signer/storage/aes_gcm_storage_test.go @@ -51,7 +51,6 @@ func TestEncryption(t *testing.T) { } func TestFileStorage(t *testing.T) { - a := map[string]storedCredential{ "secret": { Iv: common.Hex2Bytes("cdb30036279601aeee60f16b"), @@ -92,6 +91,7 @@ func TestFileStorage(t *testing.T) { } } } + func TestEnd2End(t *testing.T) { log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(3), log.StreamHandler(colorable.NewColorableStderr(), log.TerminalFormat(true)))) diff --git a/signer/storage/storage.go b/signer/storage/storage.go index 50c55e455f..2eb8ea8a1e 100644 --- a/signer/storage/storage.go +++ b/signer/storage/storage.go @@ -35,7 +35,7 @@ func (s *EphemeralStorage) Put(key, value string) { if len(key) == 0 { return } - //fmt.Printf("storage: put %v -> %v\n", key, value) + // fmt.Printf("storage: put %v -> %v\n", key, value) s.data[key] = value } @@ -43,7 +43,7 @@ func (s *EphemeralStorage) Get(key string) string { if len(key) == 0 { return "" } - //fmt.Printf("storage: get %v\n", key) + // fmt.Printf("storage: get %v\n", key) if v, exist := s.data[key]; exist { return v } diff --git a/swarm/api/act.go b/swarm/api/act.go index a79f1944b9..1b598744b8 100644 --- a/swarm/api/act.go +++ b/swarm/api/act.go @@ -46,7 +46,6 @@ type AccessEntry struct { type DecryptFunc func(*ManifestEntry) error func (a *AccessEntry) MarshalJSON() (out []byte, err error) { - return json.Marshal(struct { Type AccessType `json:"type,omitempty"` Publisher string `json:"publisher,omitempty"` @@ -60,7 +59,6 @@ func (a *AccessEntry) MarshalJSON() (out []byte, err error) { Act: a.Act, KdfParams: a.KdfParams, }) - } func (a *AccessEntry) UnmarshalJSON(value []byte) error { @@ -157,7 +155,6 @@ var DefaultKdfParams = NewKdfParams(262144, 1, 8) // NewKdfParams returns a KdfParams struct with the given scrypt params func NewKdfParams(n, p, r int) *KdfParams { - return &KdfParams{ N: n, P: p, @@ -170,7 +167,6 @@ func NewKdfParams(n, p, r int) *KdfParams { func NewSessionKeyPassword(password string, accessEntry *AccessEntry) ([]byte, error) { if accessEntry.Type != AccessTypePass && accessEntry.Type != AccessTypeACT { return nil, errors.New("incorrect access entry type") - } return sessionKeyPassword(password, accessEntry.Salt, accessEntry.KdfParams) } diff --git a/swarm/api/api.go b/swarm/api/api.go index 86c1119232..a894cce7cb 100644 --- a/swarm/api/api.go +++ b/swarm/api/api.go @@ -710,7 +710,7 @@ func (a *API) UploadTar(ctx context.Context, bodyReader io.ReadCloser, manifestP if contentType == "" { contentType = mime.TypeByExtension(filepath.Ext(hdr.Name)) } - //DetectContentType("") + // DetectContentType("") entry := &ManifestEntry{ Path: manifestPath, ContentType: contentType, @@ -818,9 +818,9 @@ func (a *API) AppendFile(ctx context.Context, mhash, path, fname string, existin totalSize := int64(len(buf)) // TODO(jmozah): to append using pyramid chunker when it is ready - //oldReader := a.Retrieve(oldKey) - //newReader := bytes.NewReader(content) - //combinedReader := io.MultiReader(oldReader, newReader) + // oldReader := a.Retrieve(oldKey) + // newReader := bytes.NewReader(content) + // combinedReader := io.MultiReader(oldReader, newReader) uri, err := Parse("bzz:/" + mhash) if err != nil { @@ -876,7 +876,6 @@ func (a *API) AppendFile(ctx context.Context, mhash, path, fname string, existin // BuildDirectoryTree used by swarmfs_unix func (a *API) BuildDirectoryTree(ctx context.Context, mhash string, nameresolver bool) (addr storage.Address, manifestEntryMap map[string]*manifestTrieEntry, err error) { - uri, err := Parse("bzz:/" + mhash) if err != nil { return nil, nil, err @@ -980,7 +979,6 @@ func (a *API) ResolveFeed(ctx context.Context, uri *URI, values feed.Values) (*f var f feed.Feed if err := f.FromValues(values); err != nil { return nil, ErrCannotResolveFeed - } fd = &f } diff --git a/swarm/api/api_test.go b/swarm/api/api_test.go index eb896f32aa..48791c57b8 100644 --- a/swarm/api/api_test.go +++ b/swarm/api/api_test.go @@ -62,7 +62,6 @@ type testResponse struct { } func checkResponse(t *testing.T, resp *testResponse, exp *Response) { - if resp.MimeType != exp.MimeType { t.Errorf("incorrect mimeType. expected '%s', got '%s'", exp.MimeType, resp.MimeType) } @@ -157,6 +156,7 @@ func (t *testResolveValidator) Resolve(addr string) (common.Hash, error) { func (t *testResolveValidator) Owner(node [32]byte) (addr common.Address, err error) { return } + func (t *testResolveValidator) HeaderByNumber(context.Context, *big.Int) (header *types.Header, err error) { return } @@ -496,7 +496,6 @@ func TestDetectContentType(t *testing.T) { if detected != tc.expectedContentType { t.Fatalf("File: %s, Expected mime type %s, got %s", tc.file, tc.expectedContentType, detected) } - }) } } diff --git a/swarm/api/client/client.go b/swarm/api/client/client.go index 5e293cca72..f3027e96f4 100644 --- a/swarm/api/client/client.go +++ b/swarm/api/client/client.go @@ -45,9 +45,7 @@ import ( "github.com/pborman/uuid" ) -var ( - ErrUnauthorized = errors.New("unauthorized") -) +var ErrUnauthorized = errors.New("unauthorized") func NewClient(gateway string) *Client { return &Client{ @@ -289,7 +287,7 @@ func (c *Client) DownloadFile(hash, path, dest, credentials string) error { case 0: return fmt.Errorf("could not find path requested at manifest address. make sure the path you've specified is correct") case 1: - //continue + // continue default: return fmt.Errorf("got too many matches for this path") } @@ -319,7 +317,7 @@ func (c *Client) DownloadFile(hash, path, dest, credentials string) error { filename = dest } else { // try to assert - re := regexp.MustCompile("[^/]+$") //everything after last slash + re := regexp.MustCompile("[^/]+$") // everything after last slash if results := re.FindAllString(path, -1); len(results) > 0 { filename = results[len(results)-1] @@ -691,7 +689,7 @@ func (c *Client) queryFeed(query *feed.Query, manifestAddressOrDomain string, me URL.Path = "/bzz-feed:/" + manifestAddressOrDomain values := URL.Query() if query != nil { - query.AppendValues(values) //adds query parameters + query.AppendValues(values) // adds query parameters } if meta { values.Set("meta", "1") @@ -723,7 +721,6 @@ func (c *Client) queryFeed(query *feed.Query, manifestAddressOrDomain string, me // manifestAddressOrDomain is the address you obtained in CreateFeedWithManifest or an ENS domain whose Resolver // points to that address func (c *Client) GetFeedRequest(query *feed.Query, manifestAddressOrDomain string) (*feed.Request, error) { - responseStream, err := c.queryFeed(query, manifestAddressOrDomain, true) if err != nil { return nil, err diff --git a/swarm/api/client/client_test.go b/swarm/api/client/client_test.go index 39f6e4797d..0ea78d1a39 100644 --- a/swarm/api/client/client_test.go +++ b/swarm/api/client/client_test.go @@ -43,6 +43,7 @@ func serverFunc(api *api.API) swarmhttp.TestServer { func TestClientUploadDownloadRaw(t *testing.T) { testClientUploadDownloadRaw(false, t) } + func TestClientUploadDownloadRawEncrypted(t *testing.T) { testClientUploadDownloadRaw(true, t) } @@ -375,7 +376,6 @@ func newTestSigner() (*feed.GenericSigner, error) { // Retrieving the update with the Swarm hash should return the manifest pointing directly to the data // and raw retrieve of that hash should return the data func TestClientBzzWithFeed(t *testing.T) { - signer, _ := newTestSigner() // Initialize a Swarm test server @@ -470,7 +470,7 @@ func TestClientBzzWithFeed(t *testing.T) { t.Fatal(err) } - //Check that indeed the **manifest hash** is retrieved + // Check that indeed the **manifest hash** is retrieved if !bytes.Equal(manifestAddress, gotData) { t.Fatalf("Expected: %v, got %v", manifestAddress, gotData) } @@ -494,7 +494,6 @@ func TestClientBzzWithFeed(t *testing.T) { // TestClientCreateUpdateFeed will check that feeds can be created and updated via the HTTP client. func TestClientCreateUpdateFeed(t *testing.T) { - signer, _ := newTestSigner() srv := swarmhttp.NewTestSwarmServer(t, serverFunc, nil) diff --git a/swarm/api/config.go b/swarm/api/config.go index 0a7100c574..f007b48595 100644 --- a/swarm/api/config.go +++ b/swarm/api/config.go @@ -74,9 +74,8 @@ type Config struct { privateKey *ecdsa.PrivateKey } -//create a default config with all parameters to set to defaults +// create a default config with all parameters to set to defaults func NewConfig() (c *Config) { - c = &Config{ LocalStoreParams: storage.NewDefaultLocalStoreParams(), FileStoreParams: storage.NewFileStoreParams(), @@ -101,10 +100,9 @@ func NewConfig() (c *Config) { return } -//some config params need to be initialized after the complete -//config building phase is completed (e.g. due to overriding flags) +// some config params need to be initialized after the complete +// config building phase is completed (e.g. due to overriding flags) func (c *Config) Init(prvKey *ecdsa.PrivateKey, nodeKey *ecdsa.PrivateKey) error { - // create swarm dir and record key err := c.createAndSetPath(c.Path, prvKey) if err != nil { diff --git a/swarm/api/config_test.go b/swarm/api/config_test.go index a55da6f7b9..2f32bf5065 100644 --- a/swarm/api/config_test.go +++ b/swarm/api/config_test.go @@ -25,7 +25,6 @@ import ( ) func TestConfig(t *testing.T) { - var hexprvkey = "65138b2aa745041b372153550584587da326ab440576b2a1191dd95cee30039c" var hexnodekey = "75138b2aa745041b372153550584587da326ab440576b2a1191dd95cee30039c" @@ -51,7 +50,7 @@ func TestConfig(t *testing.T) { t.Fatal(err) } - //the init function should set the following fields + // the init function should set the following fields if one.BzzKey == "" { t.Fatal("Expected BzzKey to be set") } diff --git a/swarm/api/filesystem.go b/swarm/api/filesystem.go index 266ef71bec..d557c55ce3 100644 --- a/swarm/api/filesystem.go +++ b/swarm/api/filesystem.go @@ -139,7 +139,6 @@ func (fs *FileSystem) Upload(lpath, index string, toEncrypt bool) (string, error errors[i] = err return } - }(i, entry) } for i := 0; i < cap(sem); i++ { @@ -187,7 +186,7 @@ func (fs *FileSystem) Download(bzzpath, localpath string) error { return err } - //resolving host and port + // resolving host and port uri, err := Parse(path.Join("bzz:/", bzzpath)) if err != nil { return err diff --git a/swarm/api/http/response.go b/swarm/api/http/response.go index d4e81d7f67..c22d1c6774 100644 --- a/swarm/api/http/response.go +++ b/swarm/api/http/response.go @@ -100,7 +100,7 @@ func respond(w http.ResponseWriter, r *http.Request, params *ResponseParams) { } else if strings.Contains(acceptHeader, "text/html") { respondHTML(w, r, params) } else { - respondPlaintext(w, r, params) //returns nice errors for curl + respondPlaintext(w, r, params) // returns nice errors for curl } } diff --git a/swarm/api/http/response_test.go b/swarm/api/http/response_test.go index 486c19ab0e..6f8c8124fb 100644 --- a/swarm/api/http/response_test.go +++ b/swarm/api/http/response_test.go @@ -103,6 +103,7 @@ func Test500Page(t *testing.T) { t.Fatalf("HTML validation failed for error page returned!") } } + func Test500PageWith0xHashPrefix(t *testing.T) { srv := NewTestSwarmServer(t, serverFunc, nil) defer srv.Close() @@ -161,7 +162,6 @@ func TestJsonResponse(t *testing.T) { if !isJSON(string(respbody)) { t.Fatalf("Expected response to be JSON, received invalid JSON: %s", string(respbody)) } - } func isJSON(s string) bool { diff --git a/swarm/api/http/roundtripper_test.go b/swarm/api/http/roundtripper_test.go index f99c4f35e0..948429075c 100644 --- a/swarm/api/http/roundtripper_test.go +++ b/swarm/api/http/roundtripper_test.go @@ -65,5 +65,4 @@ func TestRoundTripper(t *testing.T) { if string(content) != "/HTTP/1.1:/test.com/path" { t.Errorf("incorrect response from http server: expected '%v', got '%v'", "/HTTP/1.1:/test.com/path", string(content)) } - } diff --git a/swarm/api/http/server.go b/swarm/api/http/server.go index 3c6735a73e..abc3423a5a 100644 --- a/swarm/api/http/server.go +++ b/swarm/api/http/server.go @@ -796,8 +796,8 @@ func (s *Server) HandleGetFile(w http.ResponseWriter, r *http.Request) { return } - //the request results in ambiguous files - //e.g. /read with readme.md and readinglist.txt available in manifest + // the request results in ambiguous files + // e.g. /read with readme.md and readinglist.txt available in manifest if status == http.StatusMultipleChoices { list, err := s.api.GetManifestList(r.Context(), s.api.Decryptor(r.Context(), credentials), manifestAddr, uri.Path) if err != nil { @@ -812,7 +812,7 @@ func (s *Server) HandleGetFile(w http.ResponseWriter, r *http.Request) { } log.Debug(fmt.Sprintf("Multiple choices! --> %v", list), "ruid", ruid) - //show a nice page links to available entries + // show a nice page links to available entries ShowMultipleChoices(w, r, list) return } diff --git a/swarm/api/http/server_test.go b/swarm/api/http/server_test.go index e82762ce05..bad8d17668 100644 --- a/swarm/api/http/server_test.go +++ b/swarm/api/http/server_test.go @@ -75,7 +75,6 @@ func newTestSigner() (*feed.GenericSigner, error) { // Retrieving the update with the Swarm hash should return the manifest pointing directly to the data // and raw retrieve of that hash should return the data func TestBzzWithFeed(t *testing.T) { - signer, _ := newTestSigner() // Initialize Swarm test server @@ -205,7 +204,7 @@ func TestBzzFeed(t *testing.T) { // data of update 1 update1Data := testutil.RandomBytes(1, 666) update1Timestamp := srv.CurrentTime - //data for update 2 + // data for update 2 update2Data := []byte("foo") topic, _ := feed.NewTopic("foo.eth", nil) @@ -444,7 +443,6 @@ func TestBzzFeed(t *testing.T) { if !bytes.Equal(update1Data, b) { t.Fatalf("Expected body '%x', got '%x'", update1Data, b) } - } func TestBzzGetPath(t *testing.T) { @@ -745,7 +743,7 @@ func testBzzTar(encrypted bool, t *testing.T) { } } - //post tar stream + // post tar stream url := srv.URL + "/bzz:/" if encrypted { url = url + "encrypt" @@ -842,6 +840,7 @@ func testBzzTar(encrypted bool, t *testing.T) { func TestBzzRootRedirect(t *testing.T) { testBzzRootRedirect(false, t) } + func TestBzzRootRedirectEncrypted(t *testing.T) { testBzzRootRedirect(true, t) } @@ -926,7 +925,6 @@ func TestMethodsNotAllowed(t *testing.T) { t.Fatalf("should have failed. requested url: %s, expected code %d, got %d", c.url, c.code, res.StatusCode) } } - } func httpDo(httpMethod string, url string, reqBody io.Reader, headers map[string]string, verbose bool, t *testing.T) (*http.Response, string) { @@ -1030,7 +1028,8 @@ func TestGet(t *testing.T) { headers: map[string]string{}, expectedStatusCode: http.StatusNotFound, verbose: false, - }} { + }, + } { t.Run("GET "+testCase.uri, func(t *testing.T) { res, body := httpDo(testCase.method, testCase.uri, nil, testCase.headers, testCase.verbose, t) if res.StatusCode != testCase.expectedStatusCode { @@ -1212,7 +1211,7 @@ func TestBzzGetFileWithResolver(t *testing.T) { t.Fatal(err) } - //post tar stream + // post tar stream url := srv.URL + "/bzz:/" req, err := http.NewRequest("POST", url, buf) @@ -1308,6 +1307,7 @@ func (t *testResolveValidator) Resolve(addr string) (common.Hash, error) { func (t *testResolveValidator) Owner(node [32]byte) (addr common.Address, err error) { return } + func (t *testResolveValidator) HeaderByNumber(context.Context, *big.Int) (header *types.Header, err error) { return } diff --git a/swarm/api/manifest.go b/swarm/api/manifest.go index 890ed88bd4..59086bfbf9 100644 --- a/swarm/api/manifest.go +++ b/swarm/api/manifest.go @@ -411,7 +411,6 @@ func (mt *manifestTrie) recalcAndStore() error { } list.Entries = append(list.Entries, entry.ManifestEntry) } - } manifest, err := json.Marshal(list) @@ -506,7 +505,7 @@ func (mt *manifestTrie) findPrefixOf(path string, quitC chan bool) (entry *manif return mt.entries[256], 0 } - //see if first char is in manifest entries + // see if first char is in manifest entries b := path[0] entry = mt.entries[b] if entry == nil { @@ -537,7 +536,7 @@ func (mt *manifestTrie) findPrefixOf(path string, quitC chan bool) (entry *manif } if path[:epl] == entry.Path { log.Trace(fmt.Sprintf("entry.ContentType = %v", entry.ContentType)) - //the subentry is a manifest, load subtrie + // the subentry is a manifest, load subtrie if entry.ContentType == ManifestType && (strings.Contains(entry.Path, path) || strings.Contains(path, entry.Path)) { err := mt.loadSubTrie(entry, quitC) if err != nil { @@ -553,7 +552,7 @@ func (mt *manifestTrie) findPrefixOf(path string, quitC chan bool) (entry *manif } } else { - //entry is not a manifest, return it + // entry is not a manifest, return it if path != entry.Path { return nil, 0 } diff --git a/swarm/api/manifest_test.go b/swarm/api/manifest_test.go index 1c8e53c433..ee3400edaf 100644 --- a/swarm/api/manifest_test.go +++ b/swarm/api/manifest_test.go @@ -115,7 +115,6 @@ func TestExactMatch(t *testing.T) { } func TestDeleteEntry(t *testing.T) { - } // TestAddFileWithManifestPath tests that adding an entry at a path which diff --git a/swarm/api/uri.go b/swarm/api/uri.go index 09cfa45020..7f4810a81c 100644 --- a/swarm/api/uri.go +++ b/swarm/api/uri.go @@ -26,7 +26,7 @@ import ( "github.com/ethereum/go-ethereum/swarm/storage" ) -//matches hex swarm hashes +// matches hex swarm hashes // TODO: this is bad, it should not be hardcoded how long is a hash var hashMatcher = regexp.MustCompile("^([0-9A-Fa-f]{64})([0-9A-Fa-f]{64})?$") @@ -108,6 +108,7 @@ func Parse(rawuri string) (*URI, error) { } return uri, nil } + func (u *URI) Feed() bool { return u.Scheme == "bzz-feed" } diff --git a/swarm/api/uri_test.go b/swarm/api/uri_test.go index a03874c433..651952ee9c 100644 --- a/swarm/api/uri_test.go +++ b/swarm/api/uri_test.go @@ -124,12 +124,14 @@ func TestParseURI(t *testing.T) { }, { uri: "bzz-raw://4378d19c26590f1a818ed7d6a62c3809e149b0999cab5ce5f26233b3b423bf8c", - expectURI: &URI{Scheme: "bzz-raw", - Addr: "4378d19c26590f1a818ed7d6a62c3809e149b0999cab5ce5f26233b3b423bf8c", + expectURI: &URI{ + Scheme: "bzz-raw", + Addr: "4378d19c26590f1a818ed7d6a62c3809e149b0999cab5ce5f26233b3b423bf8c", }, expectValidKey: true, expectRaw: true, - expectAddr: storage.Address{67, 120, 209, 156, 38, 89, 15, 26, + expectAddr: storage.Address{ + 67, 120, 209, 156, 38, 89, 15, 26, 129, 142, 215, 214, 166, 44, 56, 9, 225, 73, 176, 153, 156, 171, 92, 229, 242, 98, 51, 179, 180, 35, 191, 140, diff --git a/swarm/bmt/bmt.go b/swarm/bmt/bmt.go index 18eab5a2bc..74f286eaad 100644 --- a/swarm/bmt/bmt.go +++ b/swarm/bmt/bmt.go @@ -54,11 +54,9 @@ Two implementations are provided: * AsyncWriter - concurrent section writes and asynchronous Sum call */ -const ( - // PoolSize is the maximum number of bmt trees used by the hashers, i.e, - // the maximum number of concurrent BMT hashing operations performed by the same hasher - PoolSize = 8 -) +// PoolSize is the maximum number of bmt trees used by the hashers, i.e, +// the maximum number of concurrent BMT hashing operations performed by the same hasher +const PoolSize = 8 // BaseHasherFunc is a hash.Hash constructor function used for the base hash of the BMT. // implemented by Keccak256 SHA3 sha3.NewLegacyKeccak256 @@ -591,7 +589,6 @@ func (h *Hasher) writeNode(n *node, bh hash.Hash, isLeft bool, s []byte) { // the pool's lookup table for BMT subtree root hashes for all-zero sections // otherwise behaves like `writeNode` func (h *Hasher) writeFinalNode(level int, n *node, bh hash.Hash, isLeft bool, s []byte) { - for { // at the root of the bmt just write the result to the result channel if n == nil { diff --git a/swarm/bmt/bmt_r.go b/swarm/bmt/bmt_r.go index 0cb6c146f5..b0dade527d 100644 --- a/swarm/bmt/bmt_r.go +++ b/swarm/bmt/bmt_r.go @@ -25,9 +25,7 @@ // * testBMTHasherCorrectness function package bmt -import ( - "hash" -) +import "hash" // RefHasher is the non-optimized easy-to-read reference implementation of BMT type RefHasher struct { diff --git a/swarm/bmt/bmt_test.go b/swarm/bmt/bmt_test.go index ab712d08c2..01d5b03649 100644 --- a/swarm/bmt/bmt_test.go +++ b/swarm/bmt/bmt_test.go @@ -33,12 +33,10 @@ import ( // the actual data length generated (could be longer than max datalength of the BMT) const BufferSize = 4128 -const ( - // segmentCount is the maximum number of segments of the underlying chunk - // Should be equal to max-chunk-data-size / hash-size - // Currently set to 128 == 4096 (default chunk size) / 32 (sha3.keccak256 size) - segmentCount = 128 -) +// segmentCount is the maximum number of segments of the underlying chunk +// Should be equal to max-chunk-data-size / hash-size +// Currently set to 128 == 4096 (default chunk size) / 32 (sha3.keccak256 size) +const segmentCount = 128 var counts = []int{1, 2, 3, 4, 5, 8, 9, 15, 16, 17, 32, 37, 42, 53, 63, 64, 65, 111, 127, 128} diff --git a/swarm/fuse/fuse_file.go b/swarm/fuse/fuse_file.go index ca04f737e2..ef9ba0eb6a 100644 --- a/swarm/fuse/fuse_file.go +++ b/swarm/fuse/fuse_file.go @@ -31,9 +31,7 @@ import ( "golang.org/x/net/context" ) -const ( - MaxAppendFileSize = 10485760 // 10Mb -) +const MaxAppendFileSize = 10485760 // 10Mb var ( errInvalidOffset = errors.New("Invalid offset during write") @@ -78,7 +76,7 @@ func (sf *SwarmFile) Attr(ctx context.Context, a *fuse.Attr) error { sf.lock.Lock() defer sf.lock.Unlock() a.Inode = sf.inode - //TODO: need to get permission as argument + // TODO: need to get permission as argument a.Mode = 0700 a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getegid()) diff --git a/swarm/fuse/fuse_root.go b/swarm/fuse/fuse_root.go index b2262d1c5a..0c8fd42d1f 100644 --- a/swarm/fuse/fuse_root.go +++ b/swarm/fuse/fuse_root.go @@ -18,13 +18,9 @@ package fuse -import ( - "bazil.org/fuse/fs" -) +import "bazil.org/fuse/fs" -var ( - _ fs.Node = (*SwarmDir)(nil) -) +var _ fs.Node = (*SwarmDir)(nil) type SwarmRoot struct { root *SwarmDir diff --git a/swarm/fuse/swarmfs.go b/swarm/fuse/swarmfs.go index db6aefb54c..7badd43610 100644 --- a/swarm/fuse/swarmfs.go +++ b/swarm/fuse/swarmfs.go @@ -53,7 +53,6 @@ func NewSwarmFS(api *api.API) *SwarmFS { } }) return swarmfs - } // Inode numbers need to be unique, they are used for caching inside fuse diff --git a/swarm/fuse/swarmfs_fallback.go b/swarm/fuse/swarmfs_fallback.go index 4864c8689c..9ba08c2be5 100644 --- a/swarm/fuse/swarmfs_fallback.go +++ b/swarm/fuse/swarmfs_fallback.go @@ -18,9 +18,7 @@ package fuse -import ( - "errors" -) +import "errors" var errNoFUSE = errors.New("FUSE is not supported on this platform") diff --git a/swarm/fuse/swarmfs_test.go b/swarm/fuse/swarmfs_test.go index 460e31c4e9..fa37d34c3c 100644 --- a/swarm/fuse/swarmfs_test.go +++ b/swarm/fuse/swarmfs_test.go @@ -55,27 +55,26 @@ type fileInfo struct { contents []byte } -//create files from the map of name and content provided and upload them to swarm via api +// create files from the map of name and content provided and upload them to swarm via api func createTestFilesAndUploadToSwarm(t *testing.T, api *api.API, files map[string]fileInfo, uploadDir string, toEncrypt bool) string { - - //iterate the map + // iterate the map for fname, finfo := range files { actualPath := filepath.Join(uploadDir, fname) filePath := filepath.Dir(actualPath) - //create directory + // create directory err := os.MkdirAll(filePath, 0777) if err != nil { t.Fatalf("Error creating directory '%v' : %v", filePath, err) } - //create file + // create file fd, err1 := os.OpenFile(actualPath, os.O_RDWR|os.O_CREATE, os.FileMode(finfo.perm)) if err1 != nil { t.Fatalf("Error creating file %v: %v", actualPath, err1) } - //write content to file + // write content to file _, err = fd.Write(finfo.contents) if err != nil { t.Fatalf("Error writing to file '%v' : %v", filePath, err) @@ -108,7 +107,7 @@ func createTestFilesAndUploadToSwarm(t *testing.T, api *api.API, files map[strin } } - //upload directory to swarm and return hash + // upload directory to swarm and return hash bzzhash, err := Upload(uploadDir, "", api, toEncrypt) if err != nil { t.Fatalf("Error uploading directory %v: %vm encryption: %v", uploadDir, err, toEncrypt) @@ -117,7 +116,7 @@ func createTestFilesAndUploadToSwarm(t *testing.T, api *api.API, files map[strin return bzzhash } -//mount a swarm hash as a directory on files system via FUSE +// mount a swarm hash as a directory on files system via FUSE func mountDir(t *testing.T, api *api.API, files map[string]fileInfo, bzzHash string, mountDir string) *SwarmFS { swarmfs := NewSwarmFS(api) _, err := swarmfs.Mount(bzzHash, mountDir) @@ -127,7 +126,7 @@ func mountDir(t *testing.T, api *api.API, files map[string]fileInfo, bzzHash str t.Fatalf("Error mounting hash %v: %v", bzzHash, err) } - //check directory is mounted + // check directory is mounted found := false mi := swarmfs.Listmounts() for _, minfo := range mi { @@ -198,7 +197,7 @@ func compareGeneratedFileWithFileInMount(t *testing.T, files map[string]fileInfo } } -//check mounted file with provided content +// check mounted file with provided content func checkFile(t *testing.T, testMountDir, fname string, contents []byte) { destinationFile := filepath.Join(testMountDir, fname) dfinfo, err1 := os.Stat(destinationFile) @@ -254,7 +253,7 @@ type testData struct { swarmfs *SwarmFS } -//create the root dir of a test +// create the root dir of a test func (ta *testAPI) initSubtest(name string) (*testData, error) { var err error d := &testData{} @@ -265,28 +264,28 @@ func (ta *testAPI) initSubtest(name string) (*testData, error) { return d, nil } -//upload data and mount directory +// upload data and mount directory func (ta *testAPI) uploadAndMount(dat *testData, t *testing.T) (*testData, error) { - //create upload dir + // create upload dir err := os.MkdirAll(dat.testUploadDir, 0777) if err != nil { return nil, fmt.Errorf("Couldn't create upload dir: %v", err) } - //create mount dir + // create mount dir err = os.MkdirAll(dat.testMountDir, 0777) if err != nil { return nil, fmt.Errorf("Couldn't create mount dir: %v", err) } - //upload the file + // upload the file dat.bzzHash = createTestFilesAndUploadToSwarm(t, ta.api, dat.files, dat.testUploadDir, dat.toEncrypt) log.Debug("Created test files and uploaded to Swarm") - //mount the directory + // mount the directory dat.swarmfs = mountDir(t, ta.api, dat.files, dat.bzzHash, dat.testMountDir) log.Debug("Mounted swarm fs") return dat, nil } -//add a directory to the test directory tree +// add a directory to the test directory tree func addDir(root string, name string) (string, error) { d := filepath.Join(root, name) err := os.MkdirAll(d, 0777) @@ -308,7 +307,7 @@ func (ta *testAPI) mountListAndUnmountNonEncrypted(t *testing.T) { log.Debug("Test mountListAndUnmountNonEncrypted terminated") } -//mount a directory unmount and check the directory is empty afterwards +// mount a directory unmount and check the directory is empty afterwards func (ta *testAPI) mountListAndUnmount(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("mountListAndUnmount") if err != nil { @@ -367,7 +366,7 @@ func (ta *testAPI) maxMountsNonEncrypted(t *testing.T) { log.Debug("Test maxMountsNonEncrypted terminated") } -//mount several different directories until the maximum has been reached +// mount several different directories until the maximum has been reached func (ta *testAPI) runMaxMounts(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("runMaxMounts") if err != nil { @@ -423,7 +422,7 @@ func (ta *testAPI) runMaxMounts(t *testing.T, toEncrypt bool) { t.Fatalf("Error during upload of files to swarm / mount of swarm dir: %v", err) } - //now try an additional mount, should fail due to max mounts reached + // now try an additional mount, should fail due to max mounts reached testUploadDir6 := filepath.Join(dat.testDir, "max-upload6") err = os.MkdirAll(testUploadDir6, 0777) if err != nil { @@ -449,13 +448,14 @@ func (ta *testAPI) remountEncrypted(t *testing.T) { ta.remount(t, true) log.Debug("Test remountEncrypted terminated") } + func (ta *testAPI) remountNonEncrypted(t *testing.T) { log.Debug("Starting remountNonEncrypted test") ta.remount(t, false) log.Debug("Test remountNonEncrypted terminated") } -//test remounting same hash second time and different hash in already mounted point +// test remounting same hash second time and different hash in already mounted point func (ta *testAPI) remount(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("remount") if err != nil { @@ -524,7 +524,7 @@ func (ta *testAPI) unmountNonEncrypted(t *testing.T) { log.Debug("Test unmountNonEncrypted terminated") } -//mount then unmount and check that it has been unmounted +// mount then unmount and check that it has been unmounted func (ta *testAPI) unmount(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("unmount") if err != nil { @@ -566,13 +566,14 @@ func (ta *testAPI) unmountWhenResourceBusyEncrypted(t *testing.T) { ta.unmountWhenResourceBusy(t, true) log.Debug("Test unmountWhenResourceBusyEncrypted terminated") } + func (ta *testAPI) unmountWhenResourceBusyNonEncrypted(t *testing.T) { log.Debug("Starting unmountWhenResourceBusyNonEncrypted test") ta.unmountWhenResourceBusy(t, false) log.Debug("Test unmountWhenResourceBusyNonEncrypted terminated") } -//unmount while a resource is busy; should fail +// unmount while a resource is busy; should fail func (ta *testAPI) unmountWhenResourceBusy(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("unmountWhenResourceBusy") if err != nil { @@ -592,15 +593,15 @@ func (ta *testAPI) unmountWhenResourceBusy(t *testing.T, toEncrypt bool) { } defer dat.swarmfs.Stop() - //create a file in the mounted directory, then try to unmount - should fail + // create a file in the mounted directory, then try to unmount - should fail actualPath := filepath.Join(dat.testMountDir, "2.txt") - //d, err := os.OpenFile(actualPath, os.O_RDWR, os.FileMode(0700)) + // d, err := os.OpenFile(actualPath, os.O_RDWR, os.FileMode(0700)) d, err := os.Create(actualPath) if err != nil { t.Fatalf("Couldn't create new file: %v", err) } - //we need to manually close the file before mount for this test - //but let's defer too in case of errors + // we need to manually close the file before mount for this test + // but let's defer too in case of errors defer d.Close() _, err = d.Write(testutil.RandomBytes(1, 10)) if err != nil { @@ -612,19 +613,19 @@ func (ta *testAPI) unmountWhenResourceBusy(t *testing.T, toEncrypt bool) { if err == nil { t.Fatalf("Expected mount to fail due to resource busy, but it succeeded...") } - //free resources + // free resources err = d.Close() if err != nil { t.Fatalf("Couldn't close file! %v", dat.bzzHash) } log.Debug("File closed") - //now unmount after explicitly closed file + // now unmount after explicitly closed file _, err = dat.swarmfs.Unmount(dat.testMountDir) if err != nil { t.Fatalf("Expected mount to succeed after freeing resource, but it failed: %v", err) } - //check if the dir is still mounted + // check if the dir is still mounted mi := dat.swarmfs.Listmounts() log.Debug("Going to list mounts") for _, minfo := range mi { @@ -648,7 +649,7 @@ func (ta *testAPI) seekInMultiChunkFileNonEncrypted(t *testing.T) { log.Debug("Test seekInMultiChunkFileNonEncrypted terminated") } -//open a file in a mounted dir and go to a certain position +// open a file in a mounted dir and go to a certain position func (ta *testAPI) seekInMultiChunkFile(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("seekInMultiChunkFile") if err != nil { @@ -713,8 +714,8 @@ func (ta *testAPI) createNewFileNonEncrypted(t *testing.T) { log.Debug("Test createNewFileNonEncrypted terminated") } -//create a new file in a mounted swarm directory, -//unmount the fuse dir and then remount to see if new file is still there +// create a new file in a mounted swarm directory, +// unmount the fuse dir and then remount to see if new file is still there func (ta *testAPI) createNewFile(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("createNewFile") if err != nil { @@ -792,7 +793,7 @@ func (ta *testAPI) createNewFileInsideDirectoryNonEncrypted(t *testing.T) { log.Debug("Test createNewFileInsideDirectoryNonEncrypted terminated") } -//create a new file inside a directory inside the mount +// create a new file inside a directory inside the mount func (ta *testAPI) createNewFileInsideDirectory(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("createNewFileInsideDirectory") if err != nil { @@ -869,7 +870,7 @@ func (ta *testAPI) createNewFileInsideNewDirectoryNonEncrypted(t *testing.T) { log.Debug("Test createNewFileInsideNewDirectoryNonEncrypted terminated") } -//create a new directory in mount and a new file +// create a new directory in mount and a new file func (ta *testAPI) createNewFileInsideNewDirectory(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("createNewFileInsideNewDirectory") if err != nil { @@ -945,7 +946,7 @@ func (ta *testAPI) removeExistingFileNonEncrypted(t *testing.T) { log.Debug("Test removeExistingFileNonEncrypted terminated") } -//remove existing file in mount +// remove existing file in mount func (ta *testAPI) removeExistingFile(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("removeExistingFile") if err != nil { @@ -1005,7 +1006,7 @@ func (ta *testAPI) removeExistingFileInsideDirNonEncrypted(t *testing.T) { log.Debug("Test removeExistingFileInsideDirNonEncrypted terminated") } -//remove a file inside a directory inside a mount +// remove a file inside a directory inside a mount func (ta *testAPI) removeExistingFileInsideDir(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("removeExistingFileInsideDir") if err != nil { @@ -1073,7 +1074,7 @@ func (ta *testAPI) removeNewlyAddedFileNonEncrypted(t *testing.T) { log.Debug("Test removeNewlyAddedFileNonEncrypted terminated") } -//add a file in mount and then remove it; on remount file should not be there +// add a file in mount and then remove it; on remount file should not be there func (ta *testAPI) removeNewlyAddedFile(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("removeNewlyAddedFile") if err != nil { @@ -1166,7 +1167,7 @@ func (ta *testAPI) addNewFileAndModifyContentsNonEncrypted(t *testing.T) { log.Debug("Test addNewFileAndModifyContentsNonEncrypted terminated") } -//add a new file and modify content; remount and check the modified file is intact +// add a new file and modify content; remount and check the modified file is intact func (ta *testAPI) addNewFileAndModifyContents(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("addNewFileAndModifyContents") if err != nil { @@ -1195,7 +1196,7 @@ func (ta *testAPI) addNewFileAndModifyContents(t *testing.T, toEncrypt bool) { t.Fatalf("Could not create file %s : %v", actualPath, err1) } defer d.Close() - //write some random data into the file + // write some random data into the file log.Debug("file opened") line1 := []byte("Line 1") _, err = rand.Read(line1) @@ -1214,14 +1215,14 @@ func (ta *testAPI) addNewFileAndModifyContents(t *testing.T, toEncrypt bool) { } log.Debug("file closed") - //unmount the hash on the mounted dir + // unmount the hash on the mounted dir mi1, err2 := dat.swarmfs.Unmount(dat.testMountDir) if err2 != nil { t.Fatalf("Could not unmount %v", err2) } log.Debug("Directory unmounted") - //mount on a different dir to see if modified file is correct + // mount on a different dir to see if modified file is correct testMountDir2, err3 := addDir(dat.testDir, "modifyfile-mount2") if err3 != nil { t.Fatalf("Error creating mount dir2: %v", err3) @@ -1233,15 +1234,15 @@ func (ta *testAPI) addNewFileAndModifyContents(t *testing.T, toEncrypt bool) { checkFile(t, testMountDir2, "2.txt", line1) log.Debug("file checked") - //unmount second dir + // unmount second dir mi2, err4 := dat.swarmfs.Unmount(testMountDir2) if err4 != nil { t.Fatalf("Could not unmount %v", err4) } log.Debug("Directory unmounted again") - //mount again on original dir and modify the file - //let's clean up the mounted dir first: remove... + // mount again on original dir and modify the file + // let's clean up the mounted dir first: remove... err = os.RemoveAll(dat.testMountDir) if err != nil { t.Fatalf("Error cleaning up mount dir: %v", err) @@ -1251,11 +1252,11 @@ func (ta *testAPI) addNewFileAndModifyContents(t *testing.T, toEncrypt bool) { if err != nil { t.Fatalf("Error re-creating mount dir: %v", err) } - //now remount + // now remount _ = mountDir(t, ta.api, dat.files, mi2.LatestManifest, dat.testMountDir) log.Debug("Directory mounted yet again") - //open the file.... + // open the file.... fd, err5 := os.OpenFile(actualPath, os.O_RDWR|os.O_APPEND, os.FileMode(0665)) if err5 != nil { t.Fatalf("Could not create file %s : %v", actualPath, err5) @@ -1284,14 +1285,14 @@ func (ta *testAPI) addNewFileAndModifyContents(t *testing.T, toEncrypt bool) { } log.Debug("file closed") - //unmount the modified directory + // unmount the modified directory mi3, err6 := dat.swarmfs.Unmount(dat.testMountDir) if err6 != nil { t.Fatalf("Could not unmount %v", err6) } log.Debug("Directory unmounted yet again") - //now remount on a different dir and check that the modified file is ok + // now remount on a different dir and check that the modified file is ok testMountDir4, err7 := addDir(dat.testDir, "modifyfile-mount4") if err7 != nil { t.Fatalf("Could not unmount %v", err7) @@ -1322,7 +1323,7 @@ func (ta *testAPI) removeEmptyDirNonEncrypted(t *testing.T) { log.Debug("Test removeEmptyDirNonEncrypted terminated") } -//remove an empty dir inside mount +// remove an empty dir inside mount func (ta *testAPI) removeEmptyDir(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("removeEmptyDir") if err != nil { @@ -1353,7 +1354,7 @@ func (ta *testAPI) removeEmptyDir(t *testing.T, toEncrypt bool) { t.Fatalf("Could not unmount %v", err) } log.Debug("Directory unmounted") - //by just adding an empty dir, the hash doesn't change; test this + // by just adding an empty dir, the hash doesn't change; test this if dat.bzzHash != mi.LatestManifest { t.Fatalf("same contents different hash orig(%v): new(%v)", dat.bzzHash, mi.LatestManifest) } @@ -1365,13 +1366,14 @@ func (ta *testAPI) removeDirWhichHasFilesEncrypted(t *testing.T) { ta.removeDirWhichHasFiles(t, true) log.Debug("Test removeDirWhichHasFilesEncrypted terminated") } + func (ta *testAPI) removeDirWhichHasFilesNonEncrypted(t *testing.T) { log.Debug("Starting removeDirWhichHasFilesNonEncrypted test") ta.removeDirWhichHasFiles(t, false) log.Debug("Test removeDirWhichHasFilesNonEncrypted terminated") } -//remove a directory with a file; check on remount file isn't there +// remove a directory with a file; check on remount file isn't there func (ta *testAPI) removeDirWhichHasFiles(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("removeDirWhichHasFiles") if err != nil { @@ -1393,7 +1395,7 @@ func (ta *testAPI) removeDirWhichHasFiles(t *testing.T, toEncrypt bool) { } defer dat.swarmfs.Stop() - //delete a directory inside the mounted dir with all its files + // delete a directory inside the mounted dir with all its files dirPath := filepath.Join(dat.testMountDir, "two") err = os.RemoveAll(dirPath) if err != nil { @@ -1406,7 +1408,7 @@ func (ta *testAPI) removeDirWhichHasFiles(t *testing.T, toEncrypt bool) { } log.Debug("Directory unmounted") - //we deleted files in the OS, so let's delete them also in the files map + // we deleted files in the OS, so let's delete them also in the files map delete(dat.files, "two/five.txt") delete(dat.files, "two/six.txt") @@ -1445,7 +1447,7 @@ func (ta *testAPI) removeDirWhichHasSubDirsNonEncrypted(t *testing.T) { log.Debug("Test removeDirWhichHasSubDirsNonEncrypted terminated") } -//remove a directory with subdirectories inside mount; on remount check they are not there +// remove a directory with subdirectories inside mount; on remount check they are not there func (ta *testAPI) removeDirWhichHasSubDirs(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("removeDirWhichHasSubDirs") if err != nil { @@ -1476,14 +1478,14 @@ func (ta *testAPI) removeDirWhichHasSubDirs(t *testing.T, toEncrypt bool) { t.Fatalf("Error removing directory in mounted dir: %v", err) } - //delete a directory inside the mounted dir with all its files + // delete a directory inside the mounted dir with all its files mi, err2 := dat.swarmfs.Unmount(dat.testMountDir) if err2 != nil { t.Fatalf("Could not unmount %v ", err2) } log.Debug("Directory unmounted") - //we deleted files in the OS, so let's delete them also in the files map + // we deleted files in the OS, so let's delete them also in the files map delete(dat.files, "two/three/2.txt") delete(dat.files, "two/three/3.txt") delete(dat.files, "two/four/5.txt") @@ -1531,7 +1533,7 @@ func (ta *testAPI) appendFileContentsToEndNonEncrypted(t *testing.T) { log.Debug("Test appendFileContentsToEndNonEncrypted terminated") } -//append contents to the end of a file; remount and check it's intact +// append contents to the end of a file; remount and check it's intact func (ta *testAPI) appendFileContentsToEnd(t *testing.T, toEncrypt bool) { dat, err := ta.initSubtest("appendFileContentsToEnd") if err != nil { @@ -1604,10 +1606,10 @@ func (ta *testAPI) appendFileContentsToEnd(t *testing.T, toEncrypt bool) { log.Debug("subtest terminated") } -//run all the tests +// run all the tests func TestFUSE(t *testing.T) { t.Skip("disable fuse tests until they are stable") - //create a data directory for swarm + // create a data directory for swarm datadir, err := ioutil.TempDir("", "fuse") if err != nil { t.Fatalf("unable to create temp dir: %v", err) @@ -1620,8 +1622,8 @@ func TestFUSE(t *testing.T) { } ta := &testAPI{api: api.NewAPI(fileStore, nil, nil, nil)} - //run a short suite of tests - //approx time: 28s + // run a short suite of tests + // approx time: 28s t.Run("mountListAndUnmountEncrypted", ta.mountListAndUnmountEncrypted) t.Run("remountEncrypted", ta.remountEncrypted) t.Run("unmountWhenResourceBusyNonEncrypted", ta.unmountWhenResourceBusyNonEncrypted) @@ -1630,8 +1632,8 @@ func TestFUSE(t *testing.T) { t.Run("removeDirWhichHasFilesNonEncrypted", ta.removeDirWhichHasFilesNonEncrypted) t.Run("appendFileContentsToEndEncrypted", ta.appendFileContentsToEndEncrypted) - //provide longrunning flag to execute all tests - //approx time with longrunning: 140s + // provide longrunning flag to execute all tests + // approx time with longrunning: 140s if *longrunning { t.Run("mountListAndUnmountNonEncrypted", ta.mountListAndUnmountNonEncrypted) t.Run("maxMountsEncrypted", ta.maxMountsEncrypted) diff --git a/swarm/fuse/swarmfs_unix.go b/swarm/fuse/swarmfs_unix.go index 54b879a4da..e73697c7a4 100644 --- a/swarm/fuse/swarmfs_unix.go +++ b/swarm/fuse/swarmfs_unix.go @@ -120,7 +120,7 @@ func (swarmfs *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) { log.Trace("swarmfs mount: traversing manifest map") for suffix, entry := range manifestEntryMap { - if suffix == "" { //empty suffix means that the file has no name - i.e. this is the default entry in a manifest. Since we cannot have files without a name, let us ignore this entry + if suffix == "" { // empty suffix means that the file has no name - i.e. this is the default entry in a manifest. Since we cannot have files without a name, let us ignore this entry log.Warn("Manifest has an empty-path (default) entry which will be ignored in FUSE mount.") continue } @@ -166,7 +166,7 @@ func (swarmfs *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) { go func() { log.Info("swarmfs", "serving hash", mhash, "at", cleanedMountPoint) filesys := &SwarmRoot{root: rootDir} - //start serving the actual file system; see note below + // start serving the actual file system; see note below if err := fs.Serve(fconn, filesys); err != nil { log.Warn("swarmfs could not serve the requested hash", "error", err) serverr <- err @@ -214,8 +214,8 @@ func (swarmfs *SwarmFS) Mount(mhash, mountpoint string) (*MountInfo, error) { return nil, err case <-fconn.Ready: - //this signals that the actual mount point from the fuse.Mount call is ready; - //it does not signal though that the file system from fs.Serve is actually fully built up + // this signals that the actual mount point from the fuse.Mount call is ready; + // it does not signal though that the file system from fs.Serve is actually fully built up if err := fconn.MountError; err != nil { log.Error("Mounting error from fuse driver: ", "err", err) return nil, err diff --git a/swarm/log/log.go b/swarm/log/log.go index ce372632e8..c0e8363354 100644 --- a/swarm/log/log.go +++ b/swarm/log/log.go @@ -5,11 +5,9 @@ import ( "github.com/ethereum/go-ethereum/metrics" ) -const ( - // CallDepth is set to 1 in order to influence to reported line number of - // the log message with 1 skipped stack frame of calling l.Output() - CallDepth = 1 -) +// CallDepth is set to 1 in order to influence to reported line number of +// the log message with 1 skipped stack frame of calling l.Output() +const CallDepth = 1 // Warn is a convenient alias for log.Warn with stats func Warn(msg string, ctx ...interface{}) { diff --git a/swarm/network/bitvector/bitvector.go b/swarm/network/bitvector/bitvector.go index 9583285023..b9b021b8dc 100644 --- a/swarm/network/bitvector/bitvector.go +++ b/swarm/network/bitvector/bitvector.go @@ -16,9 +16,7 @@ package bitvector -import ( - "errors" -) +import "errors" var errInvalidLength = errors.New("invalid length") diff --git a/swarm/network/discovery_test.go b/swarm/network/discovery_test.go index 04e1b36fed..fe4447466e 100644 --- a/swarm/network/discovery_test.go +++ b/swarm/network/discovery_test.go @@ -257,6 +257,7 @@ type dummyMsgRW struct{} func (d *dummyMsgRW) ReadMsg() (p2p.Msg, error) { return p2p.Msg{}, nil } + func (d *dummyMsgRW) WriteMsg(msg p2p.Msg) error { return nil } diff --git a/swarm/network/fetcher_test.go b/swarm/network/fetcher_test.go index 4e464f10f3..b4207d9952 100644 --- a/swarm/network/fetcher_test.go +++ b/swarm/network/fetcher_test.go @@ -33,7 +33,7 @@ type mockRequester struct { // requests []Request requestC chan *Request // when a request is coming it is pushed to requestC waitTimes []time.Duration // with waitTimes[i] you can define how much to wait on the ith request (optional) - count int //counts the number of requests + count int // counts the number of requests quitC chan struct{} } @@ -344,7 +344,6 @@ func TestFetcherFactory(t *testing.T) { case <-time.After(200 * time.Millisecond): t.Fatalf("fetch timeout") } - } func TestFetcherRequestQuitRetriesRequest(t *testing.T) { diff --git a/swarm/network/kademlia.go b/swarm/network/kademlia.go index 304f9cd778..1c9deec962 100644 --- a/swarm/network/kademlia.go +++ b/swarm/network/kademlia.go @@ -687,7 +687,6 @@ type PeerPot struct { // used for testing only // TODO move to separate testing tools file func NewPeerPotMap(neighbourhoodSize int, addrs [][]byte) map[string]*PeerPot { - // create a table of all nodes for health check np := pot.NewPot(nil, 0) for _, addr := range addrs { @@ -769,7 +768,6 @@ func (k *Kademlia) isSaturated(peersPerBin []int, depth int) bool { } unsaturatedBins := make([]int, 0) k.conns.EachBin(k.base, Pof, 0, func(po, size int, f func(func(val pot.Val) bool) bool) bool { - if po >= depth { return false } diff --git a/swarm/network/kademlia_test.go b/swarm/network/kademlia_test.go index b4663eee5e..6a8f721e12 100644 --- a/swarm/network/kademlia_test.go +++ b/swarm/network/kademlia_test.go @@ -211,7 +211,6 @@ func TestHighMinBinSize(t *testing.T) { // TestHealthStrict tests the simplest definition of health // Which means whether we are connected to all neighbors we know of func TestHealthStrict(t *testing.T) { - // base address is all zeros // no peers // unhealthy (and lonely) @@ -444,7 +443,6 @@ func TestSuggestPeerFindPeers(t *testing.T) { tk.checkSuggestPeer("00000010", 0, false) tk.checkSuggestPeer("00000001", 0, false) tk.checkSuggestPeer("