repo: bech32
action: commit
revision: 
path_from: 
revision_from: e4950b3947ef4c1c8630d105c68094f9dd6422cc:
path_to: 
revision_to: 
git.thebackupbox.net
bech32
git clone git://git.thebackupbox.net/bech32
commit e4950b3947ef4c1c8630d105c68094f9dd6422cc
Author: nullius 
Date:   Fri Dec 29 20:31:46 2017 +0000

    Create repository and make initial commit

diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7a187b76dd3fff6728eb462bccf874ad93103d7e
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,40 @@
+By nullius 
+PGP:	0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C
+Bitcoin:	3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG
+		bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h
+
+Copyright (c) 2017.  All rights reserved.
+
+The Antiviral License (AVL) v0.0.1, with added Bitcoin consensus clause:
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of the source code must retain the above copyright
+   and credit notices, this list of conditions, and the following
+   disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+   and credit notices, this list of conditions, and the following
+   disclaimer in the documentation and/or other materials provided
+   with the distribution.
+3. Derivative works hereof MUST NOT be redistributed under any license
+   containing terms which require derivative works and/or usages to
+   publish source code, viz. what is commonly known as a "copyleft"
+   or "viral" license.
+4. Derivative works hereof which have any functionality related to
+   digital money (so-called "cryptocurrency" MUST EITHER adhere to
+   consensus rules fully compatible with Bitcoin Core, OR use a name
+   which does not contain the word "Bitcoin".
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..645f37a3fcf1c3f6a22be28d559367164e820e17
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,5 @@
+CSTD=c99
+
+.include "Makefile.inc"
+
+.include 
diff --git a/Makefile.inc b/Makefile.inc
new file mode 100644
index 0000000000000000000000000000000000000000..c3f6dd920e73ad1c3c88ae59ba445bc1db0a9eac
--- /dev/null
+++ b/Makefile.inc
@@ -0,0 +1,29 @@
+PROG=bech32
+MANSEC=1
+OBJS=	$(PROG).o \
+	segwit_addr.o
+
+manfmt: $(PROG).$(MANSEC).html $(PROG).$(MANSEC).md $(PROG).$(MANSEC).txt
+#manfmt: $(PROG).$(MANSEC).html $(PROG).$(MANSEC).txt
+
+$(PROG).$(MANSEC).html: $(PROG).$(MANSEC)
+	mandoc -I os=Bitcoin -T html $< > $@
+
+#Currently broken with message:
+#mandoc -I os=Bitcoin -T markdown easyseed.1 > easyseed.1.md
+#mandoc: mdoc_markdown.c:333: md_node: Assertion `n->tok >= MDOC_Dd && n->tok < MDOC_MAX' failed.
+$(PROG).$(MANSEC).md: $(PROG).$(MANSEC)
+	mandoc -I os=Bitcoin -T markdown $< > $@
+
+$(PROG).$(MANSEC).txt: $(PROG).$(MANSEC)
+	# XXX: Ridiculous kludge around make/shell quoting issues which
+	# prevent me from simply using sed expression $'s/[^\b]\b//g' :
+	mandoc -I os=Bitcoin -T utf8 $< | \
+		tr '\b' '^' | sed $(SEDRE) -e 's/[^^]\^//g' > $@
+
+clean:
+	rm -f $(PROG) $(OBJS) \
+		$(PROG).$(MANSEC).html $(PROG).$(MANSEC).md $(PROG).$(MANSEC).txt
+
+#check: $(PROG)
+#	./$(PROG) -T
diff --git a/Makefile.linux b/Makefile.linux
new file mode 100644
index 0000000000000000000000000000000000000000..cab98719647e8942c1ee21948ea0b24b0f72c661
--- /dev/null
+++ b/Makefile.linux
@@ -0,0 +1,14 @@
+CFLAGS+=-O2 -std=c99
+
+LDADD=
+
+all: bech32
+
+include Makefile.inc
+
+bech32: $(OBJS)
+	cc -o $@ $(OBJS) $(LDADD)
+
+install:
+	install $(PROG) /usr/local/bin
+	install $(PROG).$(MANSEC) /usr/local/man/man1
diff --git a/README.md b/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..dece5e343d9ccd95ffe534d0815b20e2bf39a7b1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,35 @@
+# The bech32(1) Utility
+
+## Encode and decode [Bech32 strings](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki), ![₿](img/bitcoin_32px.png) Bitcoin [“Bravo Charlie Addresses”](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-December/015477.html), Bech32 .onion addresses...
+
+- By nullius <[nullius@nym.zone](mailto:nullius@nym.zone)>
+- PGP: [0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C](https://sks-keyservers.net/pks/lookup?op=get&search=0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C)
+- Bitcoin, tips welcome: [3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG](bitcoin:3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG) (Segwit nested in P2SH), [bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h](bitcoin:bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h) (Segwit Bech32!).
+
+Wait, did I say .onion addresses?  Yes, I think that it’s a good idea to add Bech32’s error-correcting code.
+
+This utility’s actual encoding and decoding is done by [sipa’s Bech32 reference code](https://github.com/sipa/bech32/tree/master/ref/c), here included in tree.
+
+For details, [RTFM](./bech32.1.md).  Yes, it has a manpage.  Software is unworthy of release if it does not have a proper manpage.
+
+It has been tested on FreeBSD, my main platform, and on Linux.  [Unfortunately, I may have slightly mussed the BSD building while preparing for publication; this should soon be fixed.  The build system generally is still wonky.  This is an early release, with most attention paid to the source code and manpage!]
+
+License: AVL v0.0.1 with Bitcoin consensus clause.  I would prefer to disclaim copyright, and and release things to the public domain (*the public domain is not a license, “CC0” people*).  However, this is not an ideal world.
+
+## Installation
+
+FreeBSD:
+
+```
+make && make check
+```
+
+...then, `make install` as root (via `sudo` or otherwise).  Other BSDs are probably similar.
+
+Linux:
+
+```
+make -f Makefile.linux && \
+	make -f Makefile.linux check && \
+	sudo make -f Makefile.linux install
+```
diff --git a/bech32.1 b/bech32.1
new file mode 100644
index 0000000000000000000000000000000000000000..48221d6d6f4adc9e6697d3b307867ec09c955a9a
--- /dev/null
+++ b/bech32.1
@@ -0,0 +1,258 @@
+.\" By nullius 
+.\" PGP:	0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C
+.\" Bitcoin:	3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG
+.\"		bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h
+.\"
+.\" Copyright (c) 2017.  All rights reserved.
+.\"
+.\" The Antiviral License (AVL) v0.0.1, with added Bitcoin clause:
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of the source code must retain the above copyright
+.\"    and credit notices, this list of conditions, and the following
+.\"    disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\"    and credit notices, this list of conditions, and the following
+.\"    disclaimer in the documentation and/or other materials provided
+.\"    with the distribution.
+.\" 3. Derivative works hereof MUST NOT be redistributed under any license
+.\"    containing terms which require derivative works and/or usages to
+.\"    publish source code, viz. what is commonly known as a "copyleft"
+.\"    or "viral" license.
+.\" 4. Derivative works hereof which have any functionality related to
+.\"    digital money (so-called "cryptocurrency" MUST EITHER adhere to
+.\"    consensus rules fully compatible with Bitcoin Core, OR use a name
+.\"    which does not contain the word "Bitcoin".
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.Dd December 29, 2017
+.Dt BECH32 1
+.Os Bitcoin
+.Sh NAME
+.Nm bech32
+.Nd "Encode and decode Bech32 strings and Bitcoin Segwit addresses"
+.Sh SYNOPSIS
+General-purpose encoding and decoding:
+.Pp
+.Nm
+.Fl e
+.Fl h Ar hrp
+.Ar hexdata
+.Nm
+.Fl e
+.Fl 5
+.Fl h Ar hrp
+.Ar base32data
+.Nm
+.Fl d
+.Op Fl 5
+.Op Fl u
+.Ar bech32string
+.Pp
+For Bitcoin
+.Sy "Bravo Charlie"
+addresses
+.Pq Dq bc1 :
+.Pp
+.Nm
+.Fl s Ar witver
+.Ar hexdata
+.Nm
+.Fl S
+.Ar bc1addr
+.Pp
+For .onion domains:
+.Pp
+.Nm
+.Fl e
+.Ar base32domain.onion
+.Nm
+.Fl d
+.Ar onion1bech32
+.Sh DESCRIPTION
+The
+.Nm
+utility is a powerful general-purpose tool for encoding and decoding
+of BIP 173 standard Bech32 strings and Bitcoin Bech32 addresses.
+.Pp
+Hexadecimal data may be input with or without a leading
+.Dq 0x
+prefix.
+It is output with such a prefix, to prevent ambiguity.
+.Pp
+It has the following modes, some of which overlap:
+.Bl -tag -width ".Fl d Ar argument"
+.It Fl e
+Encoder mode.
+Output is a Bech32 string.
+.It Fl d
+Decoder mode.
+Output is the input string
+.Ap
+s human-readable part
+.Pq HRP ,
+followed by a delimiting colon
+.Pq Dq ":" ,
+followed by the
+.Dq "data part"
+data in hexadecimal with a
+.Dq 0x
+prefix.
+.It Fl s Ar witver
+Encode a Bitcoin Segwit address with witness version
+.Ar witver .
+.It Fl S
+Decode a Bitcoin Segwit address.
+Output its witness version in
+.Em decimal
+.Pq "0\(en16 inclusive" ,
+followed by a delimiting colon
+.Pq Dq ":" ,
+followed by the address data in
+.Em hexadecimal
+with a
+.Dq 0x
+prefix.
+.It Pq ".onion autodetect"
+Dot-onion mode.
+When encoding,
+.Nm
+will automatically detect a dot-onion domain and read its second level
+as RFC 4648 Base32 data.
+When decoding,
+.Nm
+will detect a
+.Dq onion
+HRP, and output a dot-onion domain.
+.El
+.Pp
+The options are as follows:
+.Bl -tag -width ".Fl d Ar argument"
+.It Fl h Ar hrp
+General encoding only, and required therefor.
+Provide the Human-Readable Portion
+.Pq HRP
+for the Bech32 string.
+.It Fl 5
+Read RFC 4648 Base32 data when encoding, or write RFC 4648 Base32 data
+when decoding.
+.It Fl u
+.Pq "Decoding only."
+.\" XXX: What about Base32?
+Output hexadecimal characters in uppercase.
+.El
+.Sh EXIT STATUS
+.Ex -std
+.Sh EXAMPLES
+Extract the witness version and Hash160 from the
+.Nm
+utility author
+.Ap
+s Bech32 tip address:
+.Pp
+.Dl bech32 -S bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h
+.Dl 0:0xc76172ea149002114027b90f0759084f93aea326
+.Pp
+Get a
+.Dq "hello, world"
+introduction to Bech32:
+.Pp
+.Dl bech32 -e -h hello_world 48656c6c6f2c20776f726c6421
+.Dl hello_world1fpjkcmr09ss8wmmjd3jzzwhs4ff
+.Pp
+Generate a
+.Dq "burn address"
+with a Hash160 of all zeroes, which would be spendable by the same unknown
+private keys as the infamous 1111111111111111111114oLvT2.
+.Sy "Warning:  Do NOT send coins here:"
+.Pp
+.Dl bech32 -s 0 0x0000000000000000000000000000000000000000
+.Dl bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq9e75rs
+.Pp
+Bech32-encode the address for Wikileaks, to add error-correcting codes:
+.Pp
+.Dl bech32 -e wlupld3ptjvsgwqw.onion
+.Dl onion1kt50trm0nf4jxkskpcjy74
+.Pp
+Now, decode the address someone gave you:
+.Pp
+.Dl bech32 -d onion1kt50trm0nf4jxkskpcjy74
+.Dl wlupld3ptjvsgwqw.onion
+.Sh STANDARDS
+The
+.Nm
+utility conforms to Bitcoin
+.Lk https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki "BIP 173" ,
+the Bech32 standard.
+.Pp
+It also conforms to
+.Lk https://tools.ietf.org/html/rfc4648 "RFC 4648"
+for transcoding to Base32.
+.Pp
+The term
+.Dq Sy "Bravo Charlie Address"
+and the motto
+.Dq Sy "Bravo Charlie One means money"
+are from a
+.Lk https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-December/015477.html "proposal by this author" .
+.Sh AUTHORS
+The
+.Nm
+utility was written by
+.An nullius
+.Aq Mt nullius@nym.zone .
+.Pp
+PGP:
+.Li 0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C
+.Pp
+Tips:
+.Lk bitcoin:3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG 3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG ,
+.Lk bitcoin:bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h .
+.Pp
+The internal Bech32 encoding and decoding is done by the open-source
+.Lk https://github.com/sipa/bech32/tree/master/ref/c "Bech32 reference code"
+written by Pieter Wuille
+.Pq sipa
+.Pq "no affiliation with this author" .
+.Sh BUGS
+This code started as a quickly-made utility for personal use, and kept
+growing as such things are wont to do.
+The user interface is reasonably logical, given the tool
+.Ap
+s flexibility.
+However, the source code needs some substantial refactoring.
+.Pp
+This manpage could use more and better examples, plus some other general
+editing.
+.Pp
+Test cases are needed.
+Unfortunately, the Bech32 standard does not currently provide full roundtrip
+test vectors for arbitrary Bech32 strings.
+.Pp
+Special support is planned for a concept which this author calls
+.Dq Sy "PGP Descriptors" .
+However, a spec must be drawn before releasing such a thing into the wild.
+.Sh SECURITY CONSIDERATIONS
+This is an early release, which should be considered alpha-quality software.
+It
+.Sy should not
+be used on untrusted inputs, such as anything blindly accepted by a webserver.
+High on the author
+.Ap
+s TODO list is to beef up input validation.
+At this time, aside from a few simple checks, the utility will happily
+pass the buck to the Bech32 reference functions.
diff --git a/bech32.1.html b/bech32.1.html
new file mode 100644
index 0000000000000000000000000000000000000000..5d7446bbc8b4e884c53d0a58cc54bffb0bb60906
--- /dev/null
+++ b/bech32.1.html
@@ -0,0 +1,237 @@
+
+
+
+  
+  
+  BECH32(1)
+
+
+
+  
+    
+    
+    
+  
+
BECH32(1)General Commands ManualBECH32(1)
+
+

NAME

+bech32Encode + and decode Bech32 strings and Bitcoin Segwit addresses +

SYNOPSIS

+General-purpose encoding and decoding: +
+
+ + + + + +
bech32-e -h + hrp + hexdata
+
+ + + + + +
bech32-e -5 + -h hrp + base32data
+
+ + + + + +
bech32-d + [-5] + [-u] + bech32string +
+ For Bitcoin Bravo Charlie addresses + (“bc1”):
+
+
+ + + + + +
bech32-s witver + hexdata
+
+ + + + + +
bech32-S bc1addr +
+ For .onion domains:
+
+
+ + + + + +
bech32-e + base32domain.onion
+
+ + + + + +
bech32-d + onion1bech32
+

DESCRIPTION

+The bech32 utility is a powerful general-purpose + tool for encoding and decoding of BIP 173 standard Bech32 strings and Bitcoin + Bech32 addresses. +
+Hexadecimal data may be input with or without a leading “0x” + prefix. It is output with such a prefix, to prevent ambiguity. +
+It has the following modes, some of which overlap: +
+
-e
+
Encoder mode. Output is a Bech32 string.
+
-d
+
Decoder mode. Output is the input string's human-readable + part (HRP), followed by a delimiting colon (“:”), followed + by the “data part” data in hexadecimal with a + “0x” prefix.
+
-s + witver
+
Encode a Bitcoin Segwit address with witness version + witver.
+
-S
+
Decode a Bitcoin Segwit address. Output its witness version + in decimal (0–16 inclusive), followed + by a delimiting colon (“:”), followed by the address data in + hexadecimal with a “0x” + prefix.
+
(.onion autodetect)
+
Dot-onion mode. When encoding, + bech32 will automatically detect a dot-onion + domain and read its second level as RFC 4648 Base32 data. When decoding, + bech32 will detect a “onion” + HRP, and output a dot-onion domain.
+
+
+The options are as follows: +
+
-h + hrp
+
General encoding only, and required therefor. Provide the + Human-Readable Portion (HRP) for the Bech32 string.
+
-5
+
Read RFC 4648 Base32 data when encoding, or write RFC 4648 + Base32 data when decoding.
+
-u
+
(Decoding only.) Output hexadecimal characters in + uppercase.
+
+

EXIT + STATUS

+The bech32 utility exits 0 on success, + and >0 if an error occurs. +

EXAMPLES

+Extract the witness version and Hash160 from the + bech32 utility author's Bech32 tip address: +
+
bech32 -S + bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h
+
0:0xc76172ea149002114027b90f0759084f93aea326
+
+Get a “hello, world” introduction to Bech32: +
+
bech32 -e -h hello_world + 48656c6c6f2c20776f726c6421
+
hello_world1fpjkcmr09ss8wmmjd3jzzwhs4ff
+
+Generate a “burn address” with a Hash160 of all zeroes, which + would be spendable by the same unknown private keys as the infamous + 1111111111111111111114oLvT2. Warning: Do NOT send + coins here: +
+
bech32 -s 0 + 0x0000000000000000000000000000000000000000
+
bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq9e75rs
+
+Bech32-encode the address for Wikileaks, to add error-correcting codes: +
+
bech32 -e wlupld3ptjvsgwqw.onion
+
onion1kt50trm0nf4jxkskpcjy74
+
+Now, decode the address someone gave you: +
+
bech32 -d + onion1kt50trm0nf4jxkskpcjy74
+
wlupld3ptjvsgwqw.onion
+

STANDARDS

+The bech32 utility conforms to Bitcoin + BIP + 173, the Bech32 standard. +
+It also conforms to + RFC + 4648 for transcoding to Base32. +
+The term “Bravo Charlie Address” and + the motto “Bravo Charlie One means + money” are from a + proposal + by this author. +

AUTHORS

+The bech32 utility was written by + nullius + <nullius@nym.zone>. +
+PGP: 0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C +
+Tips: + 3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG, + bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h. +
+The internal Bech32 encoding and decoding is done by the open-source + Bech32 + reference code written by Pieter Wuille (sipa) (no affiliation with this + author). +

BUGS

+This code started as a quickly-made utility for personal use, and kept growing + as such things are wont to do. The user interface is reasonably logical, given + the tool's flexibility. However, the source code needs some substantial + refactoring. +
+This manpage could use more and better examples, plus some other general + editing. +
+Test cases are needed. Unfortunately, the Bech32 standard does not currently + provide full roundtrip test vectors for arbitrary Bech32 strings. +
+Special support is planned for a concept which this author calls + “PGP Descriptors”. However, a spec + must be drawn before releasing such a thing into the wild. +

SECURITY + CONSIDERATIONS

+This is an early release, which should be considered alpha-quality software. It + should not be used on untrusted inputs, such as + anything blindly accepted by a webserver. High on the author's TODO list is to + beef up input validation. At this time, aside from a few simple checks, the + utility will happily pass the buck to the Bech32 reference functions.
+ + + + + +
December 29, 2017Bitcoin
+ + diff --git a/bech32.1.md b/bech32.1.md new file mode 100644 index 0000000000000000000000000000000000000000..e911306d4f6e36fcbd2c5a9ff2cc23150832e98b --- /dev/null +++ b/bech32.1.md @@ -0,0 +1,246 @@ +BECH32(1) - General Commands Manual + +# NAME + +**bech32** - Encode and decode Bech32 strings and Bitcoin Segwit addresses + +# SYNOPSIS + +General-purpose encoding and decoding: + +**bech32** +**-e** +**-h** *hrp* +*hexdata* +**bech32** +**-e** +**-5** +**-h** *hrp* +*base32data* +**bech32** +**-d** +\[**-5**] +\[**-u**] +*bech32string* + +For Bitcoin +**Bravo Charlie** +addresses +("bc1"): + +**bech32** +**-s** *witver* +*hexdata* +**bech32** +**-S** +*bc1addr* + +For .onion domains: + +**bech32** +**-e** +*base32domain.onion* +**bech32** +**-d** +*onion1bech32* + +# DESCRIPTION + +The +**bech32** +utility is a powerful general-purpose tool for encoding and decoding +of BIP 173 standard Bech32 strings and Bitcoin Bech32 addresses. + +Hexadecimal data may be input with or without a leading +"0x" +prefix. +It is output with such a prefix, to prevent ambiguity. + +It has the following modes, some of which overlap: + +**-e** + +> Encoder mode. +> Output is a Bech32 string. + +**-d** + +> Decoder mode. +> Output is the input string +> 's human-readable part +> (HRP), +> followed by a delimiting colon +> (":"), +> followed by the +> "data part" +> data in hexadecimal with a +> "0x" +> prefix. + +**-s** *witver* + +> Encode a Bitcoin Segwit address with witness version +> *witver*. + +**-S** + +> Decode a Bitcoin Segwit address. +> Output its witness version in +> *decimal* +> (0–16 inclusive), +> followed by a delimiting colon +> (":"), +> followed by the address data in +> *hexadecimal* +> with a +> "0x" +> prefix. + +(.onion autodetect) + +> Dot-onion mode. +> When encoding, +> **bech32** +> will automatically detect a dot-onion domain and read its second level +> as RFC 4648 Base32 data. +> When decoding, +> **bech32** +> will detect a +> "onion" +> HRP, and output a dot-onion domain. + +The options are as follows: + +**-h** *hrp* + +> General encoding only, and required therefor. +> Provide the Human-Readable Portion +> (HRP) +> for the Bech32 string. + +**-5** + +> Read RFC 4648 Base32 data when encoding, or write RFC 4648 Base32 data +> when decoding. + +**-u** + +> (Decoding only.) +> Output hexadecimal characters in uppercase. + +# EXIT STATUS + +The **bech32** utility exits 0 on success, and >0 if an error occurs. + +# EXAMPLES + +Extract the witness version and Hash160 from the +**bech32** +utility author +'s Bech32 tip address: + + bech32 -S bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h + + 0:0xc76172ea149002114027b90f0759084f93aea326 + +Get a +"hello, world" +introduction to Bech32: + + bech32 -e -h hello_world 48656c6c6f2c20776f726c6421 + + hello_world1fpjkcmr09ss8wmmjd3jzzwhs4ff + +Generate a +"burn address" +with a Hash160 of all zeroes, which would be spendable by the same unknown +private keys as the infamous 1111111111111111111114oLvT2. +**Warning: Do NOT send coins here:** + + bech32 -s 0 0x0000000000000000000000000000000000000000 + + bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq9e75rs + +Bech32-encode the address for Wikileaks, to add error-correcting codes: + + bech32 -e wlupld3ptjvsgwqw.onion + + onion1kt50trm0nf4jxkskpcjy74 + +Now, decode the address someone gave you: + + bech32 -d onion1kt50trm0nf4jxkskpcjy74 + + wlupld3ptjvsgwqw.onion + +# STANDARDS + +The +**bech32** +utility conforms to Bitcoin +[BIP 173](https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki), +the Bech32 standard. + +It also conforms to +[RFC 4648](https://tools.ietf.org/html/rfc4648) +for transcoding to Base32. + +The term +"**Bravo Charlie Address**" +and the motto +"**Bravo Charlie One means money**" +are from a +[proposal by this author](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-December/015477.html). + +# AUTHORS + +The +**bech32** +utility was written by +nullius +<[nullius@nym.zone](mailto:nullius@nym.zone)>. + +PGP: +`0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C` + +Tips: +[3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG](bitcoin:3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG), +[bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h](bitcoin:bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h). + +The internal Bech32 encoding and decoding is done by the open-source +[Bech32 reference code](https://github.com/sipa/bech32/tree/master/ref/c) +written by Pieter Wuille +(sipa) +(no affiliation with this author). + +# BUGS + +This code started as a quickly-made utility for personal use, and kept +growing as such things are wont to do. +The user interface is reasonably logical, given the tool +'s flexibility. +However, the source code needs some substantial refactoring. + +This manpage could use more and better examples, plus some other general +editing. + +Test cases are needed. +Unfortunately, the Bech32 standard does not currently provide full roundtrip +test vectors for arbitrary Bech32 strings. + +Special support is planned for a concept which this author calls +"**PGP Descriptors**". +However, a spec must be drawn before releasing such a thing into the wild. + +# SECURITY CONSIDERATIONS + +This is an early release, which should be considered alpha-quality software. +It +**should not** +be used on untrusted inputs, such as anything blindly accepted by a webserver. +High on the author +'s TODO list is to beef up input validation. +At this time, aside from a few simple checks, the utility will happily +pass the buck to the Bech32 reference functions. + +Bitcoin - December 29, 2017 diff --git a/bech32.1.txt b/bech32.1.txt new file mode 100644 index 0000000000000000000000000000000000000000..ab93f27cc7e8a44d5ce1779943c328966bd57687 --- /dev/null +++ b/bech32.1.txt @@ -0,0 +1,150 @@ +BECH32(1) General Commands Manual BECH32(1) + +NAME + bech32 – Encode and decode Bech32 strings and Bitcoin Segwit addresses + +SYNOPSIS + General-purpose encoding and decoding: + + bech32 -e -h hrp hexdata + bech32 -e -5 -h hrp base32data + bech32 -d [-5] [-u] bech32string + + For Bitcoin Bravo Charlie addresses (“bc1”): + + bech32 -s witver hexdata + bech32 -S bc1addr + + For .onion domains: + + bech32 -e base32domain.onion + bech32 -d onion1bech32 + +DESCRIPTION + The bech32 utility is a powerful general-purpose tool for encoding and + decoding of BIP 173 standard Bech32 strings and Bitcoin Bech32 addresses. + + Hexadecimal data may be input with or without a leading “0x” prefix. It + is output with such a prefix, to prevent ambiguity. + + It has the following modes, some of which overlap: + + -e Encoder mode. Output is a Bech32 string. + + -d Decoder mode. Output is the input string's human- + readable part (HRP), followed by a delimiting colon + (“:”), followed by the “data part” data in hexadecimal + with a “0x” prefix. + + -s witver Encode a Bitcoin Segwit address with witness version + witver. + + -S Decode a Bitcoin Segwit address. Output its witness + version in decimal (0–16 inclusive), followed by a + delimiting colon (“:”), followed by the address data + in hexadecimal with a “0x” prefix. + + (.onion autodetect) + Dot-onion mode. When encoding, bech32 will + automatically detect a dot-onion domain and read its + second level as RFC 4648 Base32 data. When decoding, + bech32 will detect a “onion” HRP, and output a dot- + onion domain. + + The options are as follows: + + -h hrp General encoding only, and required therefor. Provide + the Human-Readable Portion (HRP) for the Bech32 + string. + + -5 Read RFC 4648 Base32 data when encoding, or write RFC + 4648 Base32 data when decoding. + + -u (Decoding only.) Output hexadecimal characters in + uppercase. + +EXIT STATUS + The bech32 utility exits 0 on success, and >0 if an error occurs. + +EXAMPLES + Extract the witness version and Hash160 from the bech32 utility author's + Bech32 tip address: + + bech32 -S bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h + 0:0xc76172ea149002114027b90f0759084f93aea326 + + Get a “hello, world” introduction to Bech32: + + bech32 -e -h hello_world 48656c6c6f2c20776f726c6421 + hello_world1fpjkcmr09ss8wmmjd3jzzwhs4ff + + Generate a “burn address” with a Hash160 of all zeroes, which would be + spendable by the same unknown private keys as the infamous + 1111111111111111111114oLvT2. Warning: Do NOT send coins here: + + bech32 -s 0 0x0000000000000000000000000000000000000000 + bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq9e75rs + + Bech32-encode the address for Wikileaks, to add error-correcting codes: + + bech32 -e wlupld3ptjvsgwqw.onion + onion1kt50trm0nf4jxkskpcjy74 + + Now, decode the address someone gave you: + + bech32 -d onion1kt50trm0nf4jxkskpcjy74 + wlupld3ptjvsgwqw.onion + +STANDARDS + The bech32 utility conforms to Bitcoin BIP 173: + https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki, + the Bech32 standard. + + It also conforms to RFC 4648: + https://tools.ietf.org/html/rfc4648 + for transcoding to Base32. + + The term “Bravo Charlie Address” and the motto “Bravo Charlie One means + money” are from a proposal by this author: + https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2017-December/015477.html. + +AUTHORS + The bech32 utility was written by nullius . + + PGP: 0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C + + Tips: 3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG: + bitcoin:3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG, + bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h: + bitcoin:bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h. + + The internal Bech32 encoding and decoding is done by the open-source + Bech32 reference code: + https://github.com/sipa/bech32/tree/master/ref/c + written by Pieter Wuille (sipa) (no affiliation with this author). + +BUGS + This code started as a quickly-made utility for personal use, and kept + growing as such things are wont to do. The user interface is reasonably + logical, given the tool's flexibility. However, the source code needs + some substantial refactoring. + + This manpage could use more and better examples, plus some other general + editing. + + Test cases are needed. Unfortunately, the Bech32 standard does not + currently provide full roundtrip test vectors for arbitrary Bech32 + strings. + + Special support is planned for a concept which this author calls “PGP + Descriptors”. However, a spec must be drawn before releasing such a + thing into the wild. + +SECURITY CONSIDERATIONS + This is an early release, which should be considered alpha-quality + software. It should not be used on untrusted inputs, such as anything + blindly accepted by a webserver. High on the author's TODO list is to + beef up input validation. At this time, aside from a few simple checks, + the utility will happily pass the buck to the Bech32 reference functions. + +Bitcoin December 29, 2017 Bitcoin diff --git a/bech32.c b/bech32.c new file mode 100644 index 0000000000000000000000000000000000000000..5c50f5298b2e2d2bd73e335a76da731b9318da5d --- /dev/null +++ b/bech32.c @@ -0,0 +1,387 @@ +/** + * By nullius + * PGP: 0xC2E91CD74A4C57A105F6C21B5A00591B2F307E0C + * Bitcoin: 3NULL3ZCUXr7RDLxXeLPDMZDZYxuaYkCnG + * bc1qcash96s5jqppzsp8hy8swkggf7f6agex98an7h + * + * Copyright (c) 2017. All rights reserved. + * + * The Antiviral License (AVL) v0.0.1, with added Bitcoin clause: + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of the source code must retain the above copyright + * and credit notices, this list of conditions, and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * and credit notices, this list of conditions, and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * 3. Derivative works hereof MUST NOT be redistributed under any license + * containing terms which require derivative works and/or usages to + * publish source code, viz. what is commonly known as a "copyleft" + * or "viral" license. + * 4. Derivative works hereof which have any functionality related to + * digital money (so-called "cryptocurrency" MUST EITHER adhere to + * consensus rules fully compatible with Bitcoin Core, OR use a name + * which does not contain the word "Bitcoin". + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#ifdef __linux__ +#define _POSIX_C_SOURCE 200809L +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "segwit_addr.h" + +#define MODE_DECODE 0 +#define MODE_ENCODE 1 +#define MODE_SEGWIT_DECODE 2 +#define MODE_SEGWIT_ENCODE 3 +#define MODE_ONION_DECODE 0x00012000 +#define MODE_ONION_ENCODE 0x00013000 +#define IO_HEX 0x10 +#define IO_RFC4648 0x20 + +static ssize_t +hexdec(unsigned char *data, size_t len, const char *hexdata, size_t hexdata_len) +{ + ssize_t data_len = 0; + + if (len < hexdata_len / 2 || (hexdata_len & 1)) + return (-1); + + for (size_t i = 0, j = 0; i < hexdata_len; i+=2, ++j) { +#ifdef notyet + /* For copypaste of old-style PGP fingerprint display, etc. */ + Unfortunately, this musses the length checks in main() and + the loop counting here. General concept: + + if (isblank(hexdata[i])) + continue; +#endif + if (hexdata[i] >= '0' && hexdata[i] <= '9') + data[j] = (hexdata[i] - '0') << 4; + else if (hexdata[i] >= 'A' && hexdata[i] <= 'F') + data[j] = (hexdata[i] - ('A' - 0xa)) << 4; + else if (hexdata[i] >= 'a' && hexdata[i] <= 'f') + data[j] = (hexdata[i] - ('a' - 0xa)) << 4; + else + return (-1); + + if (hexdata[i+1] >= '0' && hexdata[i+1] <= '9') + data[j] |= hexdata[i+1] - '0'; + else if (hexdata[i+1] >= 'A' && hexdata[i+1] <= 'F') + data[j] |= hexdata[i+1] - ('A' - 0xa); + else if (hexdata[i+1] >= 'a' && hexdata[i+1] <= 'f') + data[j] |= hexdata[i+1] - ('a' - 0xa); + else + return (-1); + + ++data_len; + } + + return (data_len); +} + +ssize_t +hexenc(char *hd, size_t buflen, const unsigned char *data, size_t datalen, int cs) +{ + const char hex[2][16] = { "0123456789abcdef", "0123456789ABCDEF" }; + ssize_t hexlen = 0; + + if (buflen < datalen * 2 + 1) + return (-1); + + cs = !!cs; + + for (int i = 0; i < datalen; ++i) { + *hd++ = hex[cs][data[i] >> 4]; + *hd++ = hex[cs][data[i] & 0xf]; + hexlen += 2; + } + *hd = '\0'; + + return (hexlen); +} + +static ssize_t +b32enc(unsigned char *b32, size_t b32buflen, const unsigned char *data, size_t datalen) +{ + unsigned bits = 0, b32char = 0; + ssize_t b32data_len = 0; + + if (b32buflen < (datalen * 8 / 5 + !!(datalen * 8 % 5))) + return (-1); + + do { + b32char <<= 8, b32char |= *data++, bits += 8; + + while (bits >= 5) { + *b32++ = (b32char >> (bits - 5)), ++b32data_len; + b32char &= ~(0x1f << (bits -= 5)); + } + } while (--datalen > 0); + + assert(bits < 5); + if (bits > 0) + *b32 = b32char << (5 - bits), ++b32data_len; + + return (b32data_len); +} + +static ssize_t +b32dec(unsigned char *data, size_t buflen, const unsigned char *b32data, size_t b32datalen) +{ + unsigned bits = 0, u8char = 0; + ssize_t datalen = 0; + + do { + if (*b32data > 0x1f) + return (-1); + + u8char <<= 5, u8char |= *b32data++, bits += 5; + while (bits >= 8) { + *data++ = u8char >> (bits - 8), ++datalen; + u8char &= ~(0xff << (bits -= 8)); + } + } while (--b32datalen > 0); + assert(bits <= 8); /* Guaranteed by logic. */ + if (bits > 4 || u8char != 0) /* Invalid per the specification. */ + return (-1); + + return (datalen); +} + +static ssize_t +rfcb32enc(char *b32, const unsigned char *data, size_t datalen) +{ + const char alphabet[32] = "abcdefghijklmnopqrstuvwxyz234567"; + ssize_t len = 0; + + while (datalen > 0) { + if (*data > 31) + return (-1); + *b32++ = alphabet[*data++], --datalen, ++len; + } + *b32 = '\0'; +} + +static ssize_t +rfcb32dec(unsigned char *data, size_t buflen, const char *b32, size_t b32len) +{ + ssize_t datalen = 0; + + while (b32len > 0) { + if (*b32 >= 'a' && *b32 <= 'z') + *data = *b32 - 'a'; + else if (*b32 >= 'A' && *b32 <= 'Z') + *data = *b32 - 'A'; + else if (*b32 >= '2' && *b32 <= '7') + *data = *b32 - ('2' - 26); + else + return (-1); + + ++b32, ++data, ++datalen, --b32len; + } + + return (datalen); +} + +int +main(int argc, char *argv[]) +{ + int ch, error, mode = -1, b32mode = 8, hexcase = 0; + long witver = -1; + const char *hrp = NULL, *hexdata = NULL, *bechdata = NULL, *cur; + char bech32[256], codehrp[84], *str = bech32, *endptr; + unsigned char data[80], b32data[128], *b32cur = b32data; + ssize_t hrp_len, data_len = 0, b32data_len = 0, hexdata_len; + + while ((ch = getopt(argc, argv, "58Sdeh:s:u")) > -1) { + switch (ch) { + case '5': + b32mode = 5; + break; + case '8': /* default */ + b32mode = 8; + break; + case 'S': + mode = MODE_SEGWIT_DECODE; + break; + case 'd': + mode = MODE_DECODE; + break; + case 'e': + mode = MODE_ENCODE; + break; + case 'h': + hrp = optarg; + break; + case 's': + mode = MODE_SEGWIT_ENCODE; + errno = 0; + witver = strtol(optarg, &endptr, 10); + if (witver < 0 || witver > 16 || + *endptr != '\0' || errno != 0) + witver = -2; + break; + case 'u': + hexcase = 1; + break; + default: + errx(1, "Bad option"); + } + } + argc -= optind, argv += optind; + + if (*argv == NULL || *(argv+1) != NULL) + errx(1, "Wrong options"); + + if (witver == -2) + errx(1, "Invalid witness version provided with -s"); + + if (witver != -1 && hrp != NULL) + errx(1, "-h hrp is automatically set by -s option"); + + if (witver != -1 && mode != MODE_SEGWIT_ENCODE) + errx(1, "Mode conflict"); + + switch (mode) { + case MODE_ENCODE: + if ((cur = strchr(*argv, '.')) != NULL) { + if (strcmp(cur, ".onion") != 0) + errx(1, "Bad encoding string"); + hrp = "onion"; + hrp_len = strlen(hrp); + hexdata = *argv; + hexdata_len = cur - *argv; + b32mode = 5; + mode = MODE_ONION_ENCODE; + goto onion_encode; + } else { + if (hrp == NULL) + errx(1, "HRP needed (-h hrp)"); + hrp_len = strlen(hrp); + if (hrp_len < 1 || hrp_len > 83) + errx(1, "Bad HRP length"); + } + + /* FALLTHRUOGH */ + case MODE_SEGWIT_ENCODE: + hexdata = *argv; + hexdata_len = strlen(hexdata); + if (hexdata_len < 6 || (hexdata_len & 1)) + errx(1, "Bad hex data length"); + + if (strncmp(hexdata, "0x", 2) == 0) { + hexdata += 2, hexdata_len -= 2; + if (hexdata_len < 6) + errx(1, "Bad hex data length"); + } + + /* XXX: This leaves the real check to bech32_encode(). */ + if (hexdata_len > sizeof(data) * 2) + errx(1, "Bad hex data length"); + + if (mode == MODE_SEGWIT_ENCODE) + goto segwit_encode; + +onion_encode: + if (b32mode == 5) { + b32data_len = rfcb32dec(b32data, sizeof(b32data), hexdata, hexdata_len); + if (b32data_len < 0) + errx(1, "Bad base32 data"); + } else { + data_len = hexdec(data, sizeof(data), hexdata, hexdata_len); + if (data_len < 0) + errx(1, "Bad hex data"); + + b32data_len = b32enc(b32data, sizeof(b32data), data, data_len); + if (b32data_len < 0) + errx(1, "base32 encoding failed"); + } + + error = bech32_encode(bech32, hrp, b32data, b32data_len); + if (error != 1) + errx(1, "bech32_encode() failed (data_len: %ju)", + (intmax_t)data_len); + + printf("%s\n", bech32); + break; +segwit_encode: + data_len = hexdec(data, sizeof(data), hexdata, hexdata_len); + if (data_len < 0) + errx(1, "Bad hex data"); +fprintf(stderr, "data_len: %jd\n", (intmax_t)data_len); + error = segwit_addr_encode(bech32, "bc", witver, data, data_len); + if (error != 1) + errx(1, "segwit_addr_encode() failed"); + + printf("%s\n", bech32); + break; + case MODE_DECODE: + error = bech32_decode(codehrp, b32data, &b32data_len, *argv); + if (error != 1) + errx(1, "bech32_decode() failed"); + + if (!strcmp(codehrp, "onion")) + b32mode = 5, mode = MODE_ONION_DECODE; + + if (b32mode == 5) { + rfcb32enc(str, b32data, b32data_len); + if (mode == MODE_ONION_DECODE) + printf("%s.onion\n", str); + else + printf("%s:%s\n", codehrp, str); + } else { + data_len = b32dec(data, sizeof(data), b32data, b32data_len); + hexenc(str, sizeof(bech32), data, data_len, hexcase); + + printf("%s:0x%s\n", codehrp, str); + } + break; + case MODE_SEGWIT_DECODE: { + int ver; + + error = segwit_addr_decode(&ver, data, &data_len, "bc", *argv); + if (error != 1) + errx(1, "segwit_addr_decode() failed"); + + hexenc(str, sizeof(bech32), data, data_len, hexcase); + + printf("%d:0x%s\n", ver, str); + + break; + } + default: + errx(1, "Mode not set (encode or decode)"); + } + + return (0); +} diff --git a/img/bitcoin_32px.png b/img/bitcoin_32px.png new file mode 100644 index 0000000000000000000000000000000000000000..b2c8c8f3e89bdfed906f188fa3d96cca3fbcef4b Binary files /dev/null and b/img/bitcoin_32px.png differ diff --git a/segwit_addr.c b/segwit_addr.c new file mode 100644 index 0000000000000000000000000000000000000000..8202d841816c392060edaa141cd9ee5674e117ae --- /dev/null +++ b/segwit_addr.c @@ -0,0 +1,191 @@ +/* Copyright (c) 2017 Pieter Wuille + * + * 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. + * + * 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. + */ +#include +#include +#include + +#include "segwit_addr.h" + +uint32_t bech32_polymod_step(uint32_t pre) { + uint8_t b = pre >> 25; + return ((pre & 0x1FFFFFF) << 5) ^ + (-((b >> 0) & 1) & 0x3b6a57b2UL) ^ + (-((b >> 1) & 1) & 0x26508e6dUL) ^ + (-((b >> 2) & 1) & 0x1ea119faUL) ^ + (-((b >> 3) & 1) & 0x3d4233ddUL) ^ + (-((b >> 4) & 1) & 0x2a1462b3UL); +} + +static const char* charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; + +static const int8_t charset_rev[128] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, + -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, + 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, + -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, + 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 +}; + +int bech32_encode(char *output, const char *hrp, const uint8_t *data, size_t data_len) { + uint32_t chk = 1; + size_t i = 0; + while (hrp[i] != 0) { + int ch = hrp[i]; + if (ch < 33 || ch > 126) { + return 0; + } + + if (ch >= 'A' && ch <= 'Z') return 0; + chk = bech32_polymod_step(chk) ^ (ch >> 5); + ++i; + } + if (i + 7 + data_len > 90) return 0; + chk = bech32_polymod_step(chk); + while (*hrp != 0) { + chk = bech32_polymod_step(chk) ^ (*hrp & 0x1f); + *(output++) = *(hrp++); + } + *(output++) = '1'; + for (i = 0; i < data_len; ++i) { + if (*data >> 5) return 0; + chk = bech32_polymod_step(chk) ^ (*data); + *(output++) = charset[*(data++)]; + } + for (i = 0; i < 6; ++i) { + chk = bech32_polymod_step(chk); + } + chk ^= 1; + for (i = 0; i < 6; ++i) { + *(output++) = charset[(chk >> ((5 - i) * 5)) & 0x1f]; + } + *output = 0; + return 1; +} + +int bech32_decode(char* hrp, uint8_t *data, size_t *data_len, const char *input) { + uint32_t chk = 1; + size_t i; + size_t input_len = strlen(input); + size_t hrp_len; + int have_lower = 0, have_upper = 0; + if (input_len < 8 || input_len > 90) { + return 0; + } + *data_len = 0; + while (*data_len < input_len && input[(input_len - 1) - *data_len] != '1') { + ++(*data_len); + } + hrp_len = input_len - (1 + *data_len); + if (hrp_len < 1 || *data_len < 6) { + return 0; + } + *(data_len) -= 6; + for (i = 0; i < hrp_len; ++i) { + int ch = input[i]; + if (ch < 33 || ch > 126) { + return 0; + } + if (ch >= 'a' && ch <= 'z') { + have_lower = 1; + } else if (ch >= 'A' && ch <= 'Z') { + have_upper = 1; + ch = (ch - 'A') + 'a'; + } + hrp[i] = ch; + chk = bech32_polymod_step(chk) ^ (ch >> 5); + } + hrp[i] = 0; + chk = bech32_polymod_step(chk); + for (i = 0; i < hrp_len; ++i) { + chk = bech32_polymod_step(chk) ^ (input[i] & 0x1f); + } + ++i; + while (i < input_len) { + int v = (input[i] & 0x80) ? -1 : charset_rev[(int)input[i]]; + if (input[i] >= 'a' && input[i] <= 'z') have_lower = 1; + if (input[i] >= 'A' && input[i] <= 'Z') have_upper = 1; + if (v == -1) { + return 0; + } + chk = bech32_polymod_step(chk) ^ v; + if (i + 6 < input_len) { + data[i - (1 + hrp_len)] = v; + } + ++i; + } + if (have_lower && have_upper) { + return 0; + } + return chk == 1; +} + +static int convert_bits(uint8_t* out, size_t* outlen, int outbits, const uint8_t* in, size_t inlen, int inbits, int pad) { + uint32_t val = 0; + int bits = 0; + uint32_t maxv = (((uint32_t)1) << outbits) - 1; + while (inlen--) { + val = (val << inbits) | *(in++); + bits += inbits; + while (bits >= outbits) { + bits -= outbits; + out[(*outlen)++] = (val >> bits) & maxv; + } + } + if (pad) { + if (bits) { + out[(*outlen)++] = (val << (outbits - bits)) & maxv; + } + } else if (((val << (outbits - bits)) & maxv) || bits >= inbits) { + return 0; + } + return 1; +} + +int segwit_addr_encode(char *output, const char *hrp, int witver, const uint8_t *witprog, size_t witprog_len) { + uint8_t data[65]; + size_t datalen = 0; + if (witver > 16) return 0; + if (witver == 0 && witprog_len != 20 && witprog_len != 32) return 0; + if (witprog_len < 2 || witprog_len > 40) return 0; + data[0] = witver; + convert_bits(data + 1, &datalen, 5, witprog, witprog_len, 8, 1); + ++datalen; + return bech32_encode(output, hrp, data, datalen); +} + +int segwit_addr_decode(int* witver, uint8_t* witdata, size_t* witdata_len, const char* hrp, const char* addr) { + uint8_t data[84]; + char hrp_actual[84]; + size_t data_len; + if (!bech32_decode(hrp_actual, data, &data_len, addr)) return 0; + if (data_len == 0 || data_len > 65) return 0; + if (strncmp(hrp, hrp_actual, 84) != 0) return 0; + if (data[0] > 16) return 0; + *witdata_len = 0; + if (!convert_bits(witdata, witdata_len, 8, data + 1, data_len - 1, 5, 0)) return 0; + if (*witdata_len < 2 || *witdata_len > 40) return 0; + if (data[0] == 0 && *witdata_len != 20 && *witdata_len != 32) return 0; + *witver = data[0]; + return 1; +} diff --git a/segwit_addr.h b/segwit_addr.h new file mode 100644 index 0000000000000000000000000000000000000000..dbec91b028608c3a9f6dbafea91efca2b475f696 --- /dev/null +++ b/segwit_addr.h @@ -0,0 +1,101 @@ +/* Copyright (c) 2017 Pieter Wuille + * + * 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. + * + * 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. + */ + +#ifndef _SEGWIT_ADDR_H_ +#define _SEGWIT_ADDR_H_ 1 + +#include + +/** Encode a SegWit address + * + * Out: output: Pointer to a buffer of size 73 + strlen(hrp) that will be + * updated to contain the null-terminated address. + * In: hrp: Pointer to the null-terminated human readable part to use + * (chain/network specific). + * ver: Version of the witness program (between 0 and 16 inclusive). + * prog: Data bytes for the witness program (between 2 and 40 bytes). + * prog_len: Number of data bytes in prog. + * Returns 1 if successful. + */ +int segwit_addr_encode( + char *output, + const char *hrp, + int ver, + const uint8_t *prog, + size_t prog_len +); + +/** Decode a SegWit address + * + * Out: ver: Pointer to an int that will be updated to contain the witness + * program version (between 0 and 16 inclusive). + * prog: Pointer to a buffer of size 40 that will be updated to + * contain the witness program bytes. + * prog_len: Pointer to a size_t that will be updated to contain the length + * of bytes in prog. + * hrp: Pointer to the null-terminated human readable part that is + * expected (chain/network specific). + * addr: Pointer to the null-terminated address. + * Returns 1 if successful. + */ +int segwit_addr_decode( + int* ver, + uint8_t* prog, + size_t* prog_len, + const char* hrp, + const char* addr +); + +/** Encode a Bech32 string + * + * Out: output: Pointer to a buffer of size strlen(hrp) + data_len + 8 that + * will be updated to contain the null-terminated Bech32 string. + * In: hrp : Pointer to the null-terminated human readable part. + * data : Pointer to an array of 5-bit values. + * data_len: Length of the data array. + * Returns 1 if successful. + */ +int bech32_encode( + char *output, + const char *hrp, + const uint8_t *data, + size_t data_len +); + +/** Decode a Bech32 string + * + * Out: hrp: Pointer to a buffer of size strlen(input) - 6. Will be + * updated to contain the null-terminated human readable part. + * data: Pointer to a buffer of size strlen(input) - 8 that will + * hold the encoded 5-bit data values. + * data_len: Pointer to a size_t that will be updated to be the number + * of entries in data. + * In: input: Pointer to a null-terminated Bech32 string. + * Returns 1 if succesful. + */ +int bech32_decode( + char *hrp, + uint8_t *data, + size_t *data_len, + const char *input +); + +#endif

-----END OF PAGE-----