Esempio n. 1
0
        public void CreateHDWallet()
        {
            // 通过已知的助记词生成账号
            var wallet  = new Wallet(Words, Password);
            var account = wallet.GetAccount(0);

            Console.WriteLine(account.Address);
            var prk    = wallet.GetPrivateKey(account.Address);//获取账号对应的秘钥
            var accprk = account.PrivateKey;

            Console.WriteLine("the prk is {0}", prk.ToHex());
            Console.WriteLine("the accprk is {0}", accprk);
            // 第一次创建钱包 生成随机的助记词 并保存
            var mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve);

            Console.WriteLine(mnemonic.ToString());
            var masterKey  = mnemonic.DeriveExtKey("123456"); //生成一组组秘钥对   可以通过该秘钥继续生成子孙密钥对
            var privateKey = masterKey.PrivateKey;            //获取的是bitcoin的私钥

            var wallet1 = new  Wallet(mnemonic.ToString(), "123456");

            Console.WriteLine("the wallet1 mnemonic is {0}", mnemonic.ToString());
            var account1 = wallet1.GetAccount(0);

            Console.WriteLine("the wallet1 account is {0}", account1.Address);
            var keySvc = new KeyStoreService();
            var json   = keySvc.EncryptAndGenerateDefaultKeyStoreAsJson("123456", account1.PrivateKey.HexToByteArray(),
                                                                        account1.Address);
            var path = string.Format(@"e:\{0}.json", keySvc.GenerateUTCFileName(account1.Address));

            File.WriteAllText(path, json);
        }
Esempio n. 2
0
        public static string GetMnemonic(PrivateKeyNotWallet key, Wordlist wordlist)
        {
            var mnemonic = new Mnemonic(wordlist, key.PrivateKey.GetBytes());

            Debug.Assert(mnemonic.Words.Length == 24);
            return(mnemonic.ToString());
        }
Esempio n. 3
0
        private Expression RewriteVectorIntrinsic(Mnemonic mnemonic, bool hasSideEffect, PrimitiveType dtElem, Expression[] ops)
        {
            var cElem    = ops[0].DataType.Size / dtElem.Size;
            var dtVector = new ArrayType(dtElem, cElem);

            return(host.Intrinsic(mnemonic.ToString(), hasSideEffect, dtVector, ops));
        }
Esempio n. 4
0
        public static string GenerateSecret()
        {
            RandomUtils.Random = new UnsecureRandom();
            var mnemo = new Mnemonic(Wordlist.English, WordCount.Twelve);

            return(mnemo.ToString());
        }
Esempio n. 5
0
        public void CreateWalletSuccessfullyReturnsMnemonic()
        {
            Mnemonic mnemonic         = new Mnemonic(Wordlist.English, WordCount.Twelve);
            var      mockWalletCreate = new Mock <IWalletManager>();

            mockWalletCreate.Setup(wallet => wallet.CreateWallet(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), null)).Returns(mnemonic);

            var controller = new WalletController(mockWalletCreate.Object, new Mock <ITracker>().Object);

            // Act
            var result = controller.Create(new WalletCreationRequest
            {
                Name       = "myName",
                FolderPath = "",
                Password   = "",
                Network    = ""
            });

            // Assert
            mockWalletCreate.VerifyAll();
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.Equal(mnemonic.ToString(), viewResult.Value);
            Assert.NotNull(result);
        }
        static (byte[] seed, string sentence) CreateHdSecrets(byte[] sourceKeyMaterial, int startIndex)
        {
            WordList wordList = WordList.English;

            var usedKeyMaterial = new byte[32];

            Buffer.BlockCopy(sourceKeyMaterial, startIndex, usedKeyMaterial, 0, 32);

            var mnemonic = new Mnemonic(wordList, usedKeyMaterial);

            if (!mnemonic.IsValidChecksum)
            {
                throw new InvalidOperationException("Invalid checksum.");
            }

            var seed = mnemonic.DeriveSeed();

            seed.Check(64);

            var sentence = mnemonic.ToString();

            CheckNumberOfWords(sentence, WordListLength);

            var testRecovery = new Mnemonic(sentence, WordList.English);

            if (testRecovery.ToString() != sentence ||
                !ByteArrays.AreAllBytesEqual(testRecovery.DeriveSeed(), seed))
            {
                throw new InvalidOperationException("This seed cannot be recovered.");
            }

            return(seed, sentence);
        }
        public IActionResult Create([FromBody] WalletCreationRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                return(BuildErrorResponse(this.ModelState));
            }

            try
            {
                Mnemonic mnemonic = this.walletManager.CreateWallet(request.Password, request.Name, mnemonic: request.Mnemonic);

                // start syncing the wallet from the creation date
                this.walletSyncManager.SyncFromDate(this.dateTimeProvider.GetUtcNow());

                return(this.Json(mnemonic.ToString()));
            }
            catch (WalletException e)
            {
                // indicates that this wallet already exists
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.Conflict, e.Message, e.ToString()));
            }
            catch (NotSupportedException e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "There was a problem creating a wallet.", e.ToString()));
            }
        }
