Skip to content

Commit d2300be

Browse files
authored
Merge pull request #1458 from josibake/silent-payments-bip
BIP 352: Silent Payments
2 parents 56575ff + 17e1d16 commit d2300be

8 files changed

+4497
-0
lines changed

README.mediawiki

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,6 +1106,13 @@ Those proposing changes should consider that ultimately consent may rest with th
11061106
| Alfred Hodler, Clark Moody
11071107
| Informational
11081108
| Draft
1109+
|- style="background-color: #ffffcf"
1110+
| [[bip-0352.mediawiki|352]]
1111+
| Applications
1112+
| Silent Payments
1113+
| josibake, Ruben Somsen
1114+
| Standard
1115+
| Proposed
11091116
|-
11101117
| [[bip-0370.mediawiki|370]]
11111118
| Applications

bip-0352.mediawiki

Lines changed: 493 additions & 0 deletions
Large diffs are not rendered by default.

bip-0352/bech32m.py

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# Copyright (c) 2017, 2020 Pieter Wuille
2+
#
3+
# Permission is hereby granted, free of charge, to any person obtaining a copy
4+
# of this software and associated documentation files (the "Software"), to deal
5+
# in the Software without restriction, including without limitation the rights
6+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
# copies of the Software, and to permit persons to whom the Software is
8+
# furnished to do so, subject to the following conditions:
9+
#
10+
# The above copyright notice and this permission notice shall be included in
11+
# all copies or substantial portions of the Software.
12+
#
13+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
# THE SOFTWARE.
20+
21+
"""Reference implementation for Bech32/Bech32m and segwit addresses."""
22+
23+
24+
from enum import Enum
25+
26+
class Encoding(Enum):
27+
"""Enumeration type to list the various supported encodings."""
28+
BECH32 = 1
29+
BECH32M = 2
30+
31+
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
32+
BECH32M_CONST = 0x2bc830a3
33+
34+
def bech32_polymod(values):
35+
"""Internal function that computes the Bech32 checksum."""
36+
generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
37+
chk = 1
38+
for value in values:
39+
top = chk >> 25
40+
chk = (chk & 0x1ffffff) << 5 ^ value
41+
for i in range(5):
42+
chk ^= generator[i] if ((top >> i) & 1) else 0
43+
return chk
44+
45+
46+
def bech32_hrp_expand(hrp):
47+
"""Expand the HRP into values for checksum computation."""
48+
return [ord(x) >> 5 for x in hrp] + [0] + [ord(x) & 31 for x in hrp]
49+
50+
51+
def bech32_verify_checksum(hrp, data):
52+
"""Verify a checksum given HRP and converted data characters."""
53+
const = bech32_polymod(bech32_hrp_expand(hrp) + data)
54+
if const == 1:
55+
return Encoding.BECH32
56+
if const == BECH32M_CONST:
57+
return Encoding.BECH32M
58+
return None
59+
60+
def bech32_create_checksum(hrp, data, spec):
61+
"""Compute the checksum values given HRP and data."""
62+
values = bech32_hrp_expand(hrp) + data
63+
const = BECH32M_CONST if spec == Encoding.BECH32M else 1
64+
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const
65+
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
66+
67+
68+
def bech32_encode(hrp, data, spec):
69+
"""Compute a Bech32 string given HRP and data values."""
70+
combined = data + bech32_create_checksum(hrp, data, spec)
71+
return hrp + '1' + ''.join([CHARSET[d] for d in combined])
72+
73+
def bech32_decode(bech):
74+
"""Validate a Bech32/Bech32m string, and determine HRP and data."""
75+
if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
76+
(bech.lower() != bech and bech.upper() != bech)):
77+
return (None, None, None)
78+
bech = bech.lower()
79+
pos = bech.rfind('1')
80+
81+
# remove the requirement that bech32m be less than 90 chars
82+
if pos < 1 or pos + 7 > len(bech):
83+
return (None, None, None)
84+
if not all(x in CHARSET for x in bech[pos+1:]):
85+
return (None, None, None)
86+
hrp = bech[:pos]
87+
data = [CHARSET.find(x) for x in bech[pos+1:]]
88+
spec = bech32_verify_checksum(hrp, data)
89+
if spec is None:
90+
return (None, None, None)
91+
return (hrp, data[:-6], spec)
92+
93+
def convertbits(data, frombits, tobits, pad=True):
94+
"""General power-of-2 base conversion."""
95+
acc = 0
96+
bits = 0
97+
ret = []
98+
maxv = (1 << tobits) - 1
99+
max_acc = (1 << (frombits + tobits - 1)) - 1
100+
for value in data:
101+
if value < 0 or (value >> frombits):
102+
return None
103+
acc = ((acc << frombits) | value) & max_acc
104+
bits += frombits
105+
while bits >= tobits:
106+
bits -= tobits
107+
ret.append((acc >> bits) & maxv)
108+
if pad:
109+
if bits:
110+
ret.append((acc << (tobits - bits)) & maxv)
111+
elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
112+
return None
113+
return ret
114+
115+
116+
def decode(hrp, addr):
117+
"""Decode a segwit address."""
118+
hrpgot, data, spec = bech32_decode(addr)
119+
if hrpgot != hrp:
120+
return (None, None)
121+
decoded = convertbits(data[1:], 5, 8, False)
122+
if decoded is None or len(decoded) < 2:
123+
return (None, None)
124+
if data[0] > 16:
125+
return (None, None)
126+
return (data[0], decoded)
127+
128+
129+
def encode(hrp, witver, witprog):
130+
"""Encode a segwit address."""
131+
spec = Encoding.BECH32 if witver == 0 else Encoding.BECH32M
132+
ret = bech32_encode(hrp, [witver] + convertbits(witprog, 8, 5), spec)
133+
if decode(hrp, ret) == (None, None):
134+
return None
135+
return ret

