根据BIP39标准,助记词的长度通常为12、15、18、21或24个单词,每个单词由英文单词列表中的单词组成,单词之间使用空格分隔。因此,可以使用以下代码检查输入是否是助记词:
function isMnemonic(input) {
let words = input.trim().split(/\s+/);
return words.length >= 12 && words.length <= 24;
}
该函数将输入值分割成单词,并检查单词数量是否在12和24之间。如果是,则返回 true,否则返回 false。
私钥的长度通常为32个字节,可以表示为64个十六进制字符。因此,可以使用以下代码检查输入是否是私钥:
function isPrivateKey(input) {
let hex = input.trim();
return hex.length === 64 && /^[0-9a-fA-F]+$/.test(hex);
}
该函数首先使用 trim 方法去除输入值两端的空格,并将其存储为十六进制字符串。然后,它检查字符串长度是否为64,并使用正则表达式检查字符串是否由十六进制数字组成。如果是,则返回 true,否则返回 false。
可以将这些函数结合起来,并根据需要进行调用,例如:
let input = "crazy fold swing grid acid narrow velvet potato fold gun crawl chair";
if (isMnemonic(input)) {
console.log("Input is a mnemonic");
} else if (isPrivateKey(input)) {
console.log("Input is a private key");
} else {
console.log("Input is neither a mnemonic nor a private key");
}
这将检查输入是否为助记词或私钥,并相应地输出一条消息。