Esempio n. 8
0
        private void RenderMnemonic(MachineInstructionWriter writer)
        {
            var sb = new StringBuilder();

            sb.Append(Mnemonic.ToString());
            if (Condition != 0)
            {
                sb.AppendFormat(".{0}", Condition.ToString().ToLowerInvariant());
            }
            if (Delay)
            {
                sb.Append(".d");
            }
            if (SignExtend)
            {
                sb.AppendFormat(".x");
            }
            if (SetFlags)
            {
                sb.Append(".f");
            }
            if (Writeback != AddressWritebackMode.None)
            {
                sb.AppendFormat(".{0}", Writeback);
            }
            if (DirectWrite)
            {
                sb.Append(".di");
            }
            writer.WriteOpcode(sb.ToString());
        }
Esempio n. 9
0
        private void RenderMnemonic(MachineInstructionRenderer renderer, MachineInstructionRendererOptions options)
        {
            var s  = Mnemonic.ToString();
            var sb = new StringBuilder();

            for (int i = 0; i < s.Length; ++i)
            {
                char ch = s[i];
                if (ch == '_' && i < s.Length - 1 && s[i + 1] == '_')
                {
                    sb.Append('.');
                    ++i;
                }
                else
                {
                    sb.Append(ch);
                }
            }
            if (DirectionHint != DirectionHint.None)
            {
                sb.Append(':');
                if (DirectionHint == DirectionHint.Taken)
                {
                    sb.Append('t');
                }
                else
                {
                    sb.Append("nt");
                }
            }
            renderer.WriteMnemonic(sb.ToString());
        }
Esempio n. 10
0
 public override void Render(MachineInstructionWriter writer, MachineInstructionWriterOptions options)
 {
     if (Mnemonic == Mnemonic.illegal && Operands.Length > 0 && writer.Platform != null)
     {
         var imm = Operands[0] as M68kImmediateOperand;
         // MacOS uses invalid opcodes to invoke Macintosh Toolbox services.
         // We may have to generalize the Platform API to allow specifying
         // the opcode of the invoking instruction, to disambiguate from
         // "legitimate" TRAP calls.
         var svc = writer.Platform.FindService((int)imm.Constant.ToUInt32(), null);
         if (svc != null)
         {
             writer.WriteString(svc.Name);
             return;
         }
     }
     if (dataWidth != null)
     {
         writer.WriteOpcode(string.Format("{0}{1}", Mnemonic, DataSizeSuffix(dataWidth)));
     }
     else
     {
         writer.WriteOpcode(Mnemonic.ToString());
     }
     RenderOperands(writer, options);
 }
Esempio n. 11
0
        private void RenderMnemonic(MachineInstructionRenderer renderer)
        {
            var sb = new StringBuilder();

            sb.Append(Mnemonic.ToString().Replace('_', '.'));
            renderer.WriteMnemonic(sb.ToString());
        }
Esempio n. 12
0
        public void GetDeterministicSecretTest()
        {
            var mnemonic = new Mnemonic(Wordlist.English, WordCount.TwentyFour);

            var wallet = new HdWallet(mnemonic.ToString(), Wordlist.English, new SecureString(), Network.TestNet);

            var timeStamp = DateTime.UtcNow;

            var secretBtc1 = wallet.GetDeterministicSecret(Common.BtcTestNet, timeStamp);
            var secretBtc2 = wallet.GetDeterministicSecret(Common.BtcTestNet, timeStamp.AddMilliseconds(1));

            Assert.NotEqual(secretBtc1, secretBtc2);

            var secretBtc3 = wallet.GetDeterministicSecret(Common.BtcTestNet, timeStamp);

            Assert.Equal(secretBtc1, secretBtc3);

            var secretLtc1 = wallet.GetDeterministicSecret(Common.LtcTestNet, timeStamp);

            Assert.NotEqual(secretBtc1, secretLtc1);

            var secretXtz1 = wallet.GetDeterministicSecret(Common.XtzTestNet, timeStamp);

            Assert.NotEqual(secretBtc1, secretXtz1);

            var secretEth1 = wallet.GetDeterministicSecret(Common.EthTestNet, timeStamp);

            Assert.NotEqual(secretBtc1, secretEth1);
        }
