Skip to content

Commit 5f2e25d

Browse files
authored
Merge pull request #2851 from nspcc-dev/fuzz-tests
*: add fuzz tests for `bigint.FromBytes` and `vm.ParseMultisigContract`
2 parents d9af122 + db977ce commit 5f2e25d

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

pkg/encoding/bigint/fuzz_test.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//go:build go1.18
2+
// +build go1.18
3+
4+
package bigint
5+
6+
import (
7+
"bytes"
8+
"crypto/rand"
9+
"math/big"
10+
"testing"
11+
12+
"github.com/stretchr/testify/require"
13+
)
14+
15+
func FuzzFromBytes(f *testing.F) {
16+
for _, tc := range testCases {
17+
f.Add(tc.buf)
18+
}
19+
for i := 0; i < 50; i++ {
20+
for j := 1; j < MaxBytesLen; j++ {
21+
b := make([]byte, j)
22+
_, err := rand.Read(b)
23+
require.NoError(f, err)
24+
f.Add(b)
25+
}
26+
}
27+
f.Fuzz(func(t *testing.T, raw []byte) {
28+
var bi *big.Int
29+
require.NotPanics(t, func() { bi = FromBytes(raw) })
30+
31+
var actual []byte
32+
require.NotPanics(t, func() { actual = ToBytes(bi) })
33+
require.True(t, len(actual) <= len(raw), "actual: %x, raw: %x", actual, raw)
34+
35+
require.True(t, bytes.Equal(actual, raw[:len(actual)]), "actual: %x, raw: %x", actual, raw)
36+
if len(actual) == len(raw) {
37+
return
38+
}
39+
40+
var b byte
41+
if bi.Sign() == -1 {
42+
b = 0xFF
43+
}
44+
for i := len(actual); i < len(raw); i++ {
45+
require.Equal(t, b, raw[i], "invalid prefix")
46+
}
47+
48+
newRaw := ToBytes(bi)
49+
newBi := FromBytes(newRaw)
50+
require.Equal(t, bi, newBi)
51+
})
52+
}

pkg/vm/fuzz_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ package vm
55
import (
66
"testing"
77

8+
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
9+
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
810
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
911
"github.com/stretchr/testify/require"
1012
)
@@ -35,6 +37,35 @@ func FuzzIsScriptCorrect(f *testing.F) {
3537
})
3638
}
3739

40+
func FuzzParseMultiSigContract(f *testing.F) {
41+
pubs := make(keys.PublicKeys, 10)
42+
for i := range pubs {
43+
p, _ := keys.NewPrivateKey()
44+
pubs[i] = p.PublicKey()
45+
}
46+
47+
s, _ := smartcontract.CreateMultiSigRedeemScript(1, pubs[:1])
48+
f.Add(s)
49+
50+
s, _ = smartcontract.CreateMultiSigRedeemScript(3, pubs[:6])
51+
f.Add(s)
52+
53+
s, _ = smartcontract.CreateMultiSigRedeemScript(1, pubs)
54+
f.Add(s)
55+
56+
f.Fuzz(func(t *testing.T, script []byte) {
57+
var b [][]byte
58+
var ok bool
59+
var n int
60+
require.NotPanics(t, func() {
61+
n, b, ok = ParseMultiSigContract(script)
62+
})
63+
if ok {
64+
require.True(t, n <= len(b))
65+
}
66+
})
67+
}
68+
3869
func FuzzVMDontPanic(f *testing.F) {
3970
for _, s := range fuzzSeedValidScripts {
4071
f.Add(s)

0 commit comments

Comments
 (0)