signer: formatting

This commit is contained in:
Martin Holst Swende 2018-04-16 12:40:16 +02:00
parent 8472645167
commit 0942fcfefb
No known key found for this signature in database
GPG key ID: 683B438C05A5DDF0
6 changed files with 53 additions and 73 deletions

View file

@ -53,7 +53,7 @@ const ExternalApiVersion = "2.0.0"
// InternalApiVersion -- see intapi_changelog.md // InternalApiVersion -- see intapi_changelog.md
const InternalApiVersion = "2.0.0" const InternalApiVersion = "2.0.0"
const legal_warning = ` const legalWarning = `
WARNING! WARNING!
Clef is alpha software, and not yet publically released. This software has _not_ been audited, and there Clef is alpha software, and not yet publically released. This software has _not_ been audited, and there
@ -170,7 +170,7 @@ remove any stored credential for that address (keyfile)
func init() { func init() {
app.Name = "Clef" app.Name = "Clef"
app.Usage = "Manage ethereum Account operations" app.Usage = "Manage Ethereum account operations"
app.Flags = []cli.Flag{ app.Flags = []cli.Flag{
logLevelFlag, logLevelFlag,
keystoreFlag, keystoreFlag,
@ -215,7 +215,7 @@ func initializeSecrets(c *cli.Context) error {
return err return err
} }
if n != len(masterSeed) { if n != len(masterSeed) {
return fmt.Errorf("Failed to read enough random") return fmt.Errorf("failed to read enough random")
} }
err = os.Mkdir(configDir, 0700) err = os.Mkdir(configDir, 0700)
if err != nil && !os.IsExist(err) { if err != nil && !os.IsExist(err) {
@ -283,13 +283,13 @@ func addCredential(ctx *cli.Context) error {
pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey) pwkey := crypto.Keccak256([]byte("credentials"), stretchedKey)
// Initialize the encrypted storages // Initialize the encrypted storages
pw_storage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey) pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
key := ctx.Args().First() key := ctx.Args().First()
value := "" value := ""
if len(ctx.Args()) > 1 { if len(ctx.Args()) > 1 {
value = ctx.Args().Get(1) value = ctx.Args().Get(1)
} }
pw_storage.Put(key, value) pwStorage.Put(key, value)
log.Info("Credential store updated", "key", key) log.Info("Credential store updated", "key", key)
return nil return nil
} }
@ -300,9 +300,9 @@ func initialize(c *cli.Context) error {
if c.Bool(stdiouiFlag.Name) { if c.Bool(stdiouiFlag.Name) {
logOutput = os.Stderr logOutput = os.Stderr
// If using the stdioui, we can't do the 'confirm'-flow // If using the stdioui, we can't do the 'confirm'-flow
fmt.Fprintf(logOutput, legal_warning) fmt.Fprintf(logOutput, legalWarning)
} else { } else {
if !confirm(legal_warning) { if !confirm(legalWarning) {
return fmt.Errorf("aborted by user") return fmt.Errorf("aborted by user")
} }
} }
@ -351,9 +351,9 @@ func signer(c *cli.Context) error {
confkey := crypto.Keccak256([]byte("config"), stretchedKey) confkey := crypto.Keccak256([]byte("config"), stretchedKey)
// Initialize the encrypted storages // Initialize the encrypted storages
pw_storage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey) pwStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "credentials.json"), pwkey)
js_storage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "jsstorage.json"), jskey) jsStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "jsstorage.json"), jskey)
config_storage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confkey) configStorage := storage.NewAESEncryptedStorage(filepath.Join(vaultLocation, "config.json"), confkey)
//Do we have a rule-file? //Do we have a rule-file?
ruleJS, err := ioutil.ReadFile(c.String(ruleFlag.Name)) ruleJS, err := ioutil.ReadFile(c.String(ruleFlag.Name))
@ -363,12 +363,12 @@ func signer(c *cli.Context) error {
hasher := sha256.New() hasher := sha256.New()
hasher.Write(ruleJS) hasher.Write(ruleJS)
shasum := hasher.Sum(nil) shasum := hasher.Sum(nil)
stored_shasum := config_storage.Get("ruleset_sha256") storedShasum := configStorage.Get("ruleset_sha256")
if stored_shasum != hex.EncodeToString(shasum) { if storedShasum != hex.EncodeToString(shasum) {
log.Info("Could not validate ruleset hash, rules not enabled", "got", hex.EncodeToString(shasum), "expected", stored_shasum) log.Info("Could not validate ruleset hash, rules not enabled", "got", hex.EncodeToString(shasum), "expected", storedShasum)
} else { } else {
// Initialize rules // Initialize rules
ruleEngine, err := rules.NewRuleEvaluator(ui, js_storage, pw_storage) ruleEngine, err := rules.NewRuleEvaluator(ui, jsStorage, pwStorage)
if err != nil { if err != nil {
utils.Fatalf(err.Error()) utils.Fatalf(err.Error())
} }
@ -411,8 +411,7 @@ func signer(c *cli.Context) error {
if c.Bool(utils.RPCEnabledFlag.Name) { if c.Bool(utils.RPCEnabledFlag.Name) {
vhosts := splitAndTrim(c.GlobalString(utils.RPCVirtualHostsFlag.Name)) vhosts := splitAndTrim(c.GlobalString(utils.RPCVirtualHostsFlag.Name))
//!TODO cors := splitAndTrim(c.GlobalString(utils.RPCCORSDomainFlag.Name))
cors := []string{"*"}
// start http server // start http server
httpEndpoint := fmt.Sprintf("%s:%d", c.String(utils.RPCListenAddrFlag.Name), c.Int(rpcPortFlag.Name)) httpEndpoint := fmt.Sprintf("%s:%d", c.String(utils.RPCListenAddrFlag.Name), c.Int(rpcPortFlag.Name))
@ -433,7 +432,7 @@ func signer(c *cli.Context) error {
if c.IsSet(utils.IPCPathFlag.Name) { if c.IsSet(utils.IPCPathFlag.Name) {
ipcApiUrl = c.String(utils.IPCPathFlag.Name) ipcApiUrl = c.String(utils.IPCPathFlag.Name)
} else { } else {
ipcApiUrl = fmt.Sprintf("%s", filepath.Join(configDir, "clef.ipc")) ipcApiUrl = filepath.Join(configDir, "clef.ipc")
} }
listener, _, err := rpc.StartIPCEndpoint(func() bool { return true }, ipcApiUrl, rpcApi) listener, _, err := rpc.StartIPCEndpoint(func() bool { return true }, ipcApiUrl, rpcApi)
@ -464,10 +463,8 @@ func signer(c *cli.Context) error {
abortChan := make(chan os.Signal) abortChan := make(chan os.Signal)
signal.Notify(abortChan, os.Interrupt) signal.Notify(abortChan, os.Interrupt)
select { sig := <-abortChan
case sig := <-abortChan:
log.Info("Exiting...", "signal", sig) log.Info("Exiting...", "signal", sig)
}
return nil return nil
} }
@ -527,7 +524,7 @@ func readMasterKey(ctx *cli.Context) ([]byte, error) {
return nil, err return nil, err
} }
if len(masterKey) < 256 { if len(masterKey) < 256 {
return nil, fmt.Errorf("Master key of insufficient length, expected >255 bytes, got %d", len(masterKey)) return nil, fmt.Errorf("master key of insufficient length, expected >255 bytes, got %d", len(masterKey))
} }
// Create vault location // Create vault location
vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), masterKey)[:10])) vaultLocation := filepath.Join(configDir, common.Bytes2Hex(crypto.Keccak256([]byte("vault"), masterKey)[:10]))

View file

@ -128,7 +128,7 @@ func parseCallData(calldata []byte, abidata string) (*decodedCallData, error) {
// which can be consumed by the standard abi package. // which can be consumed by the standard abi package.
func MethodSelectorToAbi(selector string) ([]byte, error) { func MethodSelectorToAbi(selector string) ([]byte, error) {
re := regexp.MustCompile("^([^\\)]+)\\(([a-z0-9,\\[\\]]*)\\)") re := regexp.MustCompile(`^([^\)]+)\(([a-z0-9,\[\]]*)\)`)
type fakeArg struct { type fakeArg struct {
Type string `json:"type"` Type string `json:"type"`

View file

@ -125,8 +125,7 @@ func setup(t *testing.T) (*SignerAPI, chan string) {
controller := make(chan string, 10) controller := make(chan string, 10)
db, err := NewAbiDBFromFile(fmt.Sprintf("../4byte.json")) db, err := NewAbiDBFromFile("../../cmd/clef/4byte.json")
if err != nil { if err != nil {
utils.Fatalf(err.Error()) utils.Fatalf(err.Error())
} }

View file

@ -51,51 +51,39 @@ func (ui *StdIOUI) dispatch(serviceMethod string, args interface{}, reply interf
func (ui *StdIOUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) { func (ui *StdIOUI) ApproveTx(request *SignTxRequest) (SignTxResponse, error) {
var result SignTxResponse var result SignTxResponse
if err := ui.dispatch("ApproveTx", request, &result); err != nil { err := ui.dispatch("ApproveTx", request, &result)
return result, err return result, err
} }
return result, nil
}
func (ui *StdIOUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) { func (ui *StdIOUI) ApproveSignData(request *SignDataRequest) (SignDataResponse, error) {
var result SignDataResponse var result SignDataResponse
if err := ui.dispatch("ApproveSignData", request, &result); err != nil { err := ui.dispatch("ApproveSignData", request, &result)
return result, err return result, err
} }
return result, nil
}
func (ui *StdIOUI) ApproveExport(request *ExportRequest) (ExportResponse, error) { func (ui *StdIOUI) ApproveExport(request *ExportRequest) (ExportResponse, error) {
var result ExportResponse var result ExportResponse
if err := ui.dispatch("ApproveExport", request, &result); err != nil { err := ui.dispatch("ApproveExport", request, &result)
return result, err return result, err
} }
return result, nil
}
func (ui *StdIOUI) ApproveImport(request *ImportRequest) (ImportResponse, error) { func (ui *StdIOUI) ApproveImport(request *ImportRequest) (ImportResponse, error) {
var result ImportResponse var result ImportResponse
if err := ui.dispatch("ApproveImport", request, &result); err != nil { err := ui.dispatch("ApproveImport", request, &result)
return result, err return result, err
} }
return result, nil
}
func (ui *StdIOUI) ApproveListing(request *ListRequest) (ListResponse, error) { func (ui *StdIOUI) ApproveListing(request *ListRequest) (ListResponse, error) {
var result ListResponse var result ListResponse
if err := ui.dispatch("ApproveListing", request, &result); err != nil { err := ui.dispatch("ApproveListing", request, &result)
return result, err return result, err
} }
return result, nil
}
func (ui *StdIOUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) { func (ui *StdIOUI) ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) {
var result NewAccountResponse var result NewAccountResponse
if err := ui.dispatch("ApproveNewAccount", request, &result); err != nil { err := ui.dispatch("ApproveNewAccount", request, &result)
return result, err return result, err
} }
return result, nil
}
func (ui *StdIOUI) ShowError(message string) { func (ui *StdIOUI) ShowError(message string) {
err := ui.dispatch("ShowError", &Message{message}, nil) err := ui.dispatch("ShowError", &Message{message}, nil)

View file

@ -100,7 +100,6 @@ func (v *Validator) validateCallData(msgs *ValidationMessages, data []byte, meth
} else { } else {
msgs.info(info.String()) msgs.info(info.String())
} }
return
} }
// validateSemantics checks if the transactions 'makes sense', and generate warnings for a couple of typical scenarios // validateSemantics checks if the transactions 'makes sense', and generate warnings for a couple of typical scenarios

View file

@ -68,7 +68,6 @@ function test(thing){
` `
func hexAddr(a string) common.Address { return common.BytesToAddress(common.Hex2Bytes(a)) }
func mixAddr(a string) (*common.MixedcaseAddress, error) { func mixAddr(a string) (*common.MixedcaseAddress, error) {
return common.NewMixedcaseAddressFromString(a) return common.NewMixedcaseAddressFromString(a)
} }
@ -79,27 +78,27 @@ func (alwaysDenyUi) OnSignerStartup(info core.StartupInfo) {
} }
func (alwaysDenyUi) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) { func (alwaysDenyUi) ApproveTx(request *core.SignTxRequest) (core.SignTxResponse, error) {
return core.SignTxResponse{request.Transaction, false, ""}, nil return core.SignTxResponse{Transaction: request.Transaction, Approved: false, Password: ""}, nil
} }
func (alwaysDenyUi) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) { func (alwaysDenyUi) ApproveSignData(request *core.SignDataRequest) (core.SignDataResponse, error) {
return core.SignDataResponse{false, ""}, nil return core.SignDataResponse{Approved: false, Password: ""}, nil
} }
func (alwaysDenyUi) ApproveExport(request *core.ExportRequest) (core.ExportResponse, error) { func (alwaysDenyUi) ApproveExport(request *core.ExportRequest) (core.ExportResponse, error) {
return core.ExportResponse{false}, nil return core.ExportResponse{Approved: false}, nil
} }
func (alwaysDenyUi) ApproveImport(request *core.ImportRequest) (core.ImportResponse, error) { func (alwaysDenyUi) ApproveImport(request *core.ImportRequest) (core.ImportResponse, error) {
return core.ImportResponse{false, "", ""}, nil return core.ImportResponse{Approved: false, OldPassword: "", NewPassword: ""}, nil
} }
func (alwaysDenyUi) ApproveListing(request *core.ListRequest) (core.ListResponse, error) { func (alwaysDenyUi) ApproveListing(request *core.ListRequest) (core.ListResponse, error) {
return core.ListResponse{nil}, nil return core.ListResponse{Accounts: nil}, nil
} }
func (alwaysDenyUi) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) { func (alwaysDenyUi) ApproveNewAccount(request *core.NewAccountRequest) (core.NewAccountResponse, error) {
return core.NewAccountResponse{false, ""}, nil return core.NewAccountResponse{Approved: false, Password: ""}, nil
} }
func (alwaysDenyUi) ShowError(message string) { func (alwaysDenyUi) ShowError(message string) {
@ -117,10 +116,10 @@ func (alwaysDenyUi) OnApprovedTx(tx ethapi.SignTransactionResult) {
func initRuleEngine(js string) (*rulesetUi, error) { func initRuleEngine(js string) (*rulesetUi, error) {
r, err := NewRuleEvaluator(&alwaysDenyUi{}, storage.NewEphemeralStorage(), storage.NewEphemeralStorage()) r, err := NewRuleEvaluator(&alwaysDenyUi{}, storage.NewEphemeralStorage(), storage.NewEphemeralStorage())
if err != nil { if err != nil {
return nil, fmt.Errorf("Failed to create js engine: %v", err) return nil, fmt.Errorf("failed to create js engine: %v", err)
} }
if err = r.Init(js); err != nil { if err = r.Init(js); err != nil {
return nil, fmt.Errorf("Failed to load bootstrap js: %v", err) return nil, fmt.Errorf("failed to load bootstrap js: %v", err)
} }
return r, nil return r, nil
} }
@ -145,10 +144,8 @@ func TestListRequest(t *testing.T) {
return return
} }
resp, err := r.ApproveListing(&core.ListRequest{ resp, err := r.ApproveListing(&core.ListRequest{
accs, Accounts: accs,
core.Metadata{ Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"},
"remoteip", "localip", "inproc",
},
}) })
if len(resp.Accounts) != len(accs) { if len(resp.Accounts) != len(accs) {
t.Errorf("Expected check to resolve to 'Approve'") t.Errorf("Expected check to resolve to 'Approve'")
@ -189,7 +186,7 @@ func TestSignTxRequest(t *testing.T) {
From: *from, From: *from,
To: to}, To: to},
Callinfo: nil, Callinfo: nil,
Meta: core.Metadata{"remoteip", "localip", "inproc"}, Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"},
}) })
if err != nil { if err != nil {
t.Errorf("Unexpected error %v", err) t.Errorf("Unexpected error %v", err)
@ -252,9 +249,9 @@ func TestForwarding(t *testing.T) {
js := "" js := ""
ui := &dummyUi{make([]string, 0)} ui := &dummyUi{make([]string, 0)}
jsbackend := storage.NewEphemeralStorage() jsBackend := storage.NewEphemeralStorage()
credbackend := storage.NewEphemeralStorage() credBackend := storage.NewEphemeralStorage()
r, err := NewRuleEvaluator(ui, jsbackend, credbackend) r, err := NewRuleEvaluator(ui, jsBackend, credBackend)
if err != nil { if err != nil {
t.Fatalf("Failed to create js engine: %v", err) t.Fatalf("Failed to create js engine: %v", err)
} }
@ -273,10 +270,10 @@ func TestForwarding(t *testing.T) {
//This one is not forwarded //This one is not forwarded
r.OnApprovedTx(ethapi.SignTransactionResult{}) r.OnApprovedTx(ethapi.SignTransactionResult{})
exp_calls := 8 expCalls := 8
if len(ui.calls) != exp_calls { if len(ui.calls) != expCalls {
t.Errorf("Expected %d forwarded calls, got %d: %s", exp_calls, len(ui.calls), strings.Join(ui.calls, ",")) t.Errorf("Expected %d forwarded calls, got %d: %s", expCalls, len(ui.calls), strings.Join(ui.calls, ","))
} }
@ -451,9 +448,9 @@ func dummyTx(value hexutil.Big) *core.SignTxRequest {
Gas: gas, Gas: gas,
}, },
Callinfo: []core.ValidationInfo{ Callinfo: []core.ValidationInfo{
{"Warning", "All your base are bellong to us"}, {Typ: "Warning", Message: "All your base are bellong to us"},
}, },
Meta: core.Metadata{"remoteip", "localip", "inproc"}, Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"},
} }
} }
func dummyTxWithV(value uint64) *core.SignTxRequest { func dummyTxWithV(value uint64) *core.SignTxRequest {
@ -622,7 +619,7 @@ function ApproveSignData(r){
Address: *addr, Address: *addr,
Message: msg, Message: msg,
Hash: hash, Hash: hash,
Meta: core.Metadata{"remoteip", "localip", "inproc"}, Meta: core.Metadata{Remote: "remoteip", Local: "localip", Scheme: "inproc"},
Rawdata: raw, Rawdata: raw,
}) })
if err != nil { if err != nil {