Moves Bech Utility methods from CryptoUtils to BechUtils

This commit is contained in:
Vitor Pamplona 2023-07-24 11:18:57 -04:00
parent 69eea8824a
commit 7923f5d854
2 changed files with 15 additions and 15 deletions

View File

@ -29,9 +29,9 @@ public typealias Int5 = Byte
* See https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki and https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki.
*/
object Bech32 {
public const val alphabet: String = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
const val alphabet: String = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
public enum class Encoding(public val constant: Int) {
enum class Encoding(public val constant: Int) {
Bech32(1),
Bech32m(0x2bc830a3),
Beck32WithoutChecksum(0)
@ -198,3 +198,16 @@ object Bech32 {
return output.toByteArray()
}
}
fun ByteArray.toNsec() = Bech32.encodeBytes(hrp = "nsec", this, Bech32.Encoding.Bech32)
fun ByteArray.toNpub() = Bech32.encodeBytes(hrp = "npub", this, Bech32.Encoding.Bech32)
fun String.bechToBytes(hrp: String? = null): ByteArray {
val decodedForm = Bech32.decodeBytes(this)
hrp?.also {
if (it != decodedForm.first) {
throw IllegalArgumentException("Expected $it but obtained ${decodedForm.first}")
}
}
return decodedForm.second
}

View File

@ -72,16 +72,3 @@ fun Int.toByteArray(): ByteArray {
}
return bytes
}
fun ByteArray.toNsec() = Bech32.encodeBytes(hrp = "nsec", this, Bech32.Encoding.Bech32)
fun ByteArray.toNpub() = Bech32.encodeBytes(hrp = "npub", this, Bech32.Encoding.Bech32)
fun String.bechToBytes(hrp: String? = null): ByteArray {
val decodedForm = Bech32.decodeBytes(this)
hrp?.also {
if (it != decodedForm.first) {
throw IllegalArgumentException("Expected $it but obtained ${decodedForm.first}")
}
}
return decodedForm.second
}