| 1 | package console |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/binary" |
| 7 | "errors" |
| 8 | "math/bits" |
| 9 | "testing" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | // refLeadingZeros is written out independently of keymailpow.go so the |
| 14 | // test does not check the code against itself. |
| 15 | func refLeadingZeros(h []byte) int { |
| 16 | n := 0 |
| 17 | for _, b := range h { |
| 18 | if b == 0 { |
| 19 | n += 8 |
| 20 | continue |
| 21 | } |
| 22 | return n + bits.LeadingZeros8(b) |
| 23 | } |
| 24 | return n |
| 25 | } |
| 26 | |
| 27 | func refHash(nonce, signPub []byte, counter uint64) []byte { |
| 28 | h := sha256.New() |
| 29 | h.Write(nonce) |
| 30 | h.Write(signPub) |
| 31 | var c [8]byte |
| 32 | binary.BigEndian.PutUint64(c[:], counter) |
| 33 | h.Write(c[:]) |
| 34 | return h.Sum(nil) |
| 35 | } |
| 36 | |
| 37 | func TestPowMineFindsAVerifiableCounter(t *testing.T) { |
| 38 | nonce := sha256.Sum256([]byte("challenge-token")) |
| 39 | signPub := []byte("sign-pub-bytes") |
| 40 | ctr, err := powMine(context.Background(), nonce[:], signPub, 12) |
| 41 | if err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | if got := refLeadingZeros(refHash(nonce[:], signPub, ctr)); got < 12 { |
| 45 | t.Fatalf("counter %d gives %d leading zero bits, want >= 12", ctr, got) |
| 46 | } |
| 47 | if !powVerify(nonce[:], signPub, ctr, 12) { |
| 48 | t.Fatal("powVerify rejects the counter powMine found") |
| 49 | } |
| 50 | if powVerify(nonce[:], []byte("another key"), ctr, 12) && refLeadingZeros(refHash(nonce[:], []byte("another key"), ctr)) < 12 { |
| 51 | t.Fatal("powVerify accepted a solution for a different key") |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | func TestPowZeroBitsIsFree(t *testing.T) { |
| 56 | if !powVerify(nil, nil, 0, 0) { |
| 57 | t.Fatal("0 bits must verify") |
| 58 | } |
| 59 | ctr, err := powMine(context.Background(), nil, nil, 0) |
| 60 | if err != nil || ctr != 0 { |
| 61 | t.Fatalf("powMine(0 bits) = %d, %v; want 0, nil", ctr, err) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | func TestPowMineHonoursCancellation(t *testing.T) { |
| 66 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) |
| 67 | defer cancel() |
| 68 | // 64 bits will never be found. |
| 69 | _, err := powMine(ctx, []byte("n"), []byte("k"), 64) |
| 70 | if !errors.Is(err, context.DeadlineExceeded) { |
| 71 | t.Fatalf("powMine under a 20ms deadline = %v, want DeadlineExceeded", err) |
| 72 | } |
| 73 | } |
| 74 | |