コード例 #1
0
        /// <summary>
        /// Returns all the 2048 words found in the given word-list.
        /// </summary>
        /// <exception cref="ArgumentException"/>
        /// <param name="wl">Word list to use</param>
        /// <returns>An array of 2048 strings</returns>
        public static string[] GetAllWords(WordLists wl)
        {
            if (!Enum.IsDefined(typeof(WordLists), wl))
            {
                throw new ArgumentException("Given word list is not defined.");
            }

            string   path = $"Autarkysoft.Bitcoin.ImprovementProposals.BIP0039WordLists.{wl}.txt";
            Assembly asm  = Assembly.GetExecutingAssembly();

            using Stream stream = asm.GetManifestResourceStream(path);
            if (stream != null)
            {
                using StreamReader reader = new StreamReader(stream);
                int      i      = 0;
                string[] result = new string[2048];
                while (!reader.EndOfStream)
                {
                    result[i++] = reader.ReadLine();
                }
                if (i != 2048)
                {
                    throw new ArgumentException("There is something wrong with the embeded word list.");
                }

                return(result);
            }
            else
            {
                throw new ArgumentException("Word list was not found.");
            }
        }
コード例 #2
0
 // Use this for initialization
 void Start()
 {
     //Initialize word list for the duration of the game
     words = WordLists.Load(Path.Combine(Application.dataPath, "Resources/_Persistence/WordBank.xml"));
     //Initialize score
     score          = 0;
     textScore.text = "Score: " + score.ToString();
     wrongPanel     = GameObject.Find("WrongPanel");
     wrongPanel.SetActive(false);
     //First Secret word is from easy list
     resetWords(Difficulty.BEGINNER);
 }
コード例 #3
0
        private string GetWord(string wordList)
        {
            if (!WordLists.ContainsKey(wordList))
            {
                WordLists.Add(wordList, GetWordList(wordList));
            }

            var list = WordLists[wordList];

            var index = Number(1, list.Count) - 1;

            return(list[index]);
        }
コード例 #4
0
        /// <summary>
        /// Initializes a new instance of <see cref="BIP0039"/> with the given entropy, world list and the passphrase.
        /// </summary>
        /// <exception cref="ArgumentException"/>
        /// <exception cref="ArgumentNullException"/>
        /// <exception cref="ArgumentOutOfRangeException"/>
        /// <param name="entropy">Entropy to use (must be 16, 24, 28 or 32 bytes)</param>
        /// <param name="wl">[Defaultvalue = <see cref="WordLists.English"/> Word list to use</param>
        /// <param name="passPhrase">
        /// [Default value = null] Optional passphrase to use for computing <see cref="BIP0032"/> entropy
        /// </param>
        public BIP0039(byte[] entropy, WordLists wl = WordLists.English, string passPhrase = null)
        {
            if (entropy == null)
            {
                throw new ArgumentNullException(nameof(entropy), "Entropy can not be null.");
            }
            if (!allowedEntropyLengths.Contains(entropy.Length))
            {
                throw new ArgumentOutOfRangeException(nameof(entropy), "Entropy must be 16 or 20 or 24 or 28 or 32 bytes.");
            }

            allWords = GetAllWords(wl);
            SetWordsFromEntropy(entropy);
            SetBip32(passPhrase);
        }
コード例 #5
0
        public void RecoverLastWord()
        {
            var          valid = new List <string>();
            const string words = "sword victory much blossom cradle sense boy float soda render arrive";

            foreach (var word in WordLists.GetWords(Languages.English))
            {
                var t = $"{words} {word}";
                if (Mnemonic.IsValid(t))
                {
                    valid.Add(t);
                }
            }
            Assert.Equal(128, valid.Count);
        }
コード例 #6
0
        /// <summary>
        /// Initializes a new instance of <see cref="BIP0039"/> with a randomly generated entropy of given
        /// <paramref name="entropySize"/> using the given <see cref="IRandomNumberGenerator"/> instance,
        /// world list and an the passphrase.
        /// </summary>
        /// <exception cref="ArgumentException"/>
        /// <exception cref="ArgumentNullException"/>
        /// <exception cref="ArgumentOutOfRangeException"/>
        /// <param name="rng">Random number generator to use</param>
        /// <param name="entropySize">
        /// Size of the entropy which determines number of words in final mnemonic.
        /// Size must be 16, 20, 24, 28 or 32 which results in 12, 15, 18, 21, and 24 words respectively.
        /// </param>
        /// <param name="wl">[Defaultvalue = <see cref="WordLists.English"/> Word list to use</param>
        /// <param name="passPhrase">
        /// [Default value = null] Optional passphrase to use for computing <see cref="BIP0032"/> entropy
        /// </param>
        public BIP0039(IRandomNumberGenerator rng, int entropySize, WordLists wl = WordLists.English, string passPhrase = null)
        {
            if (rng is null)
            {
                throw new ArgumentNullException(nameof(rng), "Random number generator can not be null.");
            }
            if (!allowedEntropyLengths.Contains(entropySize))
            {
                throw new ArgumentOutOfRangeException(nameof(entropySize), "Entropy must be 16 or 20 or 24 or 28 or 32 bytes.");
            }

            allWords = GetAllWords(wl);

            byte[] entropy = new byte[entropySize];
            rng.GetBytes(entropy);
            SetWordsFromEntropy(entropy);

            SetBip32(passPhrase);
        }
