summary refs log tree commit diff
path: root/vendor/go.mau.fi/util/base58/base58check.go
diff options
context:
space:
mode:
authorEmile <git@emile.space>2024-10-25 15:55:50 +0200
committerEmile <git@emile.space>2024-10-25 15:55:50 +0200
commitc90f36e3dd179d2de96f4f5fe38d8dc9a9de6dfe (patch)
tree89e9afb41c5bf76f48cfb09305a2d3db8d302b06 /vendor/go.mau.fi/util/base58/base58check.go
parent98bbb0f559a8883bc47bae80607dbe326a448e61 (diff)
vendor HEAD main
Diffstat (limited to 'vendor/go.mau.fi/util/base58/base58check.go')
-rw-r--r--vendor/go.mau.fi/util/base58/base58check.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/vendor/go.mau.fi/util/base58/base58check.go b/vendor/go.mau.fi/util/base58/base58check.go
new file mode 100644
index 0000000..402c323
--- /dev/null
+++ b/vendor/go.mau.fi/util/base58/base58check.go
@@ -0,0 +1,52 @@
+// Copyright (c) 2013-2014 The btcsuite developers
+// Use of this source code is governed by an ISC
+// license that can be found in the LICENSE file.
+
+package base58
+
+import (
+	"crypto/sha256"
+	"errors"
+)
+
+// ErrChecksum indicates that the checksum of a check-encoded string does not verify against
+// the checksum.
+var ErrChecksum = errors.New("checksum error")
+
+// ErrInvalidFormat indicates that the check-encoded string has an invalid format.
+var ErrInvalidFormat = errors.New("invalid format: version and/or checksum bytes missing")
+
+// checksum: first four bytes of sha256^2
+func checksum(input []byte) (cksum [4]byte) {
+	h := sha256.Sum256(input)
+	h2 := sha256.Sum256(h[:])
+	copy(cksum[:], h2[:4])
+	return
+}
+
+// CheckEncode prepends a version byte and appends a four byte checksum.
+func CheckEncode(input []byte, version byte) string {
+	b := make([]byte, 0, 1+len(input)+4)
+	b = append(b, version)
+	b = append(b, input...)
+	cksum := checksum(b)
+	b = append(b, cksum[:]...)
+	return Encode(b)
+}
+
+// CheckDecode decodes a string that was encoded with CheckEncode and verifies the checksum.
+func CheckDecode(input string) (result []byte, version byte, err error) {
+	decoded := Decode(input)
+	if len(decoded) < 5 {
+		return nil, 0, ErrInvalidFormat
+	}
+	version = decoded[0]
+	var cksum [4]byte
+	copy(cksum[:], decoded[len(decoded)-4:])
+	if checksum(decoded[:len(decoded)-4]) != cksum {
+		return nil, 0, ErrChecksum
+	}
+	payload := decoded[1 : len(decoded)-4]
+	result = append(result, payload...)
+	return
+}