52 Commits

Author SHA1 Message Date
470c018828 update(AUTHORS)
Some checks failed
Deploy documentation / deploy (push) Has been cancelled
2024-09-30 18:38:23 +03:00
435c338c8f Merge pull request #4 from vSEK1RO/1.1.0
1.1.0
2024-09-30 18:35:51 +03:00
d31b8cb376 feat(README.md): usage of cli tool 2024-09-30 18:24:55 +03:00
6ffeb39801 fix(basen): basen::Exception 2024-09-30 18:15:45 +03:00
8169651729 fix(base58): basen::Exception 2024-09-30 17:47:08 +03:00
edcaebcf53 fix(hex): basen::Exception 2024-09-30 17:41:43 +03:00
64c2e51104 fix(base64): basen::Exception 2024-09-30 17:36:29 +03:00
227579d1e2 fix(baseN): basen::Exception 2024-09-30 17:23:23 +03:00
4eaf5b53c0 feat(Exception) 2024-09-30 16:17:24 +03:00
7e78bca810 fix(types): int8_t -> uint8_t; -1 -> 255 2024-09-30 13:10:47 +03:00
1d6b086bfa fix(types): uint64_t -> size_t 2024-09-30 12:35:59 +03:00
be4f2ae036 update(LICENSE): GPL-3.0 -> LGPL-3.0 2024-09-30 12:08:36 +03:00
bffab94715 fix(baseN): decode: condition div != 0 at last iteration 2024-09-29 22:06:07 +03:00
aefef92370 feat(basen): without encoding exceptions handling 2024-09-29 15:26:04 +03:00
d8671350a4 fix(base58): decodeCheck: exception if buff.size() < 4 2024-09-29 13:34:09 +03:00
fb15184848 feat(baseN): digitsMap 2024-09-29 13:33:38 +03:00
3c93056416 fix(Makefile): -lgcov, TOOLS = basen 2024-09-28 22:06:04 +03:00
71ff3d4260 fix(base64): encode: incorrect padding if size % 3 == 2 2024-09-28 13:23:54 +03:00
bce26d3a4b submodule(update)
Some checks failed
Deploy documentation / deploy (push) Has been cancelled
2024-09-26 21:02:55 +03:00
44120b7ebb fix(docs.yml): on push main; update(Doxyfile): version 2024-09-26 20:55:30 +03:00
87a0cce29d update(AUTHORS) 2024-09-26 20:24:55 +03:00
9f939fea24 Merge pull request #2 from vSEK1RO/v1.0.2
V1.0.2
2024-09-26 20:23:15 +03:00
8da5ce49ef fix(base64): coverage 2024-09-26 20:05:38 +03:00
b0e645679d fix(hex): coverage 2024-09-26 17:17:01 +03:00
6d689cb9b3 fix(README.md): coverage 2024-09-26 12:26:07 +03:00
119bca6c87 fix(docs.yml): on realease published 2024-09-26 12:06:51 +03:00
5396abe202 feat(cover): gcov, gcovr 2024-09-26 12:00:23 +03:00
5f2cffdd82 submodule(distrib/arch): v1.0.1 2024-09-23 21:20:06 +03:00
93baa83f87 update(AUTHORS)
Some checks failed
Deploy documentation / deploy (push) Has been cancelled
2024-09-23 19:41:23 +03:00
b6780fe572 fix(docs.yml): download doxygen-1.12.0 binaries 2024-09-23 19:38:33 +03:00
bb98575fb9 fix(docs.yml): submodules: 'true' 2024-09-22 22:20:24 +03:00
98fa49bd06 Merge pull request #1 from vSEK1RO/v1.0.1
v1.0.1
2024-09-22 22:07:58 +03:00
e28d103da0 feat(docs): base58.hpp 2024-09-22 22:00:13 +03:00
5b76028d8a feat(docs): hex.hpp 2024-09-22 21:50:49 +03:00
9d9b7adcc3 feat(docs): base64.hpp 2024-09-22 21:49:12 +03:00
c511dd2fa8 feat(docs): github link, ghpages link 2024-09-22 21:28:27 +03:00
f6e17b4f7b fix(sha256): define DIGEST_LENGTH removed 2024-09-22 21:02:23 +03:00
b61d8396f5 feat(docs): baseN.hpp 2024-09-22 21:00:54 +03:00
53279581aa feat(.github): docs.yml 2024-09-22 20:24:45 +03:00
f4b5dc0ce0 fix(doxygen-awesome): moved to deps dir 2024-09-22 20:03:22 +03:00
a5374daa6f feat(Doxyfile, doxygen-awesome) 2024-09-22 19:51:15 +03:00
baf52bb404 fix(submodule): distrib/arch added to .gitmodules 2024-09-22 17:11:15 +03:00
f47f367045 fix(README.md): styles 2024-09-21 22:41:34 +03:00
fd660f3b56 feat(README.md): contents, installation, contribution 2024-09-21 22:30:36 +03:00
78276e8c88 submodule(distrib): aur 2024-09-21 16:14:13 +03:00
7b0b06a1fe feat(LICENSE, AUTHORS): MIT -> GPL-3.0, authors.sh 2024-09-21 15:34:12 +03:00
f8417be18c fix(baseN): decode: empty string case 2024-09-20 20:08:51 +03:00
4b7f01dcf6 fix(rename, submodule): libbase -> libbasen, aur.archlinux.org submodule removed 2024-09-20 19:03:26 +03:00
4e166d24cf submodule(arch): PKGBUILD 2024-09-19 10:09:10 +03:00
64912d9b54 fix(Makefile): mkdir -p 2024-09-19 09:36:56 +03:00
0086092bd9 fix(baseN): encode, decode now return uint8_t zero offset 2024-09-19 08:41:59 +03:00
f49c0463d4 fix(baseN): sizeEnc/Dec: zeros counting 2024-09-19 07:54:46 +03:00
37 changed files with 4172 additions and 348 deletions

41
.github/workflows/docs.yml vendored Normal file
View File

@ -0,0 +1,41 @@
name: Deploy documentation
on:
push:
branches: ["main"]
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: 'true'
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Install Doxygen
run: |
wget https://github.com/doxygen/doxygen/releases/download/Release_1_12_0/doxygen-1.12.0.linux.bin.tar.gz
tar -xf doxygen-1.12.0.linux.bin.tar.gz
- name: Generate docs
run: ./doxygen-1.12.0/bin/doxygen
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: 'doc/html'
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

2
.gitignore vendored
View File

@ -42,6 +42,8 @@ BUILD.bazel
bin bin
obj obj
lib lib
doc
cov
# IDE # IDE
.vscode .vscode

6
.gitmodules vendored Normal file
View File

@ -0,0 +1,6 @@
[submodule "distrib/arch"]
path = distrib/arch
url = https://aur.archlinux.org/libbasen.git
[submodule "deps/doxygen-awesome-css"]
path = deps/doxygen-awesome-css
url = https://github.com/jothepro/doxygen-awesome-css.git

5
AUTHORS Normal file
View File

@ -0,0 +1,5 @@
libbasen project authors:
commits | username
90 | vSEK1RO

2927
Doxyfile Normal file

File diff suppressed because it is too large Load Diff

166
LICENSE
View File