コード例 #7
0
 public void WordListsComplete()
 {
     Assert.True(WordLists.GetWords(Languages.English).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.English).First() == "abandon");
     Assert.True(WordLists.GetWords(Languages.Spanish).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.Spanish).First() == "ábaco");
     Assert.True(WordLists.GetWords(Languages.French).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.French).First() == "abaisser");
     Assert.True(WordLists.GetWords(Languages.Italian).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.Italian).First() == "abaco");
     Assert.True(WordLists.GetWords(Languages.Japanese).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.Japanese).First() == "あいこくしん");
     Assert.True(WordLists.GetWords(Languages.PortugueseBrazil).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.PortugueseBrazil).First() == "abacate");
     Assert.True(WordLists.GetWords(Languages.ChineseSimplified).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.ChineseSimplified).First() == "的");
     Assert.True(WordLists.GetWords(Languages.ChineseTraditional).Length == 2048);
     Assert.True(WordLists.GetWords(Languages.ChineseTraditional).First() == "的");
 }
コード例 #8
0
        private bool TrySetWordList(WordLists wl)
        {
            string   fPath = $"FinderOuter.Backend.ImprovementProposals.BIP0039WordLists.{wl.ToString()}.txt";
            Assembly asm   = Assembly.GetExecutingAssembly();

            using (Stream stream = asm.GetManifestResourceStream(fPath))
            {
                if (stream != null)
                {
                    using StreamReader reader = new StreamReader(stream);
                    allWords = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    return(Fail($"Could not find {wl.ToString()} word list among resources."));;
                }
            }

            return(true);
        }
コード例 #9
0
 public static string GenerateMissionName()
 {
     return("Operation " + WordLists.GetRandomCommonAdjective() + " " + WordLists.GetRandomCommonNoun());
 }