bip-0352/bitcoin_utils.py

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
import hashlib
2+
import struct
3+
from io import BytesIO
4+
from secp256k1 import ECKey
5+
from typing import Union
6+
7+
8+
def from_hex(hex_string):
9+
"""Deserialize from a hex string representation (e.g. from RPC)"""
10+
return BytesIO(bytes.fromhex(hex_string))
11+
12+
13+
def ser_uint32(u: int) -> bytes:
14+
return u.to_bytes(4, "big")
15+
16+
17+
def ser_uint256(u):
18+
return u.to_bytes(32, 'little')
19+
20+
21+
def deser_uint256(f):
22+
return int.from_bytes(f.read(32), 'little')
23+
24+
25+
def deser_txid(txid: str):
26+
# recall that txids are serialized little-endian, but displayed big-endian
27+
# this means when converting from a human readable hex txid, we need to first
28+
# reverse it before deserializing it
29+
dixt = "".join(map(str.__add__, txid[-2::-2], txid[-1::-2]))
30+
return bytes.fromhex(dixt)
31+
32+
33+
def deser_compact_size(f: BytesIO):
34+
view = f.getbuffer()
35+
nbytes = view.nbytes;
36+
view.release()
37+
if (nbytes == 0):
38+
return 0 # end of stream
39+
40+
nit = struct.unpack("<B", f.read(1))[0]
41+
if nit == 253:
42+
nit = struct.unpack("<H", f.read(2))[0]
43+
elif nit == 254:
44+
nit = struct.unpack("<I", f.read(4))[0]
45+
elif nit == 255:
46+
nit = struct.unpack("<Q", f.read(8))[0]
47+
return nit
48+
49+
50+
def deser_string(f: BytesIO):
51+
nit = deser_compact_size(f)
52+
return f.read(nit)
53+
54+
55+
def deser_string_vector(f: BytesIO):
56+
nit = deser_compact_size(f)
57+
r = []
58+
for _ in range(nit):
59+
t = deser_string(f)
60+
r.append(t)
61+
return r
62+
63+
64+
class COutPoint:
65+
__slots__ = ("hash", "n",)
66+
67+
def __init__(self, hash=b"", n=0,):
68+
self.hash = hash
69+
self.n = n
70+
71+
def serialize(self):
72+
r = b""
73+
r += self.hash
74+
r += struct.pack("<I", self.n)
75+
return r
76+
77+
def deserialize(self, f):
78+
self.hash = f.read(32)
79+
self.n = struct.unpack("<I", f.read(4))[0]
80+
81+
82+
class VinInfo:
83+
__slots__ = ("outpoint", "scriptSig", "txinwitness", "prevout", "private_key")
84+
85+
def __init__(self, outpoint=None, scriptSig=b"", txinwitness=None, prevout=b"", private_key=None):
86+
if outpoint is None:
87+
self.outpoint = COutPoint()
88+
else:
89+
self.outpoint = outpoint
90+
if txinwitness is None:
91+
self.txinwitness = CTxInWitness()
92+
else:
93+
self.txinwitness = txinwitness
94+
if private_key is None:
95+
self.private_key = ECKey()
96+
else:
97+
self.private_key = private_key
98+
self.scriptSig = scriptSig
99+
self.prevout = prevout
100+
101+
102+
class CScriptWitness:
103+
__slots__ = ("stack",)
104+
105+
def __init__(self):
106+
# stack is a vector of strings
107+
self.stack = []
108+
109+
def is_null(self):
110+
if self.stack:
111+
return False
112+
return True
113+
114+
115+
class CTxInWitness:
116+
__slots__ = ("scriptWitness",)
117+
118+
def __init__(self):
119+
self.scriptWitness = CScriptWitness()
120+
121+
def deserialize(self, f: BytesIO):
122+
self.scriptWitness.stack = deser_string_vector(f)
123+
return self
124+
125+
def is_null(self):
126+
return self.scriptWitness.is_null()
127+
128+
129+
def hash160(s: Union[bytes, bytearray]) -> bytes:
130+
return hashlib.new("ripemd160", hashlib.sha256(s).digest()).digest()
131+
132+
133+
def is_p2tr(spk: bytes) -> bool:
134+
if len(spk) != 34:
135+
return False
136+
# OP_1 OP_PUSHBYTES_32 <32 bytes>
137+
return (spk[0] == 0x51) & (spk[1] == 0x20)
138+
139+
140+
def is_p2wpkh(spk: bytes) -> bool:
141+
if len(spk) != 22:
142+
return False
143+
# OP_0 OP_PUSHBYTES_20 <20 bytes>
144+
return (spk[0] == 0x00) & (spk[1] == 0x14)
145+
146+
147+
def is_p2sh(spk: bytes) -> bool:
148+
if len(spk) != 23:
149+
return False
150+
# OP_HASH160 OP_PUSHBYTES_20 <20 bytes> OP_EQUAL
151+
return (spk[0] == 0xA9) & (spk[1] == 0x14) & (spk[-1] == 0x87)
152+
153+
154+
def is_p2pkh(spk: bytes) -> bool:
155+
if len(spk) != 25:
156+
return False
157+
# OP_DUP OP_HASH160 OP_PUSHBYTES_20 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG
158+
return (spk[0] == 0x76) & (spk[1] == 0xA9) & (spk[2] == 0x14) & (spk[-2] == 0x88) & (spk[-1] == 0xAC)

0 commit comments

Comments
 (0)