@ -1,9 +1,165 @@
MIT License GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2024 sek1ro Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@ -5,17 +5,18 @@ DEBUG ?= false
USRDIR ?= /usr USRDIR ?= /usr
.PHONY: build i install uni uninstall\ .PHONY: build i install uni uninstall\
tools library tests clean tools library tests docs cov clean
LIB = base LIB = basen
OBJS =\ OBJS =\
hex\ hex\
baseN\ baseN\
base58\ base58\
base64\ base64\
hash/sha256\ hash/sha256\
Exception
TOOLS =\ TOOLS = ${LIB}
TESTS =\ TESTS =\
test-hex\ test-hex\
@ -23,6 +24,7 @@ TESTS =\
test-base58\ test-base58\
test-base64\ test-base64\
hash/test-sha256\ hash/test-sha256\
test-Exception
ifeq (${origin CC}, default) ifeq (${origin CC}, default)
CC = g++ CC = g++
@ -77,8 +79,23 @@ uninstall:
rm -f ${patsubst %, ${USRLIB}/lib${LIB}${-g}%, .so .a} rm -f ${patsubst %, ${USRLIB}/lib${LIB}${-g}%, .so .a}
rm -f ${patsubst %, ${USRBIN}/%${-g}, ${TOOLS}} rm -f ${patsubst %, ${USRBIN}/%${-g}, ${TOOLS}}
docs:
doxygen Doxyfile
cover: ${DIRS} ${patsubst %, ${BINDIR}/%${-g}-cov, ${TESTS}}
rm -f **/*.gcda
${patsubst %, ./${BINDIR}/%${-g}-cov;, ${TESTS}}
mkdir -p cov
gcovr --html-nested cov/index.html --txt --exclude-throw-branches
${OBJDIR}/%${-g}-cov.o: ${SRCDIR}/%.cpp ${INCDIR}/${LIB}/%.hpp
${CC} -o $@ -c $< -I${INCDIR} ${-l} ${CFLAGS} --coverage
${BINDIR}/%${-g}-cov: ${TESTDIR}/%.cpp ${patsubst %, ${OBJDIR}/%${-g}-cov.o, ${OBJS}}
${CC} -o $@ $^ -I${INCDIR} ${-l} -lgtest -lgcov ${CFLAGS}
clean: clean:
rm -rf ${OBJDIR}/* ${LIBDIR}/* ${BINDIR}/* rm -rf ${DIRS} doc cov
ifneq (${OBJS},) ifneq (${OBJS},)
@ -122,4 +139,4 @@ ${BINDIR}/%${-g}: ${TESTDIR}/%.cpp ${patsubst %, ${OBJDIR}/%${-g}.o, ${OBJS}}
endif endif
${DIRS}: ${DIRS}:
mkdir $@ mkdir -p $@

View File

@ -1,3 +1,74 @@
# libbase # libbasen
encoding/decoding from arbitrary base c++ encoding/decoding from arbitrary base
<a href="https://repology.org/project/libbasen/versions">
<img src="https://repology.org/badge/tiny-repos/libbasen.svg" alt="Packaging status">
</a>
<a href="https://repology.org/project/libbasen/versions">
<img src="https://repology.org/badge/latest-versions/libbasen.svg" alt="latest packaged version(s)">
</a>
## Contents
- [Installation](#installation)
- [Documentation](#documentation)
- [Usage](#usage)
- [Contributing](#contributing)
## Installation
Automatically from specified repositories:
[![Packaging status](https://repology.org/badge/vertical-allrepos/libbasen.svg)](https://repology.org/project/libbasen/versions)
Manually using make:
```
make -j $(nproc)
sudo make i USRDIR=(Your installation dir)
```
Uninstall:
```
sudo make uni USRDIR=(Your installation dir)
```
## Documentation
Available [here](https://vsek1ro.github.io/libbasen)
## Usage
libbasen package provides `basen` cli tool. Below are examples of use:
```
echo "hello world" | basen -t hex > encoded.data
```
```
basen -t hex -d < encoded.data > decoded.data
```
```
echo "arbitrary alphabet" | basen -a "0123ABCD"
```
## Contributing
Main branch is under protection rules, so you should create pull request. After merging will be runned [authors.sh](https://github.com/vSEK1RO/libbasen/blob/main/authors.sh) for adding all contributors usernames and their number of commits to [AUTHORS](https://github.com/vSEK1RO/libbasen/blob/main/AUTHORS) file.
Now we would like to implement the following features:
- Base32
- BCH
- Bech32
For build with with debug flags:
```
make -j $(nproc) DEBUG=
```
For build tests (needed gtest package as dependency):
```
make tests -j $(nproc) DEBUG=
```
For generating coverage:
```
make cover -j $(nproc) DEBUG=
```
[⬆️ Contents](#contents)

20
authors.sh Executable file
View File

@ -0,0 +1,20 @@
#!/bin/bash
RESPONSE=$(curl -L \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/vSEK1RO/libbasen/contributors)
LOGIN=$(echo "$RESPONSE" | sed -n /login/p | sed 's/ \"login\": \"//' | sed 's/\",//')
CONTRIBUTIONS=$(echo "$RESPONSE" | sed -n /contributions/p | sed 's/ \"contributions\": //' | sed 's/,//')
IFS=$'\n' read -r -d '' -a arr1 <<< "$CONTRIBUTIONS"
IFS=$'\n' read -r -d '' -a arr2 <<< "$LOGIN"
AUTHORS=$'libbasen project authors:\n\n'
AUTHORS+=$(printf "%7s | %s" "commits" "username")$'\n'
for ((i = 0; i < ${#arr1[@]}; i++)); do
AUTHORS+=$(printf "%7s | %s" "${arr1[$i]}" "${arr2[$i]}")$'\n'
done
echo "$AUTHORS" > AUTHORS

1
deps/doxygen-awesome-css vendored Submodule

1
distrib/arch Submodule

Submodule distrib/arch added at 3453e4c5cd

87
header.html Normal file
View File

@ -0,0 +1,87 @@
<!-- HTML header for doxygen 1.12.0-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="$langISO">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen $doxygenversion"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!--BEGIN PROJECT_NAME--><title>$projectname: $title</title><!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME--><title>$title</title><!--END !PROJECT_NAME-->
<!--BEGIN PROJECT_ICON-->
<link rel="icon" href="$relpath^$projecticon" type="image/x-icon" />
<!--END PROJECT_ICON-->
<link href="$relpath^tabs.css" rel="stylesheet" type="text/css"/>
<!--BEGIN DISABLE_INDEX-->
<!--BEGIN FULL_SIDEBAR-->
<script type="text/javascript">var page_layout=1;</script>
<!--END FULL_SIDEBAR-->
<!--END DISABLE_INDEX-->
<script type="text/javascript" src="$relpath^jquery.js"></script>
<script type="text/javascript" src="$relpath^dynsections.js"></script>
<!--BEGIN COPY_CLIPBOARD-->
<script type="text/javascript" src="$relpath^clipboard.js"></script>
<!--END COPY_CLIPBOARD-->
$treeview
$search
$mathjax
$darkmode
<link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" />
$extrastylesheet
<script type="text/javascript" src="$relpath^doxygen-awesome-darkmode-toggle.js"></script>
<script type="text/javascript" src="$relpath^doxygen-awesome-fragment-copy-button.js"></script>
<script type="text/javascript">
DoxygenAwesomeDarkModeToggle.init()
DoxygenAwesomeFragmentCopyButton.init()
</script>
</head>
<body>
<!--BEGIN DISABLE_INDEX-->
<!--BEGIN FULL_SIDEBAR-->
<div id="side-nav" class="ui-resizable side-nav-resizable"><!-- do not remove this div, it is closed by doxygen! -->
<!--END FULL_SIDEBAR-->
<!--END DISABLE_INDEX-->
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!--BEGIN TITLEAREA-->
<a href="https://github.com/vSEK1RO/libbasen" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill: #4779ac; color:#151513; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr id="projectrow">
<!--BEGIN PROJECT_LOGO-->
<td id="projectlogo"><img alt="Logo" src="$relpath^$projectlogo"$logosize/></td>
<!--END PROJECT_LOGO-->
<!--BEGIN PROJECT_NAME-->
<td id="projectalign">
<div id="projectname">$projectname<!--BEGIN PROJECT_NUMBER--><span id="projectnumber">&#160;$projectnumber</span><!--END PROJECT_NUMBER-->
</div>
<!--BEGIN PROJECT_BRIEF--><div id="projectbrief">$projectbrief</div><!--END PROJECT_BRIEF-->
</td>
<!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME-->
<!--BEGIN PROJECT_BRIEF-->
<td>
<div id="projectbrief">$projectbrief</div>
</td>
<!--END PROJECT_BRIEF-->
<!--END !PROJECT_NAME-->
<!--BEGIN DISABLE_INDEX-->
<!--BEGIN SEARCHENGINE-->
<!--BEGIN !FULL_SIDEBAR-->
<td>$searchbox</td>
<!--END !FULL_SIDEBAR-->
<!--END SEARCHENGINE-->
<!--END DISABLE_INDEX-->
</tr>
<!--BEGIN SEARCHENGINE-->
<!--BEGIN FULL_SIDEBAR-->
<tr><td colspan="2">$searchbox</td></tr>
<!--END FULL_SIDEBAR-->
<!--END SEARCHENGINE-->
</tbody>
</table>
</div>
<!--END TITLEAREA-->
<!-- end header part -->

View File

@ -1,6 +0,0 @@
#include <base/base58.hpp>
#include <base/base64.hpp>
#include <base/baseN.hpp>
#include <base/hash/sha256.hpp>
#include <base/hex.hpp>

View File

@ -1,27 +0,0 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace base58
{
extern const char digits[59];
extern const int8_t map[256];
bool isValid(const char *str, uint64_t str_size) noexcept;
bool isValid(std::string_view str) noexcept;
uint64_t sizeEncoded(std::span<const uint8_t> data) noexcept;
uint64_t sizeDecoded(std::string_view str) noexcept;
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size) noexcept;
std::string encode(std::span<const uint8_t> data) noexcept;
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size) noexcept;
std::vector<uint8_t> decode(std::string_view str) noexcept;
std::string encodeCheck(std::span<const uint8_t> data) noexcept;
std::vector<uint8_t> decodeCheck(std::string_view str);
}

View File

@ -1,24 +0,0 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace base64
{
extern const char digits[65];
extern const int8_t map[256];
bool isValid(const char *str, uint64_t str_size) noexcept;
bool isValid(std::string_view str) noexcept;
uint64_t sizeEncoded(std::span<const uint8_t> data);
uint64_t sizeDecoded(std::string_view str) noexcept;
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size);
std::string encode(std::span<const uint8_t> data) noexcept;
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size);
std::vector<uint8_t> decode(std::string_view str) noexcept;
}

View File

@ -1,21 +0,0 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace baseN
{
bool isValid(const char *str, uint64_t str_size, const int8_t *map) noexcept;
bool isValid(std::string_view str, const int8_t *map) noexcept;
uint64_t sizeEncoded(std::span<const uint8_t> data, uint8_t base);
uint64_t sizeDecoded(std::string_view str, uint8_t base) noexcept;
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size, uint8_t base, const char *digits);
std::string encode(std::span<const uint8_t> data, uint8_t base, const char *digits) noexcept;
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size, uint8_t base, const char *digits, const int8_t *map);
std::vector<uint8_t> decode(std::string_view str, uint8_t base, const char *digits, const int8_t *map) noexcept;
}

View File

@ -1,24 +0,0 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace hex
{
extern const char digits[17];
extern const int8_t map[256];
bool isValid(const char *str, uint64_t str_size) noexcept;
bool isValid(std::string_view str) noexcept;
uint64_t sizeEncoded(std::span<const uint8_t> data);
uint64_t sizeDecoded(std::string_view str) noexcept;
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size);
std::string encode(std::span<const uint8_t> data) noexcept;
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size);
std::vector<uint8_t> decode(std::string_view str) noexcept;
}

7
include/basen.hpp Normal file
View File

@ -0,0 +1,7 @@
#include <basen/base58.hpp>
#include <basen/base64.hpp>
#include <basen/baseN.hpp>
#include <basen/Exception.hpp>
#include <basen/hash/sha256.hpp>
#include <basen/hex.hpp>

View File

@ -0,0 +1,44 @@
#pragma once
#include <cstdint>
#include <exception>
#include <source_location>
#include <string>
#include <unordered_map>
namespace basen
{
class Exception : public std::exception
{
public:
enum class Code
{
BASE,
PADDING,
CHECKSUM,
OVERFLOW,
LENGTH,
OUT_OF_ALPH,
ALPH_COLLISION
};
static const std::unordered_map<Code, std::string> messages;
Exception(Code code, const std::source_location &location = std::source_location::current());
const char *what() const noexcept override
{
return _what.c_str();
}
inline const char *message() const noexcept
{
return messages.at(_code).c_str();
}
inline Code code() const noexcept
{
return _code;
}
private:
Code _code;
std::string _what;
};
}

51
include/basen/base58.hpp Normal file
View File

@ -0,0 +1,51 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace base58
{
/**
* @brief bitcoin alphabet
*/
extern const char digits[59];
extern const uint8_t map[256];
bool isValid(const char *str, size_t str_size) noexcept;
bool isValid(std::string_view str) noexcept;
/**
* @throw basen::Exception(OVERFLOW) if there is an overflow
*/
size_t sizeEncoded(std::span<const uint8_t> data);
size_t sizeDecoded(std::string_view str) noexcept;
/**
* @return number of leading chars, which should be trimmed
* @warning contain leading zeros, returns count of them
*/
size_t encode(const uint8_t *data, size_t data_size, char *str, size_t str_size);
std::string encode(std::span<const uint8_t> data);
/**
* @return number of leading chars, which should be trimmed
* @warning contain leading zeros, returns count of them
*/
size_t decode(const char *str, size_t str_size, uint8_t *data, size_t data_size);
std::vector<uint8_t> decode(std::string_view str);
/**
* @param data vector or span of data which you want to encode
* @return encoded string + 4 first bytes of double sha256
*/
std::string encodeCheck(std::span<const uint8_t> data);
/**
* @param str string or string_view which you want to decode
* @return decoded data without 4 first bytes of double sha256
* @throw basen::Exception(PADDING) if str size < 4
* @throw basen::Exception(CHECKSUM) checksum incorrect
*/
std::vector<uint8_t> decodeCheck(std::string_view str);
}

