Bitcoin/address validation: Difference between revisions

Content added Content deleted
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
Line 965: Line 965:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<lang scala>// version 1.0.6
<lang scala>import java.security.MessageDigest

import java.security.MessageDigest


object Bitcoin {
object Bitcoin {
Line 974: Line 972:
private fun ByteArray.contentEquals(other: ByteArray): Boolean {
private fun ByteArray.contentEquals(other: ByteArray): Boolean {
if (this.size != other.size) return false
if (this.size != other.size) return false
for (i in 0 until this.size) if (this[i] != other[i]) return false
return (0 until this.size).none { this[it] != other[it] }
return true
}
}


Line 983: Line 980:
var p = ALPHABET.indexOf(c)
var p = ALPHABET.indexOf(c)
if (p == -1) return null
if (p == -1) return null
for (j in 24 downTo 1) {
for (j in 24 downTo 1) {
p += 58 * (output[j].toInt() and 0xff)
p += 58 * (output[j].toInt() and 0xff)
output[j] = (p % 256).toByte()
output[j] = (p % 256).toByte()
Line 992: Line 989:
return output
return output
}
}

private fun sha256(data: ByteArray, start: Int, len: Int, recursion: Int): ByteArray {
private fun sha256(data: ByteArray, start: Int, len: Int, recursion: Int): ByteArray {
if (recursion == 0) return data
if (recursion == 0) return data
Line 998: Line 995:
md.update(data.sliceArray(start until start + len))
md.update(data.sliceArray(start until start + len))
return sha256(md.digest(), 0, 32, recursion - 1)
return sha256(md.digest(), 0, 32, recursion - 1)
}
}


fun validateAddress(address: String): Boolean {
fun validateAddress(address: String): Boolean {
if (address.length !in 26..35) return false
if (address.length !in 26..35) return false
val decoded = decodeBase58(address)
val decoded = decodeBase58(address)
if (decoded == null) return false
if (decoded == null) return false