-
Notifications
You must be signed in to change notification settings - Fork 104
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
a06fd77 Add usage document (azuchi) 88204c7 Remove unnecessary code (azuchi) 8e988e7 Add script pubkey parse logic to SegiwtAddr#scriptpubkey= (azuchi) 30d8816 Add encoded value check (azuchi) 590d898 Fix check data length logic (azuchi) 1274ee7 Add newline at end of file (azuchi) 8795117 Add Ruby implementation (azuchi) Tree-SHA512: 3d60d8d749335bfeffe248e16d7cf4dad88d7f86d0207246c8e57d91472ffe74001759d6b333a2f9afc2b1ac8a1dc31d9834ec2b7572d43a0edb30ebabdcbabe
- Loading branch information
Showing
4 changed files
with
329 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# Bech32 Ruby | ||
|
||
## Usage | ||
|
||
Require code: | ||
|
||
```ruby | ||
require './bech32' | ||
require './segwit_addr' | ||
``` | ||
|
||
### Decode | ||
|
||
Decode Bech32-encoded data into hrp part and data part. | ||
|
||
```ruby | ||
hrp, data = Bech32.decode('BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4') | ||
|
||
# hrp is human-readable part of Bech32 format | ||
'bc' | ||
|
||
# data is data part of Bech32 format | ||
[0, 14, 20, 15, 7, 13, 26, 0, 25, 18, 6, 11, 13, 8, 21, 4, 20, 3, 17, 2, 29, 3, 12, 29, 3, 4, 15, 24, 20, 6, 14, 30, 22] | ||
``` | ||
|
||
Decode Bech32-encoded Segwit address into `SegwitAddr` instance. | ||
|
||
```ruby | ||
addr = 'BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4' | ||
segwit_addr = SegwitAddr.new(addr) | ||
|
||
# generate script pubkey | ||
segwit_addr.to_script_pubkey | ||
=> 0014751e76e8199196d454941c45d1b3a323f1433bd6 | ||
``` | ||
|
||
### Encode | ||
|
||
Encode Bech32 human-readable part and data part into Bech32 string. | ||
|
||
```ruby | ||
hrp = 'bc' | ||
data = [0, 14, 20, 15, 7, 13, 26, 0, 25, 18, 6, 11, 13, 8, 21, 4, 20, 3, 17, 2, 29, 3, 12, 29, 3, 4, 15, 24, 20, 6, 14, 30, 22] | ||
|
||
bech = Bech32.encode(hrp, data) | ||
=> bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4 | ||
``` | ||
|
||
Encode Segwit script into Bech32 Segwit address. | ||
|
||
```ruby | ||
segwit_addr = SegwitAddr.new | ||
segwit_addr.hrp = 'bc' | ||
segwit_addr.scriptpubkey = '0014751e76e8199196d454941c45d1b3a323f1433bd6' | ||
|
||
# generate addr | ||
segwit_addr.addr | ||
=> bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4 | ||
``` | ||
|
||
## Test | ||
|
||
Run test with: | ||
|
||
$ ruby test_bech32.rb |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# Copyright (c) 2017 Shigeyuki Azuchi | ||
# | ||
# 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. | ||
|
||
module Bech32 | ||
|
||
SEPARATOR = '1' | ||
|
||
CHARSET = %w(q p z r y 9 x 8 g f 2 t v d w 0 s 3 j n 5 4 k h c e 6 m u a 7 l) | ||
|
||
module_function | ||
|
||
# Encode Bech32 string | ||
def encode(hrp, data) | ||
checksummed = data + create_checksum(hrp, data) | ||
hrp + SEPARATOR + checksummed.map{|i|CHARSET[i]}.join | ||
end | ||
|
||
# Decode a Bech32 string and determine hrp and data | ||
def decode(bech) | ||
# check uppercase/lowercase | ||
return nil if (bech.downcase != bech && bech.upcase != bech) | ||
bech.each_char{|c|return nil if c.ord < 33 || c.ord > 126} | ||
bech = bech.downcase | ||
# check data length | ||
pos = bech.rindex(SEPARATOR) | ||
return nil if pos.nil? || pos < 1 || pos + 7 > bech.length || bech.length > 90 | ||
# check valid charset | ||
bech[pos+1..-1].each_char{|c|return nil unless CHARSET.include?(c)} | ||
# split hrp and data | ||
hrp = bech[0..pos-1] | ||
data = bech[pos+1..-1].each_char.map{|c|CHARSET.index(c)} | ||
# check checksum | ||
return nil unless verify_checksum(hrp, data) | ||
[hrp, data[0..-7]] | ||
end | ||
|
||
# Compute the checksum values given hrp and data. | ||
def create_checksum(hrp, data) | ||
values = expand_hrp(hrp) + data | ||
polymod = polymod(values + [0, 0, 0, 0, 0, 0]) ^ 1 | ||
(0..5).map{|i|(polymod >> 5 * (5 - i)) & 31} | ||
end | ||
|
||
# Verify a checksum given Bech32 string | ||
def verify_checksum(hrp, data) | ||
polymod(expand_hrp(hrp) + data) == 1 | ||
end | ||
|
||
# Expand the hrp into values for checksum computation. | ||
def expand_hrp(hrp) | ||
hrp.each_char.map{|c|c.ord >> 5} + [0] + hrp.each_char.map{|c|c.ord & 31} | ||
end | ||
|
||
# Compute Bech32 checksum | ||
def polymod(values) | ||
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] | ||
chk = 1 | ||
values.each do |v| | ||
top = chk >> 25 | ||
chk = (chk & 0x1ffffff) << 5 ^ v | ||
(0..4).each{|i|chk ^= ((top >> i) & 1) == 0 ? 0 : generator[i]} | ||
end | ||
chk | ||
end | ||
|
||
private_class_method :polymod, :expand_hrp | ||
|
||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
# Copyright (c) 2017 Shigeyuki Azuchi | ||
# | ||
# 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. | ||
|
||
require './bech32' | ||
|
||
class SegwitAddr | ||
|
||
attr_accessor :hrp # human-readable part | ||
attr_accessor :ver # witness version | ||
attr_accessor :prog # witness program | ||
|
||
def initialize(addr = nil) | ||
@hrp, @ver, @prog = parse_addr(addr) if addr | ||
end | ||
|
||
def to_scriptpubkey | ||
v = ver == 0 ? ver : ver + 0x80 | ||
([v, prog.length].pack("CC") + prog.map{|p|[p].pack("C")}.join).unpack('H*').first | ||
end | ||
|
||
def scriptpubkey=(script) | ||
values = [script].pack('H*').unpack("C*") | ||
@ver = values[0] | ||
@prog = values[2..-1] | ||
end | ||
|
||
def addr | ||
encoded = Bech32.encode(hrp, [ver] + convert_bits(prog, 8, 5)) | ||
chrp, cver, cprog = parse_addr(encoded) | ||
raise 'Invalid address' if chrp != hrp || cver != ver || cprog != prog | ||
encoded | ||
end | ||
|
||
private | ||
|
||
def parse_addr(addr) | ||
hrp, data = Bech32.decode(addr) | ||
raise 'Invalid address.' if hrp.nil? || (hrp != 'bc' && hrp != 'tb') | ||
ver = data[0] | ||
raise 'Invalid witness version' if ver > 16 | ||
prog = convert_bits(data[1..-1], 5, 8, false) | ||
raise 'Invalid witness program' if prog.nil? || prog.length < 2 || prog.length > 40 | ||
raise 'Invalid witness program with version 0' if ver == 0 && (prog.length != 20 && prog.length != 32) | ||
[hrp, ver, prog] | ||
end | ||
|
||
def convert_bits(data, from, to, padding=true) | ||
acc = 0 | ||
bits = 0 | ||
ret = [] | ||
maxv = (1 << to) - 1 | ||
max_acc = (1 << (from + to - 1)) - 1 | ||
data.each do |v| | ||
return nil if v < 0 || (v >> from) != 0 | ||
acc = ((acc << from) | v) & max_acc | ||
bits += from | ||
while bits >= to | ||
bits -= to | ||
ret << ((acc >> bits) & maxv) | ||
end | ||
end | ||
if padding | ||
ret << ((acc << (to - bits)) & maxv) unless bits == 0 | ||
elsif bits >= from || ((acc << (to - bits)) & maxv) != 0 | ||
return nil | ||
end | ||
ret | ||
end | ||
|
||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
# Copyright (c) 2017 Shigeyuki Azuchi | ||
# | ||
# 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. | ||
|
||
require './bech32' | ||
require './segwit_addr' | ||
require 'test/unit' | ||
|
||
class TestBech32 < Test::Unit::TestCase | ||
|
||
VALID_CHECKSUM = [ | ||
"A12UEL5L", | ||
"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs", | ||
"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw", | ||
"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j", | ||
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w", | ||
] | ||
|
||
VALID_ADDRESS = [ | ||
["BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4", "0014751e76e8199196d454941c45d1b3a323f1433bd6"], | ||
["tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7", | ||
"00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262"], | ||
["bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx", | ||
"8128751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd6"], | ||
["BC1SW50QA3JX3S", "9002751e"], | ||
["bc1zw508d6qejxtdg4y5r3zarvaryvg6kdaj", "8210751e76e8199196d454941c45d1b3a323"], | ||
["tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy", | ||
"0020000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433"], | ||
] | ||
|
||
INVALID_ADDRESS = [ | ||
"tc1qw508d6qejxtdg4y5r3zarvary0c5xw7kg3g4ty", | ||
"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5", | ||
"BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2", | ||
"bc1rw5uspcuh", | ||
"bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90", | ||
"BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P", | ||
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7", | ||
"tb1pw508d6qejxtdg4y5r3zarqfsj6c3", | ||
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv", | ||
] | ||
|
||
def test_verify_checksum | ||
VALID_CHECKSUM.each do |bech| | ||
hrp, _ = Bech32.decode(bech) | ||
assert_not_nil (hrp) | ||
pos = bech.rindex('1') | ||
bech = bech[0..pos] + (bech[pos + 1].ord ^ 1).chr + bech[pos+2..-1] | ||
hrp, _ = Bech32.decode(bech) | ||
assert_nil (hrp) | ||
end | ||
end | ||
|
||
def test_valid_address | ||
VALID_ADDRESS.each do |addr, hex| | ||
segwit_addr = SegwitAddr.new(addr) | ||
assert_not_nil(segwit_addr.ver) | ||
assert_equal(hex, segwit_addr.to_scriptpubkey) | ||
assert_equal(addr.downcase, segwit_addr.addr) | ||
end | ||
end | ||
|
||
def test_invalid_address | ||
INVALID_ADDRESS.each do |addr| | ||
assert_raise(RuntimeError){SegwitAddr.new(addr)} | ||
end | ||
end | ||
|
||
def test_scriptpubkey= | ||
segwit_addr = SegwitAddr.new | ||
segwit_addr.hrp = 'bc' | ||
segwit_addr.scriptpubkey = '0014751e76e8199196d454941c45d1b3a323f1433bd6' | ||
assert_equal('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', segwit_addr.addr) | ||
end | ||
|
||
end |