37
include/basen/base64.hpp Normal file
View File

@ -0,0 +1,37 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace base64
{
extern const char digits[65];
extern const uint8_t map[256];
bool isValid(const char *str, size_t str_size) noexcept;
bool isValid(std::string_view str) noexcept;
/**
* @throw basen::Exception(OVERFLOW) if there is an overflow
*/
size_t sizeEncoded(std::span<const uint8_t> data);
size_t sizeDecoded(std::string_view str) noexcept;
/**
* @throw basen::Exception(LENGTH) if not enough allocated length
* @warning contain leading zeros, returns count of them
*/
void encode(const uint8_t *data, size_t data_size, char *str, size_t str_size);
std::string encode(std::span<const uint8_t> data);
/**
* @throw basen::Exception(LENGTH) if not enough allocated length
* @throw basen::Exception(OUT_OF_ALPH) if out of digits map
* @throw basen::Exception(PADDING) if incorrect padding
* @warning contain leading zeros, returns count of them
*/
void decode(const char *str, size_t str_size, uint8_t *data, size_t data_size);
std::vector<uint8_t> decode(std::string_view str);
}

114
include/basen/baseN.hpp Normal file
View File

@ -0,0 +1,114 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace baseN
{
/**
* @param digits char[base] array of digits
* @param digits_size size of digits array. Equals to base
* @param map [out] uint8_t[256] array, where at an index equal to the value of the symbol is the index of this symbol in the digits array. 255 if there is no symbol
* @throw basen::Exception(ALPH_COLLISION) if alphabet contain same chars
*/
void digitsMap(const char *digits, uint8_t digits_size, uint8_t *map);
/**
* @param str [in] pointer to string
* @param str_size
* @param map uint8_t[256] array, where at an index equal to the value of the symbol is the index of this symbol in the digits array. 255 if there is no symbol
* @return that string doesn't contain unnecessary symbols
*/
bool isValid(const char *str, size_t str_size, const uint8_t *map) noexcept;
/**
* @param str string or string_view which you want to decode
* @param map uint8_t[256] array, where at an index equal to the value of the symbol is the index of this symbol in the digits array. 255 if there is no symbol
* @return that string doesn't contain unnecessary symbols
*/
bool isValid(std::string_view str, const uint8_t *map) noexcept;
/**
* @param data vector or span of data which you want to encode
* @param base from 1 to 255
* @return estimated size after encoding
* @throw basen::Exception(BASE) if base < 2 || base > 254
*/
size_t sizeEncoded(std::span<const uint8_t> data, uint8_t base);
/**
* @param str string or string_view which you want to decode
* @param base from 1 to 255
* @param digits char[base] array of digits
* @return estimated size after decoding
* @throw basen::Exception(BASE) if base < 2 || base > 254
* @throw basen::Exception(OVERFLOW) if if there is an overflow
*/
size_t sizeDecoded(std::string_view str, uint8_t base, const char *digits);
/**
* @param data [in] pointer to data which you want encode
* @param data_size
* @param str [out] pointer to string for encoded data output
* @param str_size
* @param base from 1 to 255
* @param digits char[base] array of digits
* @code{cpp}
* std::vector<uint8_t> data;
* std::string str(baseN::sizeEncoded(data, 58), ' ');
*
* auto offset = baseN::encode(data.data(), data.size(), str.data(), str.size(), 58, base58::digits);
* // deleting leading zeroes
* str.erase(str.begin(), str.begin() + offset);
* @endcode
* @return number of leading chars, which should be trimmed
* @throw basen::Exception(BASE) if base < 2 || base > 254
* @warning contain leading zeros, returns count of them
*/
size_t encode(const uint8_t *data, size_t data_size, char *str, size_t str_size, uint8_t base, const char *digits);
/**
* @param data vector or span of data which you want to encode
* @param base from 1 to 255
* @param digits char[base] array of digits
* @code{cpp}
* std::vector<uint8_t> data;
* auto str = baseN::encode(data, 58, base58::digits);
* @endcode
* @return encoded string
*/
std::string encode(std::span<const uint8_t> data, uint8_t base, const char *digits);
/**
* @param str [in] pointer to string which you want decode
* @param str_size
* @param data [out] pointer to data for encoded string output
* @param data_size
* @param base from 1 to 255
* @param digits char[base] array of digits
* @param map uint8_t[256] array, where at an index equal to the value of the symbol is the index of this symbol in the digits array. 255 if there is no symbol
* @code{cpp}
* std::string str;
* std::vector<uint8_t> data(baseN::sizeDecoded(str, 58));
*
* auto offset = baseN::decode(str.data(), str.size(), data.data(), data.size(), 58, base58::digits, base58::map);
* // deleting leading zeroes
* data.erase(data.begin(), data.begin() + offset);
* @endcode
* @return number of leading chars, which should be trimmed
* @throw basen::Exception(BASE) if base < 2 || base > 254
* @throw basen::Exception(OUT_OF_ALPH) if out of alphabet
* @warning contain leading zeros, returns count of them
*/
size_t decode(const char *str, size_t str_size, uint8_t *data, size_t data_size, uint8_t base, const char *digits, const uint8_t *map);
/**
* @param str string or string_view which you want to decode
* @param base from 1 to 255
* @param digits char[base] array of digits
* @param map uint8_t[256] array, where at an index equal to the value of the symbol is the index of this symbol in the digits array. 255 if there is no symbol
* @code{cpp}
* std::string str;
* auto data = baseN::decode(str, 58, base58::digits, base58::map);
* @endcode
* @return decoded data
*/
std::vector<uint8_t> decode(std::string_view str, uint8_t base, const char *digits, const uint8_t *map);
}