コード例 #10
0
        /// <summary>
        /// Initializes a new instance of <see cref="BIP0039"/> with the given mnemonic, world list and the passphrase.
        /// </summary>
        /// <exception cref="ArgumentException"/>
        /// <exception cref="ArgumentNullException"/>
        /// <exception cref="FormatException"/>
        /// <param name="mnemonic">Mnemonic (should be 12, 15, 18, 21 or 24 words)</param>
        /// <param name="wl">[Defaultvalue = <see cref="WordLists.English"/> Word list to use</param>
        /// <param name="passPhrase">
        /// [Default value = null] Optional passphrase to use for computing <see cref="BIP0032"/> entropy
        /// </param>
        public BIP0039(string mnemonic, WordLists wl = WordLists.English, string passPhrase = null)
        {
            if (string.IsNullOrWhiteSpace(mnemonic))
            {
                throw new ArgumentNullException(nameof(mnemonic), "Seed can not be null or empty!");
            }
            allWords = GetAllWords(wl);

            string[] words = mnemonic.Normalize(NormalizationForm.FormKD)
                             .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (!words.All(x => allWords.Contains(x)))
            {
                throw new ArgumentException(nameof(mnemonic), "Seed has invalid words.");
            }
            if (!allowedWordLengths.Contains(words.Length))
            {
                throw new FormatException("Invalid seed length. It should be ∈{12, 15, 18, 21, 24}");
            }

            wordIndexes = new uint[words.Length];
            for (int i = 0; i < words.Length; i++)
            {
                wordIndexes[i] = (uint)Array.IndexOf(allWords, words[i]);
            }

            // Compute and check checksum
            int MS    = words.Length;
            int ENTCS = MS * 11;
            int CS    = ENTCS % 32;
            int ENT   = ENTCS - CS;

            byte[] entropy = new byte[ENT / 8];

            int itemIndex = 0;
            int bitIndex  = 0;
            // Number of bits in a word
            int toTake = 8;
            // Indexes are held in a UInt32 but they are only 11 bits
            int maxBits = 11;

            for (int i = 0; i < entropy.Length; i++)
            {
                if (bitIndex + toTake <= maxBits)
                {
                    // All 8 bits are in one item

                    // To take 8 bits (*) out of 00000000 00000000 00000xx* *******x:
                    // 1. Shift right to get rid of extra bits on right, then cast to byte to get rid of the rest
                    // >> maxBits - toTake - bitIndex
                    entropy[i] = (byte)(wordIndexes[itemIndex] >> (3 - bitIndex));
                }
                else
                {
                    // Only a part of 8 bits are in this item, the rest is in the next.
                    // Since items are only 32 bits there is no other possibility (8<32)

                    // To take 8 bits(*) out of [00000000 00000000 00000xxx xxxx****] [00000000 00000000 00000*** *xxxxxxx]:
                    // Take first item at itemIndex [00000000 00000000 00000xxx xxxx****]:
                    //    * At most 7 bits and at least 1 bit should be taken
                    // 1. Shift left [00000000 00000000 0xxxxxxx ****0000] (<< 8 - (maxBits - bitIndex)) 8-max+bi
                    // 2. Zero the rest of the bits (& (00000000 00000000 00000000 11111111))

                    // Take next item at itemIndex+1 [00000000 00000000 00000*** *xxxxxxx]
                    // 3. Shift right [00000000 00000000 00000000 0000****]
                    // number of bits already taken = maxBits - bitIndex
                    // nuber of bits to take = toTake - (maxBits - bitIndex)
                    // Number of bits on the right to get rid of= maxBits - (toTake - (maxBits - bitIndex))
                    // 4. Add two values to each other using bitwise OR [****0000] | [0000****]
                    entropy[i] = (byte)(((wordIndexes[itemIndex] << (bitIndex - 3)) & 0xff) |
                                        (wordIndexes[itemIndex + 1] >> (14 - bitIndex)));
                }

                bitIndex += toTake;
                if (bitIndex >= maxBits)
                {
                    bitIndex -= maxBits;
                    itemIndex++;
                }
            }

            // Compute and compare checksum:
            // CS is at most 8 bits and it is the remaining bits from the loop above and it is only from last item
            // [00000000 00000000 00000xxx xxxx****]
            // We already know the number of bits here: CS
            // A simple & does the work
            uint mask             = (1U << CS) - 1;
            byte expectedChecksum = (byte)(wordIndexes[itemIndex] & mask);

            // Checksum is the "first" CS bits of hash: [****xxxx]
            using Sha256 hash = new Sha256();
            byte[] hashOfEntropy  = hash.ComputeHash(entropy);
            byte   actualChecksum = (byte)(hashOfEntropy[0] >> (8 - CS));

            if (expectedChecksum != actualChecksum)
            {
                Array.Clear(wordIndexes, 0, wordIndexes.Length);
                wordIndexes = null;

                throw new FormatException("Wrong checksum.");
            }

            SetBip32(passPhrase);
        }
コード例 #11
0
 /// <inheritdoc cref="LevenshteinDistance(string[])"/>
 /// <exception cref="ArgumentException"/>
 public static int[,] LevenshteinDistance(WordLists wl) => LevenshteinDistance(GetAllWords(wl));
コード例 #12
0
 private void DataBindLocale()
 {
     DataContext = _localization;
     CallLetters.SetLocalization(_localization.CallLetters);
     WordLists.SetLocalization(_localization.WordLists);
 }
コード例 #13
0
 // Check overlap
 /// <summary>Returns whether the given token counts as a valid pronominal mention for KBP.</summary>
 /// <remarks>
 /// Returns whether the given token counts as a valid pronominal mention for KBP.
 /// This method (at present) works for either Chinese or English.
 /// </remarks>
 /// <param name="word">The token to classify.</param>
 /// <returns>true if this token is a pronoun that KBP should recognize.</returns>
 private static bool KbpIsPronominalMention(CoreLabel word)
 {
     return(WordLists.IsKbpPronominalMention(word.Word()));
 }
コード例 #14
0
        public async Task <bool> FindMissing(string mnemonic, char missingChar, MnemonicTypes mnType, WordLists wl)
        {
            InitReport();

            if (!TrySetWordList(wl))
            {
                return(false);
            }
            if (!IsMissingCharValid(missingChar))
            {
                return(Fail("Missing character is not accepted."));
            }
            if (!TrySplitMnemonic(mnemonic, missingChar, out words))
            {
                return(false);
            }

            Stopwatch watch = Stopwatch.StartNew();

            bool success = await Task.Run(() =>
            {
                return(words.Length switch
                {
                    24 => Loop24(),
                    21 => Loop21(),
                    18 => Loop18(),
                    15 => Loop15(),
                    _ => Loop12(),
                });
            });
コード例 #15
0
 private void DataBind()
 {
     WordLists.SetModel(_model.WordListsModel);
     CallLetters.SetModel(_model.CallLettersModel);
 }