Skip to content

Commit

Permalink
feat(mnemonic): js doesnt handle List and swift doesnt handle Array t…
Browse files Browse the repository at this point in the history
…his is the solution
  • Loading branch information
goncalo-frade-iohk committed Oct 18, 2023
1 parent 3f32662 commit 9cacf48
Show file tree
Hide file tree
Showing 7 changed files with 2,160 additions and 2,135 deletions.
Original file line number Diff line number Diff line change
@@ -1,21 +1,51 @@
package io.iohk.atala.prism.apollo.derivation

import kotlin.js.ExperimentalJsExport
import kotlin.js.JsExport
import io.iohk.atala.prism.apollo.hashing.SHA256

/**
* A model representing the Mnemonic Code
*
* @exception MnemonicLengthException in case it is not 24 words
*/
@OptIn(ExperimentalJsExport::class)
@JsExport
data class MnemonicCode
@Throws(MnemonicLengthException::class)
constructor(val words: List<String>) {
init {
if (words.size % 3 != 0) {
throw MnemonicLengthException("Can't create a DID from mnemonic that is not dividable by 3")

data class MnemonicCode constructor(val words: List<String>) {
fun toMnemonic(entropy: ByteArray): List<String> {
if (entropy.size % 4 > 0) {
throw Exception("Entropy length not multiple of 32 bits.")
}
if (entropy.isEmpty()) {
throw Exception("Entropy is empty.")
}

val sha = SHA256()
sha.update(entropy)
val hash = sha.digest()
val checksumLengthBits = entropy.size / 4
val checksum = hash[0].toInt() ushr (8 - checksumLengthBits)

val concatBits = BooleanArray(entropy.size * 8 + checksumLengthBits)
for (i in entropy.indices) {
for (j in 0 until 8) {
concatBits[i * 8 + j] = entropy[i].toInt() and (1 shl (7 - j)) != 0
}
}
for (i in 0 until checksumLengthBits) {
concatBits[entropy.size * 8 + i] = checksum and (1 shl (checksumLengthBits - i - 1)) != 0
}

val words = ArrayList<String>()
val nwords = concatBits.size / 11
for (i in 0 until nwords) {
var index = 0
for (j in 0 until 11) {
index = index shl 1
if (concatBits[i * 11 + j]) {
index = index or 0x1
}
}
words.add(this.words[index]) // Assuming wordList is a list of words according to BIP-39
}

return words
}
}
Loading

0 comments on commit 9cacf48

Please sign in to comment.