View File

@ -4,9 +4,8 @@
#include <span> #include <span>
#include <vector> #include <vector>
#define SHA256_DIGEST_LENGTH 32 namespace hash
{
namespace hash { void sha256(const uint8_t *data, size_t data_size, uint8_t *hash) noexcept;
void sha256(const uint8_t *data, uint64_t data_size, uint8_t *hash) noexcept;
std::vector<uint8_t> sha256(std::span<const uint8_t> data) noexcept; std::vector<uint8_t> sha256(std::span<const uint8_t> data) noexcept;
} }

37
include/basen/hex.hpp Normal file
View File

@ -0,0 +1,37 @@
#pragma once
#include <cstdint>
#include <span>
#include <string>
#include <vector>
namespace hex
{
extern const char digits[17];
extern const uint8_t map[256];
bool isValid(const char *str, size_t str_size) noexcept;
bool isValid(std::string_view str) noexcept;
/**
* @throw basen::Exception(OVERFLOW) if there is an overflow
*/
size_t sizeEncoded(std::span<const uint8_t> data);
size_t sizeDecoded(std::string_view str) noexcept;
/**
* @throw basen::Exception(LENGTH) if not enough allocated length
* @warning contain leading zeros, returns count of them
*/
void encode(const uint8_t *data, size_t data_size, char *str, size_t str_size);
std::string encode(std::span<const uint8_t> data);
/**
* @throw basen::Exception(LENGTH) if not enough allocated length
* @throw basen::Exception(OUT_OF_ALPH) if out of digits map
* @throw basen::Exception(PADDING) if str_size %2 != 0 (isn't hex)
* @warning contain leading zeros, returns count of them
*/
void decode(const char *str, size_t str_size, uint8_t *data, size_t data_size);
std::vector<uint8_t> decode(std::string_view str);
}

29
src/Exception.cpp Normal file
View File

@ -0,0 +1,29 @@
#include <sstream>
#include <basen/Exception.hpp>
namespace basen
{
const std::unordered_map<Exception::Code, std::string> Exception::messages = {
{Code::BASE, "incorrect base"},
{Code::PADDING, "incorrect padding"},
{Code::CHECKSUM, "incorrect checksum"},
{Code::OVERFLOW, "overflow"},
{Code::LENGTH, "not enough allocated length"},
{Code::OUT_OF_ALPH, "out of alphabet"},
{Code::ALPH_COLLISION, "alphabet contains same chars"},
};
Exception::Exception(Code code, const std::source_location &location)
{
_code = code;
std::ostringstream oss;
oss << "\033[34m"
<< location.function_name()
<< ':'
<< location.line()
<< ": \033[31mbasen::Exception:\n\t\033[0m"
<< message()
<< "\n";
_what = oss.str();
}
}

View File

