Skip to content

Commit

Permalink
change public recover logic, use sha256 hash (#42)
Browse files Browse the repository at this point in the history
* change publick recover logic, use sha256 hash

* add log
  • Loading branch information
huangzhiran authored Nov 7, 2024
1 parent 8a446c0 commit bcb1f18
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions api/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package api

import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
Expand Down Expand Up @@ -207,24 +208,32 @@ func (s *httpServer) owner(sigStr string, o any) (common.Address, error) {
if err != nil {
return common.Address{}, errors.Wrap(err, "failed to marshal request into json format")
}
h := crypto.Keccak256Hash(reqJson)

if a, err := s.recoverOwner(sigStr+"1b", h); err == nil {
slog.Info("recover owner with 27 success")
return a, nil
}
return s.recoverOwner(sigStr+"1c", h)
}

func (s *httpServer) recoverOwner(sigStr string, h common.Hash) (common.Address, error) {
sig, err := hexutil.Decode(sigStr)
if err != nil {
return common.Address{}, errors.Wrapf(err, "failed to decode signature from hex format, signature %s", sigStr)
}
hash := sha256.New()
hash.Write(reqJson)
h := hash.Sum(nil)

rID := []uint8{0, 1, 2, 3, 4, 27, 28}
for _, id := range rID {
ns := append(sig, byte(id))
slog.Info("current signature", "signature", hexutil.Encode(ns))
if a, err := s.recover(ns, h); err == nil {
slog.Info("recover owner success", "r_id", id)
return a, nil
} else {
slog.Error("failed to recover public key from signature", "error", err, "r_id", id)
}
}
return common.Address{}, errors.New("failed to recover public key from signature")
}

sigpk, err := crypto.SigToPub(h.Bytes(), sig)
func (s *httpServer) recover(sig, h []byte) (common.Address, error) {
sigpk, err := crypto.SigToPub(h, sig)
if err != nil {
return common.Address{}, errors.Wrapf(err, "failed to recover public key from signature, signature %s", sigStr)
return common.Address{}, errors.Wrapf(err, "failed to recover public key from signature")
}
return crypto.PubkeyToAddress(*sigpk), nil
}
Expand Down

0 comments on commit bcb1f18

Please sign in to comment.