Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 64 additions & 10 deletions ecc/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,70 @@ import (

func TestNafDecomposition(t *testing.T) {
t.Parallel()
// TODO write a real test...
exp := big.NewInt(13)
var result [400]int8
lExp := NafDecomposition(exp, result[:])
dec := result[:lExp]

res := [5]int8{1, 0, -1, 0, 1}
for i, v := range dec {
if v != res[i] {
t.Error("Error in NafDecomposition")

tests := []struct {
input string // large number in decimal form
expected []int8 // expected NAF representation
}{
{"13", []int8{1, 0, -1, 0, 1}}, // existing test case
{"0", []int8{}}, // edge case - zero
{"1", []int8{1}}, // edge case - one
{"7", []int8{1, 0, 0, -1}}, // 7 = 2³ - 2⁰ (8 - 1)
{"15", []int8{1, 0, 0, 0, 1}}, // 15 = 2⁴ - 2⁰
{"31", []int8{1, 0, 0, 0, 0, 1}}, // 31 = 2⁵ - 2⁰
}

for i, test := range tests {
input, success := new(big.Int).SetString(test.input, 10)
if !success {
t.Errorf("Failed to parse input number %s", test.input)
continue
}

var result [400]int8
length := NafDecomposition(input, result[:])
naf := result[:length]

// Length check
if len(naf) != len(test.expected) {
t.Errorf("Test %d: Incorrect length for input %s. Got %d, want %d",
i, test.input, len(naf), len(test.expected))
continue
}

// Value check
for j := range naf {
if naf[j] != test.expected[j] {
t.Errorf("Test %d: Mismatch at position %d for input %s. Got %d, want %d",
i, j, test.input, naf[j], test.expected[j])
}
}

// Checking NAF properties:
// 1. All digits must be -1, 0, or 1
// 2. No two non-zero digits should be adjacent
for j := range naf {
if naf[j] < -1 || naf[j] > 1 {
t.Errorf("Test %d: Invalid NAF digit at position %d: %d", i, j, naf[j])
}
if j > 0 && naf[j] != 0 && naf[j-1] != 0 {
t.Errorf("Test %d: Adjacent non-zero digits at positions %d and %d", i, j-1, j)
}
}

// Verify that the NAF representation equals the original number
reconstructed := new(big.Int)
power := new(big.Int).SetInt64(1)
for j := range naf {
if naf[j] != 0 {
term := new(big.Int).Mul(power, big.NewInt(int64(naf[j])))
reconstructed.Add(reconstructed, term)
}
power.Mul(power, big.NewInt(2))
}
if reconstructed.Cmp(input) != 0 {
t.Errorf("Test %d: NAF reconstruction failed for input %s. Got %s",
i, test.input, reconstructed.String())
}
}
}
Expand Down
Loading