@ -1,33 +1,34 @@
#include <stdexcept> #include <stdexcept>
#include <base/base58.hpp> #include <basen/base58.hpp>
#include <base/baseN.hpp> #include <basen/baseN.hpp>
#include <base/hash/sha256.hpp> #include <basen/Exception.hpp>
#include <basen/hash/sha256.hpp>
namespace base58 namespace base58
{ {
const char digits[] = const char digits[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
const int8_t map[] = { const uint8_t map[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 255, 255, 255, 255, 255, 255,
-1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1, 255, 9, 10, 11, 12, 13, 14, 15, 16, 255, 17, 18, 19, 20, 21, 255,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 255, 255, 255, 255, 255,
-1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46, 255, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 255, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, -1, -1, -1, -1, -1, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
// //
}; };
bool isValid(const char *str, uint64_t str_size) noexcept bool isValid(const char *str, size_t str_size) noexcept
{ {
return baseN::isValid(str, str_size, map); return baseN::isValid(str, str_size, map);
} }
@ -35,31 +36,31 @@ namespace base58
{ {
return baseN::isValid(str, map); return baseN::isValid(str, map);
} }
uint64_t sizeEncoded(std::span<const uint8_t> data) noexcept size_t sizeEncoded(std::span<const uint8_t> data)
{ {
return baseN::sizeEncoded(data, 58); return baseN::sizeEncoded(data, 58);
} }
uint64_t sizeDecoded(std::string_view str) noexcept size_t sizeDecoded(std::string_view str) noexcept
{ {
return baseN::sizeDecoded(str, 58); return baseN::sizeDecoded(str, 58, digits);
} }
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size) noexcept size_t encode(const uint8_t *data, size_t data_size, char *str, size_t str_size)
{ {
baseN::encode(data, data_size, str, str_size, 58, digits); return baseN::encode(data, data_size, str, str_size, 58, digits);
} }
std::string encode(std::span<const uint8_t> data) noexcept std::string encode(std::span<const uint8_t> data)
{ {
return baseN::encode(data, 58, digits); return baseN::encode(data, 58, digits);
} }
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size) noexcept size_t decode(const char *str, size_t str_size, uint8_t *data, size_t data_size)
{ {
baseN::decode(str, str_size, data, data_size, 58, digits, map); return baseN::decode(str, str_size, data, data_size, 58, digits, map);
} }
std::vector<uint8_t> decode(std::string_view str) noexcept std::vector<uint8_t> decode(std::string_view str)
{ {
return baseN::decode(str, 58, digits, map); return baseN::decode(str, 58, digits, map);
} }
std::string encodeCheck(std::span<const uint8_t> data) noexcept std::string encodeCheck(std::span<const uint8_t> data)
{ {
std::vector<uint8_t> buff(data.begin(), data.end()), dhash; std::vector<uint8_t> buff(data.begin(), data.end()), dhash;
dhash = hash::sha256(hash::sha256(data)); dhash = hash::sha256(hash::sha256(data));
@ -69,11 +70,15 @@ namespace base58
std::vector<uint8_t> decodeCheck(std::string_view str) std::vector<uint8_t> decodeCheck(std::string_view str)
{ {
std::vector<uint8_t> buff(base58::decode(str)); std::vector<uint8_t> buff(base58::decode(str));
if (buff.size() < 4)
{
throw basen::Exception(basen::Exception::Code::PADDING);
}
std::span<uint8_t> data(buff.begin(), buff.end() - 4); std::span<uint8_t> data(buff.begin(), buff.end() - 4);
std::span<uint8_t> dhash(buff.end() - 4, buff.end()); std::span<uint8_t> dhash(buff.end() - 4, buff.end());
if (!std::equal(dhash.begin(), dhash.end(), hash::sha256(hash::sha256(data)).begin())) if (!std::equal(dhash.begin(), dhash.end(), hash::sha256(hash::sha256(data)).begin()))
{ {
throw std::logic_error("base58::decodeCheck: checksum incorrect"); throw basen::Exception(basen::Exception::Code::CHECKSUM);
} }
return std::vector<uint8_t>(data.begin(), data.end()); return std::vector<uint8_t>(data.begin(), data.end());
} }

View File

@ -2,33 +2,34 @@
#include <limits> #include <limits>
#include <stdexcept> #include <stdexcept>
#include <base/base64.hpp> #include <basen/base64.hpp>
#include <base/baseN.hpp> #include <basen/baseN.hpp>
#include <basen/Exception.hpp>
namespace base64 namespace base64
{ {
const char digits[] = const char digits[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const int8_t map[] = { const uint8_t map[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
// //
}; };
bool isValid(const char *str, uint64_t str_size) noexcept bool isValid(const char *str, size_t str_size) noexcept
{ {
return base64::isValid(std::string_view(str, str_size)); return base64::isValid(std::string_view(str, str_size));
} }
@ -43,103 +44,100 @@ namespace base64
} }
return baseN::isValid(sv, map); return baseN::isValid(sv, map);
} }
uint64_t sizeEncoded(std::span<const uint8_t> data) size_t sizeEncoded(std::span<const uint8_t> data)
{ {
uint64_t str_size = data.size() / 3; size_t str_size = data.size() / 3;
if (str_size > std::numeric_limits<uint64_t>::max() / 4) if (str_size > std::numeric_limits<size_t>::max() / 4)
{ {
throw std::overflow_error("base64::sizeEncoded: overflow"); throw basen::Exception(basen::Exception::Code::OVERFLOW);
} }
str_size = str_size * 4 + (data.size() % 3 ? 4 : 0); str_size = str_size * 4 + (data.size() % 3 ? 4 : 0);
return str_size; return str_size;
} }
uint64_t sizeDecoded(std::string_view str) noexcept size_t sizeDecoded(std::string_view str) noexcept
{ {
auto size = std::distance(str.begin(), std::find_if(str.rbegin(), str.rend(), [](char ch) auto size = std::distance(str.begin(), std::find_if(str.rbegin(), str.rend(), [](char ch)
{ return ch != '='; }) { return ch != '='; })
.base()); .base());
return size / 4 * 3 + (size % 4 ? size % 4 - 1 : 0); return size / 4 * 3 + (size % 4 ? size % 4 - 1 : 0);
} }
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size) void encode(const uint8_t *data, size_t data_size, char *str, size_t str_size)
{ {
if (str_size < base64::sizeEncoded(std::span<const uint8_t>(data, data_size))) if (str_size < base64::sizeEncoded(std::span<const uint8_t>(data, data_size)))
{ {
throw std::logic_error("base64::encode: not enough allocated length"); throw basen::Exception(basen::Exception::Code::LENGTH);
} }
for (uint64_t i = 0; i < data_size / 3; i++) for (size_t i = 0; i < data_size / 3; i++)
{ {
str[i * 4] = digits[data[i * 3] >> 2]; str[i * 4] = digits[data[i * 3] >> 2];
str[i * 4 + 1] = digits[(data[i * 3] << 4 | data[i * 3 + 1] >> 4) & 0x3F]; str[i * 4 + 1] = digits[(data[i * 3] << 4 | data[i * 3 + 1] >> 4) & 0x3F];
str[i * 4 + 2] = digits[(data[i * 3 + 1] << 2 | data[i * 3 + 2] >> 6) & 0x3F]; str[i * 4 + 2] = digits[(data[i * 3 + 1] << 2 | data[i * 3 + 2] >> 6) & 0x3F];
str[i * 4 + 3] = digits[data[i * 3 + 2] & 0x3F]; str[i * 4 + 3] = digits[data[i * 3 + 2] & 0x3F];
} }
uint64_t last_idx = data_size / 3 * 4; size_t last_idx = data_size / 3 * 4;
if (last_idx + 3 < str_size) switch (data_size % 3)
{ {
switch (data_size % 3) case 1:
{ str[last_idx] = digits[data[data_size - 1] >> 2];
case 1: str[last_idx + 1] = digits[data[data_size - 1] << 4 & 0x30];
str[last_idx] = digits[data[data_size - 1] >> 2]; str[last_idx + 2] = '=';
str[last_idx + 1] = digits[data[data_size - 1] << 4 & 0x30]; str[last_idx + 3] = '=';
str[last_idx + 2] = '='; break;
str[last_idx + 3] = '='; case 2:
break; str[last_idx] = digits[data[data_size - 2] >> 2];
case 2: str[last_idx + 1] = digits[(data[data_size - 2] << 4 | data[data_size - 1] >> 4) & 0x3F];
str[last_idx] = digits[data[data_size - 2] >> 2]; str[last_idx + 2] = digits[data[data_size - 1] << 2 & 0x3F];
str[last_idx + 1] = digits[(data[data_size - 2] << 4 | data[data_size - 1] >> 4) & 0x3F]; str[last_idx + 3] = '=';
str[last_idx + 2] = digits[data[data_size - 1] & 0x0F]; break;
str[last_idx + 3] = '='; default:
break; break;
default:
break;
}
} }
} }
std::string encode(std::span<const uint8_t> data) noexcept std::string encode(std::span<const uint8_t> data)
{ {
std::string str(base64::sizeEncoded(data), ' '); std::string str(base64::sizeEncoded(data), ' ');
base64::encode(data.data(), data.size(), str.data(), str.size()); base64::encode(data.data(), data.size(), str.data(), str.size());
return str; return str;
} }
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size) void decode(const char *str, size_t str_size, uint8_t *data, size_t data_size)
{ {
std::string_view sv(str, str_size); std::string_view sv(str, str_size);
if (data_size < base64::sizeDecoded(sv)) if (data_size < base64::sizeDecoded(sv))
{ {
throw std::logic_error("base64::decode: not enough allocated length"); throw basen::Exception(basen::Exception::Code::LENGTH);
} }
if (!base64::isValid(sv)) if (!base64::isValid(sv))
{ {
throw std::logic_error("base64::decode: out of digits map"); throw basen::Exception(basen::Exception::Code::OUT_OF_ALPH);
} }
auto size = std::distance(sv.begin(), std::find_if(sv.rbegin(), sv.rend(), [](char ch) auto size = std::distance(sv.begin(), std::find_if(sv.rbegin(), sv.rend(), [](char ch)
{ return ch != '='; }) { return ch != '='; })
.base()); .base());
if (sv.size() % 4 != 0 || sv.size() - size > 2) if (sv.size() % 4 != 0 || sv.size() - size > 2)
{ {
throw std::logic_error("base64::decode: incorrect padding"); throw basen::Exception(basen::Exception::Code::PADDING);
} }
for (auto i = 0; i < size / 4; i++) for (auto i = 0; i < size / 4; i++)
{ {
data[i * 3] = map[(int8_t)str[i * 4]] << 2 | map[(int8_t)str[i * 4 + 1]] >> 4; data[i * 3] = map[(uint8_t)str[i * 4]] << 2 | map[(uint8_t)str[i * 4 + 1]] >> 4;
data[i * 3 + 1] = map[(int8_t)str[i * 4 + 1]] << 4 | map[(int8_t)str[i * 4 + 2]] >> 2; data[i * 3 + 1] = map[(uint8_t)str[i * 4 + 1]] << 4 | map[(uint8_t)str[i * 4 + 2]] >> 2;
data[i * 3 + 2] = map[(int8_t)str[i * 4 + 2]] << 6 | map[(int8_t)str[i * 4 + 3]]; data[i * 3 + 2] = map[(uint8_t)str[i * 4 + 2]] << 6 | map[(uint8_t)str[i * 4 + 3]];
} }
uint64_t last_idx = size / 4 * 3; size_t last_idx = size / 4 * 3;
switch (size % 4) switch (size % 4)
{ {
case 2: case 2:
data[last_idx] = map[(int8_t)str[size - 2]] << 2 | map[(int8_t)str[size - 1]] >> 4; data[last_idx] = map[(uint8_t)str[size - 2]] << 2 | map[(uint8_t)str[size - 1]] >> 4;
break; break;
case 3: case 3:
data[last_idx] = map[(int8_t)str[size - 3]] << 2 | map[(int8_t)str[size - 2]] >> 4; data[last_idx] = map[(uint8_t)str[size - 3]] << 2 | map[(uint8_t)str[size - 2]] >> 4;
data[last_idx + 1] = map[(int8_t)str[size - 2]] << 4 | map[(int8_t)str[size - 1]] >> 2; data[last_idx + 1] = map[(uint8_t)str[size - 2]] << 4 | map[(uint8_t)str[size - 1]] >> 2;
break; break;
default: default:
break; break;
} }
} }
std::vector<uint8_t> decode(std::string_view str) noexcept std::vector<uint8_t> decode(std::string_view str)
{ {
std::vector<uint8_t> data(base64::sizeDecoded(str)); std::vector<uint8_t> data(base64::sizeDecoded(str));
base64::decode(str.data(), str.size(), data.data(), data.size()); base64::decode(str.data(), str.size(), data.data(), data.size());

View File

@ -3,126 +3,166 @@
#include <limits> #include <limits>
#include <stdexcept> #include <stdexcept>
#include <base/baseN.hpp> #include <basen/baseN.hpp>
#include <basen/Exception.hpp>
static constexpr auto log256 = std::log(256); static constexpr auto log256 = std::log(256);
namespace baseN namespace baseN
{ {
bool isValid(const char *str, uint64_t str_size, const int8_t *map) noexcept void digitsMap(const char *digits, uint8_t digits_size, uint8_t *map)
{
std::fill(map, map + 256, 255);
for (uint8_t i = 0; i < digits_size; i++)
{
if (map[(uint8_t)digits[i]] != 255)
{
throw basen::Exception(basen::Exception::Code::ALPH_COLLISION);
}
map[(uint8_t)digits[i]] = i;
}
}
bool isValid(const char *str, size_t str_size, const uint8_t *map) noexcept
{ {
return std::all_of(str, str + str_size, [map](char ch) return std::all_of(str, str + str_size, [map](char ch)
{ return map[(int8_t)ch] != -1; }); { return map[(uint8_t)ch] != 255; });
} }
bool isValid(std::string_view str, const int8_t *map) noexcept bool isValid(std::string_view str, const uint8_t *map) noexcept
{ {
return baseN::isValid(str.data(), str.size(), map); return baseN::isValid(str.data(), str.size(), map);
} }
uint64_t sizeEncoded(std::span<const uint8_t> data, uint8_t base) size_t sizeEncoded(std::span<const uint8_t> data, uint8_t base)
{ {
if (data.size() > std::numeric_limits<uint64_t>::max() / log256) if (base < 2 || base > 254)
{ {
throw std::overflow_error("baseN::sizeEncoded: overflow"); throw basen::Exception(basen::Exception::Code::BASE);
} }
return data.size() * log256 / std::log(base) + 1; std::span<const uint8_t> dv(std::find_if(data.begin(), data.end(), [](uint8_t item)
{ return item != 0; }),
data.end());
if (dv.size() > std::numeric_limits<size_t>::max() / log256)
{
throw basen::Exception(basen::Exception::Code::OVERFLOW);
}
return dv.size() * log256 / std::log(base) + 1 + (data.size() - dv.size());
} }
uint64_t sizeDecoded(std::string_view str, uint8_t base) noexcept size_t sizeDecoded(std::string_view str, uint8_t base, const char *digits)
{ {
return str.size() * std::log(base) / log256 + 1; if (base < 2 || base > 254)
{
throw basen::Exception(basen::Exception::Code::BASE);
}
std::string_view sv(std::find_if(str.begin(), str.end(), [digits](uint8_t ch)
{ return ch != digits[0]; }),
str.end());
return sv.size() * std::log(base) / log256 + 1 + (str.size() - sv.size());
} }
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size, uint8_t base, const char *digits) size_t encode(const uint8_t *data, size_t data_size, char *str, size_t str_size, uint8_t base, const char *digits)
{ {
if (base < 2 || base > 254)
{
throw basen::Exception(basen::Exception::Code::BASE);
}
std::vector<uint8_t> dv(std::find_if(data, data + data_size, [](uint8_t item) std::vector<uint8_t> dv(std::find_if(data, data + data_size, [](uint8_t item)
{ return item != 0; }), { return item != 0; }),
data + data_size); data + data_size);
if (dv.size() == 0)
{
return;
}
std::span<char> sv(str, str_size); std::span<char> sv(str, str_size);
auto sv_it = sv.rbegin(); auto sv_it = sv.rbegin();
auto dv_it = dv.begin(); auto dv_it = dv.begin();
auto quo_it = dv.begin(); auto quo_it = dv.begin();
auto quo_it_last = dv.end(); auto quo_it_last = dv.end();
uint16_t div = *dv_it++;
while ((dv[0] > base || quo_it_last > dv.begin() + 1) && sv_it < sv.rend() - 1) if (dv.size() != 0)
{ {
if (div < base) uint16_t div = *dv_it++;
while ((dv[0] > base || quo_it_last > dv.begin() + 1) && sv_it < sv.rend() - 1)
{ {
div <<= 8; if (div < base)
div += *dv_it++; {
} div <<= 8;
*quo_it++ = div / base; div += *dv_it++;
div %= base; }
while (dv_it < quo_it_last)
{
div <<= 8;
div += *dv_it++;
*quo_it++ = div / base; *quo_it++ = div / base;
div %= base; div %= base;
while (dv_it < quo_it_last)
{
div <<= 8;
div += *dv_it++;
*quo_it++ = div / base;
div %= base;
}
quo_it_last = quo_it;
dv_it = dv.begin();
quo_it = dv.begin();
*sv_it++ = digits[div];
div = *dv_it++;
} }
quo_it_last = quo_it;
dv_it = dv.begin();
quo_it = dv.begin();
*sv_it++ = digits[div]; *sv_it++ = digits[div];
div = *dv_it++;
} }
*sv_it++ = digits[div]; for (size_t i = 0; i < data_size - dv.size() && sv_it < sv.rend(); i++)
for (uint64_t i = 0; i < data_size - dv.size() && sv_it < sv.rend(); i++)
{ {
*sv_it++ = digits[0]; *sv_it++ = digits[0];
} }
return std::distance(sv_it, sv.rend());
} }
std::string encode(std::span<const uint8_t> data, uint8_t base, const char *digits) noexcept std::string encode(std::span<const uint8_t> data, uint8_t base, const char *digits)
{ {
std::string str(baseN::sizeEncoded(data, base), ' '); std::string str(baseN::sizeEncoded(data, base), ' ');
baseN::encode(data.data(), data.size(), str.data(), str.size(), base, digits); size_t offset = baseN::encode(data.data(), data.size(), str.data(), str.size(), base, digits);
str.erase(str.begin(), std::find_if( str.erase(str.begin(), str.begin() + offset);
str.begin(), str.end(), [](char ch)
{ return ch != ' '; }));
return str; return str;
} }
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size, uint8_t base, const char *digits, const int8_t *map) size_t decode(const char *str, size_t str_size, uint8_t *data, size_t data_size, uint8_t base, const char *digits, const uint8_t *map)
{ {
if (base < 2 || base > 254)
{
throw basen::Exception(basen::Exception::Code::BASE);
}
std::string_view sv(std::find_if(str, str + str_size, [digits](char ch) std::string_view sv(std::find_if(str, str + str_size, [digits](char ch)
{ return ch != digits[0]; }), { return ch != digits[0]; }),
str_size); str + str_size);
if (sv.size() == 0)
{
return;
}
if (!baseN::isValid(sv, map)) if (!baseN::isValid(sv, map))
{ {
throw std::logic_error("baseN::decode: out of digits map"); throw basen::Exception(basen::Exception::Code::OUT_OF_ALPH);
} }
std::span<uint8_t> dv(data, data_size); std::span<uint8_t> dv(data, data_size);
auto sv_it = sv.begin(); auto sv_it = sv.begin();
auto quo_it = dv.rbegin(); auto quo_it = dv.rbegin();
auto quo_it_last = dv.rbegin() + 1; auto quo_it_last = dv.rbegin();
uint16_t div; uint16_t div;
*quo_it = map[(int8_t)*sv_it++]; if (sv.size() != 0)
while (sv_it < sv.end())
{ {
div = map[(int8_t)*sv_it++]; quo_it_last++;
while (quo_it < quo_it_last && quo_it < dv.rend() - 1) *quo_it = map[(uint8_t)*sv_it++];
while (sv_it < sv.end())
{ {
div += *quo_it * base; div = map[(uint8_t)*sv_it++];
*quo_it++ = div; while (quo_it < quo_it_last && quo_it < dv.rend())
div >>= 8; {
div += *quo_it * base;
*quo_it++ = div;
div >>= 8;
}
if (div != 0 && quo_it < dv.rend())
{
*quo_it++ = div;
}
quo_it_last = quo_it;
quo_it = dv.rbegin();
} }
*quo_it++ = div;
quo_it_last = quo_it;
quo_it = dv.rbegin();
} }
for (size_t i = 0; i < str_size - sv.size() && quo_it_last < dv.rend(); i++)
{
*quo_it_last++ = 0;
}
return std::distance(quo_it_last, dv.rend());
} }
std::vector<uint8_t> decode(std::string_view str, uint8_t base, const char *digits, const int8_t *map) noexcept std::vector<uint8_t> decode(std::string_view str, uint8_t base, const char *digits, const uint8_t *map)
{ {
std::vector<uint8_t> data(baseN::sizeDecoded(str, base)); std::vector<uint8_t> data(baseN::sizeDecoded(str, base, digits));
baseN::decode(str.data(), str.size(), data.data(), data.size(), base, digits, map); size_t offset = baseN::decode(str.data(), str.size(), data.data(), data.size(), base, digits, map);
data.erase(data.begin(), std::find_if(data.begin(), data.end(), [](uint8_t item) data.erase(data.begin(), data.begin() + offset);
{ return item != 0; }));
return data; return data;
} }
} }

