Skip to content

Commit

Permalink
Merge pull request HuobiRDCenter#9 from shaodan/master
Browse files Browse the repository at this point in the history
Fix sha256 race condition panic
  • Loading branch information
eynzhang authored Sep 10, 2020
2 parents 2496a79 + 2c6e5b5 commit 5e9a2e6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
11 changes: 5 additions & 6 deletions internal/requestbuilder/signer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"hash"
"strings"
)

type Signer struct {
hash hash.Hash
key []byte
}

func (p *Signer) Init(key string) *Signer {
p.hash = hmac.New(sha256.New, []byte(key))
p.key = []byte(key)
return p
}

Expand All @@ -35,8 +34,8 @@ func (p *Signer) Sign(method string, host string, path string, parameters string
}

func (p *Signer) sign(payload string) string {
p.hash.Reset()
p.hash.Write([]byte(payload))
result := base64.StdEncoding.EncodeToString(p.hash.Sum(nil))
hash := hmac.New(sha256.New, p.key)
hash.Write([]byte(payload))
result := base64.StdEncoding.EncodeToString(hash.Sum(nil))
return result
}
22 changes: 22 additions & 0 deletions internal/requestbuilder/signer_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package requestbuilder

import (
"sync"
"testing"
)

Expand Down Expand Up @@ -36,3 +37,24 @@ func TestSigner_Sign_OneEmptyString_ReturnEmpty(t *testing.T) {
t.Errorf("expected: %s, actual: %s", expected, result)
}
}

func TestSigner_Sign_RaceCondition(t *testing.T) {
signer := new(Signer).Init("secret")

var r = 100
wg := sync.WaitGroup{}
wg.Add(r)
for i := 0; i < r; i++ {
go func() {
defer func() {
if r := recover(); r != nil {
t.Errorf("race condition: panic %s", r)
}
wg.Done()
}()
signer.Sign("GET", "api.huobi.pro", "/v1/account/history", "account-id=1&currency=btcusdt")
}()
}

wg.Wait()
}

0 comments on commit 5e9a2e6

Please sign in to comment.