mirror of
https://github.com/jeremyd/ergo.git
synced 2026-07-27 01:18:10 -07:00
factor out confirmation codes into utils, change their format
This commit is contained in:
@@ -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])
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user