150
src/basen.cpp Normal file
View File

@ -0,0 +1,150 @@
#include <functional>
#include <iostream>
#include <unordered_map>
#include <argparse/argparse.hpp>
#include <basen.hpp>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <unistd.h>
#endif
namespace basen
{
typedef std::string (*encoder_t)(std::span<const uint8_t>);
typedef std::vector<uint8_t> (*decoder_t)(std::string_view);
const std::unordered_map<std::string, encoder_t> encoders = {
{"base58", base58::encode},
{"base58check", base58::encodeCheck},
{"base64", base64::encode},
{"hex", hex::encode},
};
const std::unordered_map<std::string, decoder_t> decoders = {
{"base58", base58::decode},
{"base58check", base58::decodeCheck},
{"base64", base64::decode},
{"hex", hex::decode},
};
std::string getPipe()
{
std::string str;
str.reserve(1024 * 1024);
#ifdef _WIN32
if (_isatty(_fileno(stdin)))
#else
if (isatty(fileno(stdin)))
#endif
{
throw std::logic_error("should use pipe syntax ( | or < )");
}
else
{
char temp[4096];
while (std::cin.read(temp, sizeof(temp)))
{
str.insert(str.end(), temp, temp + std::cin.gcount());
}
str.insert(str.end(), temp, temp + std::cin.gcount());
}
if (!str.empty() && str.back() == '\n')
{
str.erase(str.size() - 1);
}
return str;
}
uint8_t error(const std::string &str, argparse::ArgumentParser &program) noexcept
{
std::cerr << "\033[31merror:\t\033[0m"
<< str << "\n\n"
<< program << '\n';
return 1;
}
}
int main(int argc, char *argv[])
{
argparse::ArgumentParser program("basen", "1.1.0");
program.add_argument("-t", "--type")
.help("encoding type")
.metavar("STRING")
.choices("base58", "base58check", "base64", "hex");
program.add_argument("-a", "--alphabet")
.help("specify alphabet")
.metavar("STRING");
program.add_argument("-d", "--decode")
.help("decode flag")
.flag();
try
{
program.parse_args(argc, argv);
}
catch (const std::exception &err)
{
return basen::error(err.what(), program);
}
if (!program.is_used("-t") && !program.is_used("-a"))
{
return basen::error("either -t or -a should be provided", program);
}
if (program.is_used("-t") && program.is_used("-a"))
{
return basen::error("-t and -a cannot be used together", program);
}
std::string str;
try
{
str = basen::getPipe();
}
catch (const std::exception &e)
{
return basen::error(e.what(), program);
}
try
{
if (program.is_used("-t"))
{
auto type = program.get<std::string>("-t");
if (program.is_used("-d"))
{
auto data = (*basen::decoders.at(type))(str);
std::for_each(data.begin(), data.end(), [](uint8_t item)
{ std::cout << (char)item; });
std::cout << '\n';
}
else
{
std::span<uint8_t> dv((uint8_t *)str.data(), str.size());
std::cout << (*basen::encoders.at(type))(dv) << '\n';
}
}
if (program.is_used("-a"))
{
auto alphabet = program.get<std::string>("-a");
uint8_t map[256];
baseN::digitsMap(alphabet.data(), alphabet.size(), map);
if (program.is_used("-d"))
{
auto data = baseN::decode(str, alphabet.size(), alphabet.data(), map);
std::for_each(data.begin(), data.end(), [](uint8_t item)
{ std::cout << (char)item; });
std::cout << '\n';
}
else
{
std::span<uint8_t> dv((uint8_t *)str.data(), str.size());
std::cout << baseN::encode(dv, alphabet.size(), alphabet.data()) << '\n';
}
}
}
catch (const basen::Exception &e)
{
return basen::error(e.message(), program);
}
return 0;
}

