28 Commits

Author SHA1 Message Date
web3-bot
701f9d5222 chore!: bump go.mod to Go 1.24 and run go fix (#65)
BREAKING CHANGE: Updating the Go version to 1.24
2025-08-21 08:31:50 +01:00
web3-bot
eabda15156 ci: uci/copy-templates (#64)
* chore: add or force update .github/workflows/stale.yml

* chore: add or force update .github/workflows/generated-pr.yml
2025-03-28 14:06:30 +01:00
web3-bot
766dbc86ae chore!: bump go.mod to Go 1.23 and run go fix (#63)
BREAKING CHANGE: Updating the Go version to 1.23
2025-02-16 21:01:37 +01:00
web3-bot
44b28418c8 chore: bump go.mod to Go 1.22 and run go fix (#61) 2024-08-26 11:26:41 +01:00
web3-bot
989fa114c3 ci: uci/copy-templates (#60)
* chore: add or force update .github/workflows/go-test.yml

* chore: add or force update .github/workflows/go-check.yml

* chore: add or force update .github/workflows/releaser.yml

* chore: add or force update .github/workflows/release-check.yml

* chore: add or force update .github/workflows/tagpush.yml

* chore: add or force update .github/workflows/go-test.yml

* chore: add or force update .github/workflows/go-check.yml

* chore: add or force update .github/workflows/releaser.yml

* chore: add or force update .github/workflows/release-check.yml

* chore: add or force update .github/workflows/tagpush.yml

* chore: add or force update .github/workflows/go-test.yml

* chore: add or force update .github/workflows/go-check.yml

* chore: add or force update .github/workflows/releaser.yml

* chore: add or force update .github/workflows/release-check.yml

* chore: add or force update .github/workflows/tagpush.yml
2024-03-22 07:17:09 +00:00
web3-bot
02ed95de81 ci: uci/update-go (#59)
* chore: bump go.mod to Go 1.21 and run go fix

* chore: run go mod tidy
2024-03-14 12:25:52 +01:00
web3-bot
a0303a6f45 chore: bump go.mod to Go 1.20 and run go fix (#58) 2023-08-14 15:36:12 +02:00
web3-bot
8c53981821 ci: uci/copy-templates (#57)
* chore: add or force update .github/workflows/go-test.yml

* chore: add or force update .github/workflows/go-check.yml

* chore: add or force update .github/workflows/releaser.yml

* chore: add or force update .github/workflows/release-check.yml

* chore: add or force update .github/workflows/tagpush.yml
2023-08-14 08:20:20 +02:00
web3-bot
8b61179671 chore: delete templates [skip ci] (#56) 2023-08-13 21:28:16 +02:00
Rod Vagg
58a41f7df1 chore: bump v0.2.0 2023-03-15 15:43:10 +11:00
Rod Vagg
a791fa9589 fix: math/rand -> crypto/rand 2023-03-15 15:43:10 +11:00
web3-bot
c36c36f88b update .github/workflows/release-check.yml 2023-03-15 15:43:10 +11:00
web3-bot
3bbbe822b0 update .github/workflows/go-check.yml 2023-03-15 15:43:10 +11:00
web3-bot
b85d20169d update .github/workflows/go-test.yml 2023-03-15 15:43:10 +11:00
web3-bot
8170d966f8 bump go.mod to Go 1.19 and run go fix 2023-03-15 15:43:10 +11:00
Jorropo
c442d70f87 fuzz: add Decoder fuzzing
This uses the spec tests as seeding value.
2023-01-08 22:58:38 +01:00
web3-bot
7160a7347e sync: update CI config files (#53) 2022-08-23 16:23:09 +00:00
Jorropo
c1bc15b22e chore: release version 0.1.1 2022-06-17 10:57:57 +10:00
Jorropo
801f90a945 fix: add new emoji codepoint for Base256Emoji 🐉
One of the values of base256emoji was not actually an emoji.

Here there be dragons instead !

See df5b7bc6ee (r75683795) for context.
2022-06-17 10:57:57 +10:00
Jorropo
6e0e420356 chore: release v0.1.0 2022-06-09 15:18:49 +10:00
Jorropo
df5b7bc6ee feat: add UTF-8 support and base256emoji
This include fixes for UTF-8 as well as base256emoji encoding (an encoding which actually use UTF-8).
2022-06-09 15:18:49 +10:00
Jorropo
0bd72a8c32 submodule: spec/
The spec submodule was on a 2 year old commit and the tests structure 
changed, this bring it to the latest master at this time.
2022-06-09 15:18:49 +10:00
web3-bot
714f5c0130 sync: update CI config files (#50) 2022-04-04 11:49:11 +00:00
web3-bot
f067816be3 sync: update CI config files (#48) 2021-12-10 14:34:10 +00:00
web3-bot
66b6f5f82a sync: update CI config files (#45) 2021-08-17 13:39:44 +00:00
web3-bot
c1e5d4e95b sync: update CI config files (#43) 2021-06-01 16:57:12 +00:00
Marten Seemann
f68598dd02 Merge pull request #41 from multiformats/fix-staticcheck
fix staticcheck
2021-05-05 20:16:15 +07:00
Marten Seemann
daffaef0db fix staticcheck 2021-05-05 20:13:06 +07:00
20 changed files with 324 additions and 193 deletions

14
.github/workflows/generated-pr.yml vendored Normal file
View File

@@ -0,0 +1,14 @@
name: Close Generated PRs
on:
schedule:
- cron: '0 0 * * *'
workflow_dispatch:
permissions:
issues: write
pull-requests: write
jobs:
stale:
uses: ipdxco/unified-github-workflows/.github/workflows/reusable-generated-pr.yml@v1

18
.github/workflows/go-check.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: Go Checks
on:
pull_request:
push:
branches: ["master"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event_name == 'push' && github.sha || github.ref }}
cancel-in-progress: true
jobs:
go-check:
uses: ipdxco/unified-github-workflows/.github/workflows/go-check.yml@v1.0

20
.github/workflows/go-test.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: Go Test
on:
pull_request:
push:
branches: ["master"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event_name == 'push' && github.sha || github.ref }}
cancel-in-progress: true
jobs:
go-test:
uses: ipdxco/unified-github-workflows/.github/workflows/go-test.yml@v1.0
secrets:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

19
.github/workflows/release-check.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: Release Checker
on:
pull_request_target:
paths: [ 'version.json' ]
types: [ opened, synchronize, reopened, labeled, unlabeled ]
workflow_dispatch:
permissions:
contents: write
pull-requests: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
release-check:
uses: ipdxco/unified-github-workflows/.github/workflows/release-check.yml@v1.0

17
.github/workflows/releaser.yml vendored Normal file
View File

@@ -0,0 +1,17 @@
name: Releaser
on:
push:
paths: [ 'version.json' ]
workflow_dispatch:
permissions:
contents: write
concurrency:
group: ${{ github.workflow }}-${{ github.sha }}
cancel-in-progress: true
jobs:
releaser:
uses: ipdxco/unified-github-workflows/.github/workflows/releaser.yml@v1.0

14
.github/workflows/stale.yml vendored Normal file
View File

@@ -0,0 +1,14 @@
name: Close Stale Issues
on:
schedule:
- cron: '0 0 * * *'
workflow_dispatch:
permissions:
issues: write
pull-requests: write
jobs:
stale:
uses: ipdxco/unified-github-workflows/.github/workflows/reusable-stale-issue.yml@v1

18
.github/workflows/tagpush.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: Tag Push Checker
on:
push:
tags:
- v*
permissions:
contents: read
issues: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
releaser:
uses: ipdxco/unified-github-workflows/.github/workflows/tagpush.yml@v1.0

View File

@@ -1,31 +0,0 @@
os:
- linux
language: go
go:
- 1.11.x
- 1.15.x
env:
global:
- GOTFLAGS="-race"
matrix:
- BUILD_DEPTYPE=gomod
# disable travis install
install:
- true
script:
- bash <(curl -s https://raw.githubusercontent.com/ipfs/ci-helpers/master/travis-ci/run-standard-tests.sh)
cache:
directories:
- $GOPATH/pkg/mod
- /home/travis/.cache/go-build
notifications:
email: false

95
base256emoji.go Normal file
View File

@@ -0,0 +1,95 @@
package multibase
import (
"strconv"
"strings"
"unicode/utf8"
)
var base256emojiTable = [256]rune{
// Curated list, this is just a list of things that *somwhat* are related to our comunity
'🚀', '🪐', '☄', '🛰', '🌌', // Space
'🌑', '🌒', '🌓', '🌔', '🌕', '🌖', '🌗', '🌘', // Moon
'🌍', '🌏', '🌎', // Our Home, for now (earth)
'🐉', // Dragon!!!
'☀', // Our Garden, for now (sol)
'💻', '🖥', '💾', '💿', // Computer
// The rest is completed from https://home.unicode.org/emoji/emoji-frequency/ at the time of creation (december 2021) (the data is from 2019), most used first until we reach 256.
// We exclude modifier based emojies (such as flags) as they are bigger than one single codepoint.
// Some other emojies were removed adhoc for various reasons.
'😂', '❤', '😍', '🤣', '😊', '🙏', '💕', '😭', '😘', '👍',
'😅', '👏', '😁', '🔥', '🥰', '💔', '💖', '💙', '😢', '🤔',
'😆', '🙄', '💪', '😉', '☺', '👌', '🤗', '💜', '😔', '😎',
'😇', '🌹', '🤦', '🎉', '💞', '✌', '✨', '🤷', '😱', '😌',
'🌸', '🙌', '😋', '💗', '💚', '😏', '💛', '🙂', '💓', '🤩',
'😄', '😀', '🖤', '😃', '💯', '🙈', '👇', '🎶', '😒', '🤭',
'❣', '😜', '💋', '👀', '😪', '😑', '💥', '🙋', '😞', '😩',
'😡', '🤪', '👊', '🥳', '😥', '🤤', '👉', '💃', '😳', '✋',
'😚', '😝', '😴', '🌟', '😬', '🙃', '🍀', '🌷', '😻', '😓',
'⭐', '✅', '🥺', '🌈', '😈', '🤘', '💦', '✔', '😣', '🏃',
'💐', '☹', '🎊', '💘', '😠', '☝', '😕', '🌺', '🎂', '🌻',
'😐', '🖕', '💝', '🙊', '😹', '🗣', '💫', '💀', '👑', '🎵',
'🤞', '😛', '🔴', '😤', '🌼', '😫', '⚽', '🤙', '☕', '🏆',
'🤫', '👈', '😮', '🙆', '🍻', '🍃', '🐶', '💁', '😲', '🌿',
'🧡', '🎁', '⚡', '🌞', '🎈', '❌', '✊', '👋', '😰', '🤨',
'😶', '🤝', '🚶', '💰', '🍓', '💢', '🤟', '🙁', '🚨', '💨',
'🤬', '✈', '🎀', '🍺', '🤓', '😙', '💟', '🌱', '😖', '👶',
'🥴', '▶', '➡', '❓', '💎', '💸', '⬇', '😨', '🌚', '🦋',
'😷', '🕺', '⚠', '🙅', '😟', '😵', '👎', '🤲', '🤠', '🤧',
'📌', '🔵', '💅', '🧐', '🐾', '🍒', '😗', '🤑', '🌊', '🤯',
'🐷', '☎', '💧', '😯', '💆', '👆', '🎤', '🙇', '🍑', '❄',
'🌴', '💣', '🐸', '💌', '📍', '🥀', '🤢', '👅', '💡', '💩',
'👐', '📸', '👻', '🤐', '🤮', '🎼', '🥵', '🚩', '🍎', '🍊',
'👼', '💍', '📣', '🥂',
}
var base256emojiReverseTable map[rune]byte
func init() {
base256emojiReverseTable = make(map[rune]byte, len(base256emojiTable))
for i, v := range base256emojiTable {
base256emojiReverseTable[v] = byte(i)
}
}
func base256emojiEncode(in []byte) string {
var l int
for _, v := range in {
l += utf8.RuneLen(base256emojiTable[v])
}
var out strings.Builder
out.Grow(l)
for _, v := range in {
out.WriteRune(base256emojiTable[v])
}
return out.String()
}
type base256emojiCorruptInputError struct {
index int
char rune
}
func (e base256emojiCorruptInputError) Error() string {
return "illegal base256emoji data at input byte " + strconv.FormatInt(int64(e.index), 10) + ", char: '" + string(e.char) + "'"
}
func (e base256emojiCorruptInputError) String() string {
return e.Error()
}
func base256emojiDecode(in string) ([]byte, error) {
out := make([]byte, utf8.RuneCountInString(in))
var stri int
for i := 0; len(in) > 0; i++ {
r, n := utf8.DecodeRuneInString(in)
in = in[n:]
var ok bool
out[i], ok = base256emojiReverseTable[r]
if !ok {
return nil, base256emojiCorruptInputError{stri, r}
}
stri += n
}
return out, nil
}

26
base256emoji_test.go Normal file
View File

@@ -0,0 +1,26 @@
package multibase
import "testing"
func TestBase256EmojiAlphabet(t *testing.T) {
var c uint
for _, v := range base256emojiTable {
if v != rune(0) {
c++
}
}
if c != 256 {
t.Errorf("Base256Emoji count is wrong, expected 256, got %d.", c)
}
}
func TestBase256EmojiUniq(t *testing.T) {
m := make(map[rune]struct{}, len(base256emojiTable))
for i, v := range base256emojiTable {
_, ok := m[v]
if ok {
t.Errorf("Base256Emoji duplicate %s at index %d.", string(v), i)
}
m[v] = struct{}{}
}
}

View File

@@ -2,6 +2,7 @@ package multibase
import ( import (
"fmt" "fmt"
"unicode/utf8"
) )
// Encoder is a multibase encoding that is verified to be supported and // Encoder is a multibase encoding that is verified to be supported and
@@ -14,7 +15,7 @@ type Encoder struct {
func NewEncoder(base Encoding) (Encoder, error) { func NewEncoder(base Encoding) (Encoder, error) {
_, ok := EncodingToStr[base] _, ok := EncodingToStr[base]
if !ok { if !ok {
return Encoder{-1}, fmt.Errorf("Unsupported multibase encoding: %d", base) return Encoder{-1}, fmt.Errorf("unsupported multibase encoding: %d", base)
} }
return Encoder{base}, nil return Encoder{base}, nil
} }
@@ -33,17 +34,18 @@ func MustNewEncoder(base Encoding) Encoder {
// either be the multibase name or single character multibase prefix // either be the multibase name or single character multibase prefix
func EncoderByName(str string) (Encoder, error) { func EncoderByName(str string) (Encoder, error) {
var base Encoding var base Encoding
ok := true var ok bool
if len(str) == 0 { if len(str) == 0 {
return Encoder{-1}, fmt.Errorf("Empty multibase encoding") return Encoder{-1}, fmt.Errorf("empty multibase encoding")
} else if len(str) == 1 { } else if utf8.RuneCountInString(str) == 1 {
base = Encoding(str[0]) r, _ := utf8.DecodeRuneInString(str)
base = Encoding(r)
_, ok = EncodingToStr[base] _, ok = EncodingToStr[base]
} else { } else {
base, ok = Encodings[str] base, ok = Encodings[str]
} }
if !ok { if !ok {
return Encoder{-1}, fmt.Errorf("Unsupported multibase encoding: %s", str) return Encoder{-1}, fmt.Errorf("unsupported multibase encoding: %s", str)
} }
return Encoder{base}, nil return Encoder{base}, nil
} }

View File

@@ -2,6 +2,7 @@ package multibase
import ( import (
"testing" "testing"
"unicode/utf8"
) )
func TestInvalidCode(t *testing.T) { func TestInvalidCode(t *testing.T) {
@@ -43,9 +44,10 @@ func TestEncoder(t *testing.T) {
} }
// Test that an encoder can be created from the single letter // Test that an encoder can be created from the single letter
// prefix // prefix
_, err = EncoderByName(str[0:1]) r, _ := utf8.DecodeRuneInString(str)
_, err = EncoderByName(string(r))
if err != nil { if err != nil {
t.Fatalf("EncoderByName(%s) failed: %v", str[0:1], err) t.Fatalf("EncoderByName(%s) failed: %v", string(r), err)
} }
} }
} }

3
go.mod
View File

@@ -1,10 +1,9 @@
module github.com/multiformats/go-multibase module github.com/multiformats/go-multibase
go 1.11 go 1.24
require ( require (
github.com/mr-tron/base58 v1.1.0 github.com/mr-tron/base58 v1.1.0
github.com/multiformats/go-base32 v0.0.3 github.com/multiformats/go-base32 v0.0.3
github.com/multiformats/go-base36 v0.1.0 github.com/multiformats/go-base36 v0.1.0
github.com/urfave/cli/v2 v2.3.0
) )

13
go.sum
View File

@@ -1,19 +1,6 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/mr-tron/base58 v1.1.0 h1:Y51FGVJ91WBqCEabAi5OPUz38eAx8DakuAm5svLcsfQ= github.com/mr-tron/base58 v1.1.0 h1:Y51FGVJ91WBqCEabAi5OPUz38eAx8DakuAm5svLcsfQ=
github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8= github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8=
github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI= github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI=
github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA= github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA=
github.com/multiformats/go-base36 v0.1.0 h1:JR6TyF7JjGd3m6FbLU2cOxhC0Li8z8dLNGQ89tUg4F4= github.com/multiformats/go-base36 v0.1.0 h1:JR6TyF7JjGd3m6FbLU2cOxhC0Li8z8dLNGQ89tUg4F4=
github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM= github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M=
github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@@ -4,6 +4,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"unicode/utf8"
b58 "github.com/mr-tron/base58/base58" b58 "github.com/mr-tron/base58/base58"
b32 "github.com/multiformats/go-base32" b32 "github.com/multiformats/go-base32"
@@ -38,31 +39,33 @@ const (
Base64url = 'u' Base64url = 'u'
Base64pad = 'M' Base64pad = 'M'
Base64urlPad = 'U' Base64urlPad = 'U'
Base256Emoji = '🚀'
) )
// EncodingToStr is a map of the supported encoding, unsupported encoding // EncodingToStr is a map of the supported encoding, unsupported encoding
// specified in standard are left out // specified in standard are left out
var EncodingToStr = map[Encoding]string{ var EncodingToStr = map[Encoding]string{
0x00: "identity", 0x00: "identity",
'0': "base2", '0': "base2",
'f': "base16", 'f': "base16",
'F': "base16upper", 'F': "base16upper",
'b': "base32", 'b': "base32",
'B': "base32upper", 'B': "base32upper",
'c': "base32pad", 'c': "base32pad",
'C': "base32padupper", 'C': "base32padupper",
'v': "base32hex", 'v': "base32hex",
'V': "base32hexupper", 'V': "base32hexupper",
't': "base32hexpad", 't': "base32hexpad",
'T': "base32hexpadupper", 'T': "base32hexpadupper",
'k': "base36", 'k': "base36",
'K': "base36upper", 'K': "base36upper",
'z': "base58btc", 'z': "base58btc",
'Z': "base58flickr", 'Z': "base58flickr",
'm': "base64", 'm': "base64",
'u': "base64url", 'u': "base64url",
'M': "base64pad", 'M': "base64pad",
'U': "base64urlpad", 'U': "base64urlpad",
Base256Emoji: "base256emoji",
} }
var Encodings = map[string]Encoding{} var Encodings = map[string]Encoding{}
@@ -123,6 +126,8 @@ func Encode(base Encoding, data []byte) (string, error) {
return string(Base64url) + base64.RawURLEncoding.EncodeToString(data), nil return string(Base64url) + base64.RawURLEncoding.EncodeToString(data), nil
case Base64: case Base64:
return string(Base64) + base64.RawStdEncoding.EncodeToString(data), nil return string(Base64) + base64.RawStdEncoding.EncodeToString(data), nil
case Base256Emoji:
return string(Base256Emoji) + base256emojiEncode(data), nil
default: default:
return "", ErrUnsupportedEncoding return "", ErrUnsupportedEncoding
} }
@@ -135,7 +140,8 @@ func Decode(data string) (Encoding, []byte, error) {
return 0, nil, fmt.Errorf("cannot decode multibase for zero length string") return 0, nil, fmt.Errorf("cannot decode multibase for zero length string")
} }
enc := Encoding(data[0]) r, _ := utf8.DecodeRuneInString(data)
enc := Encoding(r)
switch enc { switch enc {
case Identity: case Identity:
@@ -179,6 +185,9 @@ func Decode(data string) (Encoding, []byte, error) {
case Base64url: case Base64url:
bytes, err := base64.RawURLEncoding.DecodeString(data[1:]) bytes, err := base64.RawURLEncoding.DecodeString(data[1:])
return Base64url, bytes, err return Base64url, bytes, err
case Base256Emoji:
bytes, err := base256emojiDecode(data[4:])
return Base256Emoji, bytes, err
default: default:
return -1, nil, ErrUnsupportedEncoding return -1, nil, ErrUnsupportedEncoding
} }

View File

@@ -1,115 +0,0 @@
package main
import (
"fmt"
"github.com/multiformats/go-multibase"
"io/ioutil"
"os"
"github.com/urfave/cli/v2"
)
func main() {
app := &cli.App{
Name: "multibase",
Usage: "base encoding and transcoding tool",
Commands: []*cli.Command{
{
Name: "encode",
ArgsUsage: "<base>",
Usage: "encode data in multibase",
Flags: []cli.Flag{
&cli.PathFlag{
Name: "input",
Aliases: []string{"i"},
Usage: "the file that should be encoded",
},
},
Action: func(context *cli.Context) error {
if !context.Args().Present() || context.NArg() > 2 {
return cli.ShowCommandHelp(context, "")
}
p := context.Path("input")
if (p == "" && context.NArg() != 2) || (p != "" && context.NArg() != 1) {
return cli.ShowCommandHelp(context, "")
}
base, err := multibase.EncoderByName(context.Args().First())
if err != nil {
return err
}
if p != "" {
fileData, err := ioutil.ReadFile(p)
if err != nil {
return err
}
fmt.Println(base.Encode(fileData))
return nil
}
fmt.Println(base.Encode([]byte(context.Args().Get(1))))
return nil
},
},
{
Name: "decode",
ArgsUsage: "<data>",
Usage: "encode data in multibase",
Flags: []cli.Flag{
&cli.PathFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "output decoded data to a file",
},
},
Action: func(context *cli.Context) error {
if context.NArg() != 1 {
return cli.ShowCommandHelp(context, "")
}
_, data, err := multibase.Decode(context.Args().First())
if err != nil {
return err
}
p := context.Path("output")
if p == "" {
fmt.Printf(string(data))
return nil
}
return ioutil.WriteFile(p, data, os.ModePerm)
},
},
{
Name: "transcode",
ArgsUsage: "<new-base> <data>",
Usage: "transcode multibase data",
Action: func(context *cli.Context) error {
if context.NArg() != 2 {
return cli.ShowCommandHelp(context, "")
}
newbase, err := multibase.EncoderByName(context.Args().Get(0))
if err != nil {
return err
}
_, data, err := multibase.Decode(context.Args().Get(1))
if err != nil {
return err
}
fmt.Println(newbase.Encode(data))
return nil
},
},
},
}
err := app.Run(os.Args)
if err != nil {
panic(err)
}
}

View File

@@ -2,7 +2,7 @@ package multibase
import ( import (
"bytes" "bytes"
"math/rand" "crypto/rand"
"sort" "sort"
"testing" "testing"
) )
@@ -44,6 +44,7 @@ var encodedSamples = map[Encoding]string{
Base64url: "uRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchISE", Base64url: "uRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchISE",
Base64pad: "MRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchISE=", Base64pad: "MRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchISE=",
Base64urlPad: "URGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchISE=", Base64urlPad: "URGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchISE=",
Base256Emoji: "🚀💛✋💃✋😻😈🥺🤤🍀🌟💐✋😅✋💦✋🥺🏃😈😴🌟😻😝👏👏👏",
} }
func testEncode(t *testing.T, encoding Encoding, bytes []byte, expected string) { func testEncode(t *testing.T, encoding Encoding, bytes []byte, expected string) {

2
spec

Submodule spec updated: 3806057e6f...4c8344e378

View File

@@ -66,7 +66,7 @@ func TestSpec(t *testing.T) {
} }
} }
func TestSpecVectors(t *testing.T) { func TestSpecVectors(t *testing.T) {
files, err := filepath.Glob("spec/tests/test[0-9]*.csv") files, err := filepath.Glob("spec/tests/*.csv")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -145,3 +145,36 @@ func TestSpecVectors(t *testing.T) {
}) })
} }
} }
func FuzzDecode(f *testing.F) {
files, err := filepath.Glob("spec/tests/*.csv")
if err != nil {
f.Fatal(err)
}
for _, fname := range files {
func() {
file, err := os.Open(fname)
if err != nil {
f.Fatal(err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.LazyQuotes = false
reader.FieldsPerRecord = 2
reader.TrimLeadingSpace = true
values, err := reader.ReadAll()
if err != nil {
f.Fatal(err)
}
for _, tc := range values[1:] {
f.Add(tc[1])
}
}()
}
f.Fuzz(func(_ *testing.T, data string) {
Decode(data)
})
}

3
version.json Normal file
View File

@@ -0,0 +1,3 @@
{
"version": "v0.2.0"
}