Esempio n. 13
0
        void GenerateNewMnemonic(object sender, EventArgs args)
        {
            Mnemonic mnemo  = new Mnemonic(Wordlist.English);
            ExtKey   hdRoot = mnemo.DeriveExtKey("my password");

            message.Text = mnemo.ToString();
        }
        public IActionResult Create([FromBody] WalletCreationRequest request)
        {
            Guard.NotNull(request, nameof(request));

            // checks the request is valid
            if (!this.ModelState.IsValid)
            {
                var errors = this.ModelState.Values.SelectMany(e => e.Errors.Select(m => m.ErrorMessage));
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Formatting error", string.Join(Environment.NewLine, errors)));
            }

            try
            {
                Mnemonic mnemonic = this.walletManager.CreateWallet(request.Password, request.Name, mnemonic: request.Mnemonic);

                // start syncing the wallet from the creation date
                this.walletSyncManager.SyncFromDate(DateTime.Now);

                return(this.Json(mnemonic.ToString()));
            }
            catch (WalletException e)
            {
                // indicates that this wallet already exists
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.Conflict, e.Message, e.ToString()));
            }
            catch (NotSupportedException e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "There was a problem creating a wallet.", e.ToString()));
            }
        }
Esempio n. 15
0
        protected override void DoRender(MachineInstructionRenderer renderer, MachineInstructionRendererOptions options)
        {
            int iOp = WriteMnemonic(renderer);

            if (Operands == null || Operands.Length == 0)
            {
                return;
            }
            renderer.Tab();
            RenderOperand(Operands[iOp++], renderer, options);
            for (; iOp < Operands.Length; ++iOp)
            {
                var op = Operands[iOp];
                renderer.WriteChar(',');
                RenderOperand(op, renderer, options);
            }
            if (this.shiftCode == Mnemonic.Invalid)
            {
                return;
            }
            if (shiftCode == Mnemonic.lsl && (shiftAmount is ImmediateOperand imm && imm.Value.IsIntegerZero))
            {
                return;
            }
            renderer.WriteChar(',');
            renderer.WriteMnemonic(shiftCode.ToString());
            renderer.WriteChar(' ');
            RenderOperand(shiftAmount !, renderer, options);
        }
Esempio n. 16
0
    public void CreateAccount()
    {
        if (signUpPW.text.Length > 7)
        {
            password = signUpPW.text;
            WalletManager.Instance.CreateAccount(password);

            seedPanel.SetActive(true);

            // Creat mnemonic
            Mnemonic mnemo  = new Mnemonic(Wordlist.English, WordCount.Twelve);
            ExtKey   hdRoot = mnemo.DeriveExtKey(password);
            seedText.text = mnemo.ToString();

            IsEncryptedJson();

            Debug.Log(mnemo);
            Debug.Log("Address:" + WalletManager.Instance.publicAddress);
            Debug.Log("PrivateKey:" + WalletManager.Instance.privateKey);
            Debug.Log("Json:" + WalletManager.Instance.encryptedJson);
            Debug.Log("Password:" + WalletManager.Instance.password);

            password = null;
            //UIFunction();
        }
    }
Esempio n. 17
0
        private Expression RewriteVectorIntrinsic(Mnemonic mnemonic, PrimitiveType dtElem, Expression[] ops)
        {
            var cElem    = ops[0].DataType.Size / dtElem.Size;
            var dtVector = new ArrayType(dtElem, cElem);

            return(host.PseudoProcedure(mnemonic.ToString(), dtVector, ops));
        }
Esempio n. 18
0
        public Identity RandomIdentity()
        {
            var      recoveryPhrase = new Mnemonic(Wordlist.English, WordCount.Twelve);
            Identity identity       = new Identity(recoveryPhrase.ToString());

            return(identity);
        }