View File

@ -15,7 +15,7 @@
#include <memory.h> #include <memory.h>
#include <stdlib.h> #include <stdlib.h>
#include <base/hash/sha256.hpp> #include <basen/hash/sha256.hpp>
#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b)))) #define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))
#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b)))) #define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))
@ -165,7 +165,7 @@ static void sha256_final(SHA256_CTX *ctx, uint8_t *hash)
namespace hash namespace hash
{ {
void sha256(const uint8_t *data, uint64_t data_size, uint8_t *hash) noexcept void sha256(const uint8_t *data, size_t data_size, uint8_t *hash) noexcept
{ {
SHA256_CTX ctx; SHA256_CTX ctx;
sha256_init(&ctx); sha256_init(&ctx);
@ -174,7 +174,7 @@ namespace hash
} }
std::vector<uint8_t> sha256(std::span<const uint8_t> data) noexcept std::vector<uint8_t> sha256(std::span<const uint8_t> data) noexcept
{ {
std::vector<uint8_t> hash(SHA256_DIGEST_LENGTH); std::vector<uint8_t> hash(32);
sha256(data.data(), data.size(), hash.data()); sha256(data.data(), data.size(), hash.data());
return hash; return hash;
} }

View File

@ -1,32 +1,33 @@
#include <limits> #include <limits>
#include <stdexcept> #include <stdexcept>
#include <base/baseN.hpp> #include <basen/baseN.hpp>
#include <base/hex.hpp> #include <basen/Exception.hpp>
#include <basen/hex.hpp>
namespace hex namespace hex
{ {
const char digits[] = "0123456789abcdef"; const char digits[] = "0123456789abcdef";
const int8_t map[] = { const uint8_t map[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
// //
}; };
bool isValid(const char *str, uint64_t str_size) noexcept bool isValid(const char *str, size_t str_size) noexcept
{ {
return baseN::isValid(str, str_size, map); return baseN::isValid(str, str_size, map);
} }
@ -34,56 +35,56 @@ namespace hex
{ {
return baseN::isValid(str, map); return baseN::isValid(str, map);
} }
uint64_t sizeEncoded(std::span<const uint8_t> data) size_t sizeEncoded(std::span<const uint8_t> data)
{ {
if (data.size() > std::numeric_limits<uint64_t>::max() / 2) if (data.size() > std::numeric_limits<size_t>::max() / 2)
{ {
throw std::overflow_error("hex::sizeEncoded: overflow"); throw basen::Exception(basen::Exception::Code::OVERFLOW);
} }
return data.size() * 2; return data.size() * 2;
} }
uint64_t sizeDecoded(std::string_view str) noexcept size_t sizeDecoded(std::string_view str) noexcept
{ {
return str.size() / 2; return str.size() / 2;
} }
void encode(const uint8_t *data, uint64_t data_size, char *str, uint64_t str_size) void encode(const uint8_t *data, size_t data_size, char *str, size_t str_size)
{ {
if (str_size < hex::sizeEncoded(std::span<const uint8_t>(data, data_size))) if (str_size < hex::sizeEncoded(std::span<const uint8_t>(data, data_size)))
{ {
throw std::logic_error("hex::encode: not enough allocated length"); throw basen::Exception(basen::Exception::Code::LENGTH);
} }
for (uint64_t i = 0; i < data_size; i++) for (size_t i = 0; i < data_size; i++)
{ {
str[i * 2] = digits[data[i] >> 4]; str[i * 2] = digits[data[i] >> 4];
str[i * 2 + 1] = digits[data[i] & 0x0F]; str[i * 2 + 1] = digits[data[i] & 0x0F];
} }
} }
std::string encode(std::span<const uint8_t> data) noexcept std::string encode(std::span<const uint8_t> data)
{ {
std::string str(hex::sizeEncoded(data), ' '); std::string str(hex::sizeEncoded(data), ' ');
hex::encode(data.data(), data.size(), str.data(), str.size()); hex::encode(data.data(), data.size(), str.data(), str.size());
return str; return str;
} }
void decode(const char *str, uint64_t str_size, uint8_t *data, uint64_t data_size) void decode(const char *str, size_t str_size, uint8_t *data, size_t data_size)
{ {
if (str_size % 2 != 0) if (str_size % 2 != 0)
{ {
throw std::logic_error("hex::decode: isn't hex"); throw basen::Exception(basen::Exception::Code::PADDING);
} }
if (data_size < hex::sizeDecoded(std::string_view(str, str_size))) if (data_size < hex::sizeDecoded(std::string_view(str, str_size)))
{ {
throw std::logic_error("hex::decode: not enough allocated length"); throw basen::Exception(basen::Exception::Code::LENGTH);
} }
if (!hex::isValid(str, str_size)) if (!hex::isValid(str, str_size))
{ {
throw std::logic_error("hex::decode: out of digits map"); throw basen::Exception(basen::Exception::Code::OUT_OF_ALPH);
} }
for (uint64_t i = 0; i * 2 < str_size; i++) for (size_t i = 0; i * 2 < str_size; i++)
{ {
data[i] = map[(int8_t)str[i * 2]] << 4 | map[(int8_t)str[i * 2 + 1]]; data[i] = map[(uint8_t)str[i * 2]] << 4 | map[(uint8_t)str[i * 2 + 1]];
} }
} }
std::vector<uint8_t> decode(std::string_view str) noexcept std::vector<uint8_t> decode(std::string_view str)
{ {
std::vector<uint8_t> data(hex::sizeDecoded(str)); std::vector<uint8_t> data(hex::sizeDecoded(str));
hex::decode(str.data(), str.size(), data.data(), data.size()); hex::decode(str.data(), str.size(), data.data(), data.size());

View File

@ -1,5 +1,5 @@
#include <base/hash/sha256.hpp> #include <basen/hash/sha256.hpp>
#include <base/hex.hpp> #include <basen/hex.hpp>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using namespace hash; using namespace hash;
@ -11,7 +11,7 @@ TEST(hash, sha256)
TEST(hash, sha256_1e4) TEST(hash, sha256_1e4)
{ {
std::vector<uint8_t> data(32); std::vector<uint8_t> data(32);
for (uint64_t i = 0; i < 1e4; i++) for (size_t i = 0; i < 1e4; i++)
{ {
sha256(data); sha256(data);
} }

35
test/test-Exception.cpp Normal file
View File

@ -0,0 +1,35 @@
#include <basen/Exception.hpp>
#include <gtest/gtest.h>
TEST(Exception, Exception)
{
EXPECT_ANY_THROW(throw basen::Exception(basen::Exception::Code::BASE));
}
TEST(Exception, message)
{
try
{
throw basen::Exception(basen::Exception::Code::BASE);
}
catch (const basen::Exception &e)
{
EXPECT_STREQ(e.message(), "incorrect base");
}
}
TEST(Exception, code)
{
try
{
throw basen::Exception(basen::Exception::Code::BASE);
}
catch (const basen::Exception &e)
{
EXPECT_EQ(uint32_t(e.code()), uint32_t(basen::Exception::Code::BASE));
}
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@ -1,7 +1,8 @@
#include <utility> #include <utility>
#include <base/base58.hpp> #include <basen/base58.hpp>
#include <base/hex.hpp> #include <basen/Exception.hpp>
#include <basen/hex.hpp>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using namespace base58; using namespace base58;
@ -18,14 +19,7 @@ TEST(base58, encodeCheck)
TEST(base58, decodeCheck) TEST(base58, decodeCheck)
{ {
EXPECT_EQ(test.first, hex::encode(decodeCheck(test.second))); EXPECT_EQ(test.first, hex::encode(decodeCheck(test.second)));
try EXPECT_THROW(decodeCheck("incorrect"), basen::Exception);
{
decodeCheck("incorrect");
}
catch (const std::exception &e)
{
EXPECT_STREQ(e.what(), "base58::decodeCheck: checksum incorrect");
}
} }
int main(int argc, char **argv) int main(int argc, char **argv)

View File

@ -1,7 +1,8 @@
#include <utility> #include <utility>
#include <base/base64.hpp> #include <basen/base64.hpp>
#include <base/hex.hpp> #include <basen/Exception.hpp>
#include <basen/hex.hpp>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using namespace base64; using namespace base64;
@ -21,13 +22,19 @@ TEST(base64, isValid)
std::vector<std::pair<std::string, std::string>> tests = { std::vector<std::pair<std::string, std::string>> tests = {
{"", ""}, {"", ""},
{"BKUEpQ==", "04a504a5"}, {"BKUEpQ==", "04a504a5"},
{"BKUEpQA=", "04a504a500"}, {"aGVsbG8=", "68656c6c6f"},
{"BKUEpQAA", "04a504a50000"}, {"aGVsbG9v", "68656c6c6f6f"},
}; };
TEST(base64, encode) TEST(base64, encode)
{ {
for (auto it : tests) for (auto it : tests)
EXPECT_EQ(it.first, encode(hex::decode(it.second))); EXPECT_EQ(it.first, encode(hex::decode(it.second)));
std::vector<uint8_t> data = {0x74, 0x65, 0x73, 0x74};
std::string str = "";
EXPECT_THROW(encode(data.data(), std::numeric_limits<size_t>::max(), str.data(), str.size()), basen::Exception);
EXPECT_THROW(encode(data.data(), data.size(), str.data(), str.size()), basen::Exception);
EXPECT_NO_THROW(encode(data.data(), 0, str.data(), str.size()));
} }
TEST(base64, encode_1e7) TEST(base64, encode_1e7)
{ {
@ -38,6 +45,12 @@ TEST(base64, decode)
{ {
for (auto it : tests) for (auto it : tests)
EXPECT_EQ(hex::encode(decode(it.first)), it.second); EXPECT_EQ(hex::encode(decode(it.first)), it.second);
std::vector<uint8_t> data = {0x61, 0x6e, 0x6f};
EXPECT_THROW(decode("FFF", 3, data.data(), data.size()), basen::Exception);
EXPECT_THROW(decode("!@#!", 4, data.data(), data.size()), basen::Exception);
EXPECT_THROW(decode("FF==", 2, data.data(), 0), basen::Exception);
EXPECT_NO_THROW(decode("", 0, data.data(), 0));
} }
TEST(base64, decode_1e7) TEST(base64, decode_1e7)
{ {

View File

@ -1,12 +1,21 @@
#include <utility> #include <utility>
#include <base/base58.hpp> #include <basen/base58.hpp>
#include <base/baseN.hpp> #include <basen/baseN.hpp>
#include <base/hex.hpp> #include <basen/Exception.hpp>
#include <basen/hex.hpp>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using namespace baseN; using namespace baseN;
TEST(baseN, digitsMap)
{
uint8_t map[256];
digitsMap(base58::digits, 58, map);
EXPECT_TRUE(std::equal(map, map + 256, base58::map));
EXPECT_THROW(digitsMap("11", 2, map), basen::Exception);
}
TEST(baseN, isValid) TEST(baseN, isValid)
{ {
std::vector<std::pair<bool, std::string>> tests = { std::vector<std::pair<bool, std::string>> tests = {
@ -16,6 +25,28 @@ TEST(baseN, isValid)
for (auto it : tests) for (auto it : tests)
EXPECT_EQ(it.first, isValid(it.second, base58::map)); EXPECT_EQ(it.first, isValid(it.second, base58::map));
} }
TEST(baseN, sizeEncoded)
{
std::vector<std::pair<size_t, std::string>> tests = {
{6, "12341234"},
{5, "00000000"},
};
for (auto it : tests)
EXPECT_EQ(it.first, sizeEncoded(hex::decode(it.second), 58));
EXPECT_THROW(sizeEncoded(hex::decode(""), 0), basen::Exception);
}
TEST(baseN, sizeDecoded)
{
std::vector<std::pair<size_t, std::string>> tests = {
{3, "qwer"},
{5, "1111"},
};
for (auto it : tests)
EXPECT_EQ(it.first, sizeDecoded(it.second, 58, base58::digits));
EXPECT_THROW(sizeDecoded("", 0, base58::digits), basen::Exception);
}
std::vector<std::pair<std::string, std::string>> tests = { std::vector<std::pair<std::string, std::string>> tests = {
{"", ""}, {"", ""},
{"Ky", "044c"}, {"Ky", "044c"},
@ -23,6 +54,7 @@ std::vector<std::pair<std::string, std::string>> tests = {
{"KyKX", "387ae2"}, {"KyKX", "387ae2"},
{"KyKXa", "0ccbd755"}, {"KyKXa", "0ccbd755"},
{"KyKXaa", "02e62ec963"}, {"KyKXaa", "02e62ec963"},
{"111KyKX", "000000387ae2"},
{"4uqWDRyJZUpS6KKwLAiitndmv7TPFt2bfxVVfhJhgTn3Rh6aQtGHQY6PhhNDpCwSNU8a", {"4uqWDRyJZUpS6KKwLAiitndmv7TPFt2bfxVVfhJhgTn3Rh6aQtGHQY6PhhNDpCwSNU8a",
"057902f9cebebb68879911002aae743280140a78c4a077405b057902f9cebebb68879911002aae743280140a78c4a077405b"}, "057902f9cebebb68879911002aae743280140a78c4a077405b057902f9cebebb68879911002aae743280140a78c4a077405b"},
}; };
@ -41,6 +73,8 @@ TEST(baseN, decode)
{ {
for (auto it : tests) for (auto it : tests)
EXPECT_EQ(hex::encode(decode(it.first, 58, base58::digits, base58::map)), it.second); EXPECT_EQ(hex::encode(decode(it.first, 58, base58::digits, base58::map)), it.second);
EXPECT_THROW(decode("!@#", 58, base58::digits, base58::map), basen::Exception);
} }
TEST(baseN, decode_1e3) TEST(baseN, decode_1e3)
{ {

View File

@ -1,21 +1,29 @@
#include <base/hex.hpp> #include <utility>
#include <basen/Exception.hpp>
#include <basen/hex.hpp>
#include <gtest/gtest.h> #include <gtest/gtest.h>
using namespace hex; using namespace hex;
TEST(hex, isValid)
{
std::vector<std::pair<bool, std::string>> tests = {
{true, "1234"},
{false, "!@/"},
};
for (auto it : tests)
EXPECT_EQ(it.first, isValid(it.second));
}
TEST(hex, encode) TEST(hex, encode)
{ {
std::vector<uint8_t> data = {0x74, 0x65, 0x73, 0x74}; std::vector<uint8_t> data = {0x74, 0x65, 0x73, 0x74};
EXPECT_EQ("74657374", encode(data)); EXPECT_EQ("74657374", encode(data));
try
{ std::string str = "";
std::string str = ""; EXPECT_THROW(encode(data.data(), std::numeric_limits<size_t>::max(), str.data(), str.size()), basen::Exception);
encode(data.data(), data.size(), str.data(), str.size()); EXPECT_THROW(encode(data.data(), data.size(), str.data(), str.size()), basen::Exception);
} EXPECT_NO_THROW(encode(data.data(), 0, str.data(), str.size()));
catch (const std::exception &e)
{
EXPECT_STREQ(e.what(), "hex::encode: not enough allocated length");
}
} }
TEST(hex, encode_1e7) TEST(hex, encode_1e7)
{ {
@ -26,15 +34,11 @@ TEST(hex, decode)
{ {
std::vector<uint8_t> data = {0x61, 0x6e, 0x6f}; std::vector<uint8_t> data = {0x61, 0x6e, 0x6f};
EXPECT_EQ(decode("616e6f"), data); EXPECT_EQ(decode("616e6f"), data);
try
{ EXPECT_THROW(decode("FFF", 3, data.data(), data.size()), basen::Exception);
std::string str = ""; EXPECT_THROW(decode("!@#!", 4, data.data(), data.size()), basen::Exception);
decode("616", 3, data.data(), data.size()); EXPECT_THROW(decode("FF", 2, data.data(), 0), basen::Exception);
} EXPECT_NO_THROW(decode("", 0, data.data(), 0));
catch (const std::exception &e)
{
EXPECT_STREQ(e.what(), "hex::decode: isn't hex");
}
} }
TEST(hex, decode_1e7) TEST(hex, decode_1e7)
{ {