factor out confirmation codes into utils, change their format

This commit is contained in:
Shivaram Lingamneni
2020-02-22 22:32:19 -05:00
parent 490b3722bd
commit 85a536977c
5 changed files with 63 additions and 15 deletions
+22
View File
@@ -0,0 +1,22 @@
// Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
// released under the MIT license
package utils
import (
"crypto/sha256"
"encoding/binary"
"time"
)
// Deterministically generates a confirmation code for some destructive activity;
// `name` is typically the name of the identity being destroyed (a channel being
// unregistered, or the server being crashed) and `createdAt` means a different
// value is required each time.
func ConfirmationCode(name string, createdAt time.Time) (code string) {
buf := make([]byte, len(name)+8)
binary.BigEndian.PutUint64(buf, uint64(createdAt.UnixNano()))
copy(buf[8:], name[:])
out := sha256.Sum256(buf)
return B32Encoder.EncodeToString(out[:3])
}
+36
View File
@@ -0,0 +1,36 @@
// Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
// released under the MIT license
package utils
import (
"testing"
"time"
)
func easyParse(timestamp string) time.Time {
result, err := time.Parse("2006-01-02 15:04:05Z", timestamp)
if err != nil {
panic(err)
}
return result
}
func TestConfirmation(t *testing.T) {
set := make(map[string]struct{})
set[ConfirmationCode("#darwin", easyParse("2006-01-01 00:00:00Z"))] = struct{}{}
set[ConfirmationCode("#darwin", easyParse("2006-01-02 00:00:00Z"))] = struct{}{}
set[ConfirmationCode("#xelpers", easyParse("2006-01-01 00:00:00Z"))] = struct{}{}
set[ConfirmationCode("#xelpers", easyParse("2006-01-02 00:00:00Z"))] = struct{}{}
if len(set) != 4 {
t.Error("confirmation codes are not unique")
}
for code := range set {
if len(code) <= 2 || len(code) >= 8 {
t.Errorf("bad code: %s", code)
}
}
}