basic implementation
This commit is contained in:
40
multibase.go
Normal file
40
multibase.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package multibase
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
b58 "github.com/jbenet/go-base58"
|
||||
)
|
||||
|
||||
const (
|
||||
Base1 = '1'
|
||||
Base2 = '0'
|
||||
Base8 = '7'
|
||||
Base10 = '9'
|
||||
Base16 = 'f'
|
||||
Base58Flickr = 'Z'
|
||||
Base58BTC = 'z'
|
||||
)
|
||||
|
||||
var ErrUnsupportedEncoding = fmt.Errorf("selected encoding not supported")
|
||||
|
||||
func Encode(base int, data []byte) (string, error) {
|
||||
switch base {
|
||||
case Base58BTC:
|
||||
return string(Base58BTC) + b58.EncodeAlphabet(data, b58.BTCAlphabet), nil
|
||||
case Base16:
|
||||
return string(Base16) + hex.EncodeToString(data), nil
|
||||
default:
|
||||
return "", ErrUnsupportedEncoding
|
||||
}
|
||||
}
|
||||
|
||||
func Decode(data string) (int, []byte, error) {
|
||||
switch data[0] {
|
||||
case Base58BTC:
|
||||
return Base58BTC, b58.DecodeAlphabet(data[1:], b58.BTCAlphabet), nil
|
||||
default:
|
||||
return -1, nil, ErrUnsupportedEncoding
|
||||
}
|
||||
}
|
||||
30
multibase_test.go
Normal file
30
multibase_test.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package multibase
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math/rand"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBase58RoundTrip(t *testing.T) {
|
||||
buf := make([]byte, 16)
|
||||
rand.Read(buf)
|
||||
|
||||
enc, err := Encode(Base58BTC, buf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
e, out, err := Decode(enc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if e != Base58BTC {
|
||||
t.Fatal("got wrong encoding out")
|
||||
}
|
||||
|
||||
if !bytes.Equal(buf, out) {
|
||||
t.Fatal("input wasnt the same as output", buf, out)
|
||||
}
|
||||
}
|
||||
14
package.json
Normal file
14
package.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": "whyrusleeping",
|
||||
"bugs": {
|
||||
"url": "https://github.com/multiformats/go-multibase"
|
||||
},
|
||||
"gx": {
|
||||
"dvcsimport": "github.com/multiformats/go-multibase"
|
||||
},
|
||||
"gxVersion": "0.8.0",
|
||||
"language": "go",
|
||||
"license": "",
|
||||
"name": "go-multibase",
|
||||
"version": "0.0.0"
|
||||
}
|
||||
Reference in New Issue
Block a user