Esempio n. 19
0
        public void RandomWordsTest()
        {
            Mnemonic mnemonic     = new Mnemonic(Wordlist.English, WordCount.TwentyFour);
            string   mnemonicCode = mnemonic.ToString();

            Assert.Equal(24, mnemonicCode.Split(' ').Length);
        }
        public void CreateWalletSuccessfullyReturnsMnemonic()
        {
            Mnemonic mnemonic         = new Mnemonic(Wordlist.English, WordCount.Twelve);
            var      mockWalletCreate = new Mock <IWalletManager>();

            mockWalletCreate.Setup(wallet => wallet.CreateWallet(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(mnemonic);

            string dir        = AssureEmptyDir("TestData/ControllersTests/CreateWalletSuccessfullyReturnsMnemonic");
            var    dataFolder = new DataFolder(new NodeSettings {
                DataDir = dir
            });

            var controller = new WalletController(mockWalletCreate.Object, new Mock <IWalletSyncManager>().Object, It.IsAny <ConnectionManager>(), Network.Main, new Mock <ConcurrentChain>().Object, dataFolder);

            // Act
            var result = controller.Create(new WalletCreationRequest
            {
                Name       = "myName",
                FolderPath = "",
                Password   = "",
                Network    = ""
            });

            // Assert
            mockWalletCreate.VerifyAll();
            var viewResult = Assert.IsType <JsonResult>(result);

            Assert.Equal(mnemonic.ToString(), viewResult.Value);
            Assert.NotNull(result);
        }
Esempio n. 21
0
        public void CanNormalizeMnemonicString()
        {
            var mnemonic  = new Mnemonic("turtle front uncle idea crush write shrug there lottery flower risk shell", Wordlist.English);
            var mnemonic2 = new Mnemonic("turtle    front	uncle  idea crush write shrug there lottery flower risk shell", Wordlist.English);

            Assert.Equal(mnemonic.DeriveExtKey().ScriptPubKey, mnemonic2.DeriveExtKey().ScriptPubKey);
            Assert.Equal(mnemonic.ToString(), mnemonic2.ToString());
        }
Esempio n. 22
0
        static void CreateMnemonic()
        {
            Mnemonic mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve);

            var mnemonicValue = mnemonic.ToString();

            Console.WriteLine(mnemonicValue);
        }
Esempio n. 23
0
 public override void Render(MachineInstructionWriter writer, MachineInstructionWriterOptions options)
 {
     writer.WriteMnemonic(
         string.Format("{0}{1}",
                       Mnemonic.ToString(),
                       Annul ? ",a" : ""));
     RenderOperands(writer, options);
 }
Esempio n. 24
0
        static void generateHDWallet()
        {
            var mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve);

            Console.WriteLine("The 12 seed words are : " + mnemonic.ToString());

            var password = "";
            var wallet   = new Wallet(mnemonic.ToString(), password);

            // var account = wallet.GetAccount(0);
            // Console.WriteLine("Address at Index 0 is : " + account.Address + " with private key : "+ account.PrivateKey );
            for (int i = 0; i < 10; i++)
            {
                var account = wallet.GetAccount(i);
                Console.WriteLine("Address at Index " + i + " is : " + account.Address + " with private key : " + account.PrivateKey);
            }
        }
Esempio n. 25
0
        public static string GetMnemonicFromEncrypted(PrivateKeyNotWallet key, Wordlist wordlist, string password, Network network)
        {
            var encryptedString = EncryptedPrivateKeyFormat.Encrypt(key, password, network);
            var encrypted       = Encoders.Base58Check.DecodeData(encryptedString);
            var mnemonic        = new Mnemonic(wordlist, encrypted);

            Debug.Assert(mnemonic.Words.Length == 28);
            return(mnemonic.ToString());
        }
Esempio n. 26
0
        public void AssertGeneratedWalletCredentialsVerifyWithoutPassphrase()
        {
            string   passphrase = "";           // cannot be null
            Mnemonic mnemonic   = WalletController.GenerateMnemonic(passphrase, Network.Main);

            var isVerified = WalletController.VerifyWalletCredentials(mnemonic.ToString(), passphrase, Network.Main);

            Assert.True(isVerified);
        }
Esempio n. 27
0
        public GenerateWalletSuccessViewModel(WalletManagerViewModel owner, Mnemonic mnemonic) : base("Wallet Generated Successfully!")
        {
            _mnemonicWords = mnemonic.ToString();

            ConfirmCommand = ReactiveCommand.Create(() =>
            {
                owner.SelectTestPassword();
            });
        }
Esempio n. 28
0
 private void RenderMnemonic(MachineInstructionRenderer renderer)
 {
     if (!mnemonicNames.TryGetValue(Mnemonic, out string name))
     {
         name = Mnemonic.ToString();
         name = name.Replace('_', '.');
     }
     renderer.WriteMnemonic(name);
 }
Esempio n. 29
0
 private void RenderMnemonic(MachineInstructionWriter writer)
 {
     if (!opcodeNames.TryGetValue(Mnemonic, out string name))
     {
         name = Mnemonic.ToString();
         name = name.Replace('_', '.');
     }
     writer.WriteOpcode(name);
 }
Esempio n. 30
0
 public override void Render(MachineInstructionWriter writer, MachineInstructionWriterOptions options)
 {
     if (!opcodeNames.TryGetValue(Mnemonic, out string name))
     {
         name = Mnemonic.ToString();
     }
     writer.WriteOpcode(name);
     RenderOperands(writer, options);
 }