2018-02-09 13:37:56 +00:00
|
|
|
package api
|
|
|
|
|
2019-03-21 10:48:47 +00:00
|
|
|
import (
|
2019-04-29 23:26:41 +00:00
|
|
|
"bytes"
|
|
|
|
"encoding/hex"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
2019-03-21 10:48:47 +00:00
|
|
|
|
2024-09-26 22:37:32 +00:00
|
|
|
"github.com/status-im/status-go/common"
|
2019-12-19 16:03:00 +00:00
|
|
|
"github.com/status-im/status-go/eth-node/crypto"
|
2019-03-21 10:48:47 +00:00
|
|
|
)
|
|
|
|
|
2018-06-27 08:11:45 +00:00
|
|
|
// RunAsync runs the specified function asynchronously.
|
2018-06-19 07:49:24 +00:00
|
|
|
func RunAsync(f func() error) <-chan error {
|
2018-02-09 13:37:56 +00:00
|
|
|
resp := make(chan error, 1)
|
|
|
|
go func() {
|
2024-09-26 22:37:32 +00:00
|
|
|
defer common.LogOnPanic()
|
2018-02-09 13:37:56 +00:00
|
|
|
err := f()
|
|
|
|
resp <- err
|
|
|
|
close(resp)
|
|
|
|
}()
|
|
|
|
return resp
|
|
|
|
}
|
2019-03-21 10:48:47 +00:00
|
|
|
|
|
|
|
// HashMessage calculates the hash of a message to be safely signed by the keycard
|
|
|
|
// The hash is calulcated as
|
2022-12-29 06:16:19 +00:00
|
|
|
//
|
|
|
|
// keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
|
|
|
|
//
|
2019-03-21 10:48:47 +00:00
|
|
|
// This gives context to the signed message and prevents signing of transactions.
|
2019-04-29 23:26:41 +00:00
|
|
|
func HashMessage(message string) ([]byte, error) {
|
|
|
|
buf := bytes.NewBufferString("\x19Ethereum Signed Message:\n")
|
|
|
|
if value, ok := decodeHexStrict(message); ok {
|
|
|
|
if _, err := buf.WriteString(strconv.Itoa(len(value))); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if _, err := buf.Write(value); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if _, err := buf.WriteString(strconv.Itoa(len(message))); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if _, err := buf.WriteString(message); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return crypto.Keccak256(buf.Bytes()), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func decodeHexStrict(s string) ([]byte, bool) {
|
|
|
|
if !strings.HasPrefix(s, "0x") {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
value, err := hex.DecodeString(s[2:])
|
|
|
|
if err != nil {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
return value, true
|
2019-03-21 10:48:47 +00:00
|
|
|
}
|