public void AccountKey_Success()
        {
            AccountKey result = new AccountKey(LedgerPath.Parse("/path/"), LedgerPath.Parse("/asset/"));

            Assert.Equal("/path/", result.Account.FullPath);
            Assert.Equal("/asset/", result.Asset.FullPath);
        }
Example #2
0
        public AccountStatus(AccountKey accountKey, long amount, ByteString version)
        {
            if (accountKey == null)
                throw new ArgumentNullException(nameof(accountKey));

            if (version == null)
                throw new ArgumentNullException(nameof(version));

            this.AccountKey = accountKey;
            this.Balance = amount;
            this.Version = version;
        }
        private static async Task <AcmeProtocolClient> CreateAcmeClientAsync()
        {
            var account    = default(AccountDetails);
            var accountKey = default(AccountKey);
            var acmeDir    = default(ServiceDirectory);

            LoadState(ref account, "account.json");
            LoadState(ref accountKey, "account_key.json");
            LoadState(ref acmeDir, "directory.json");

            var acme = new AcmeProtocolClient(_acmeHttpClient, acmeDir, account, accountKey?.GenerateSigner());

            if (acmeDir == null)
            {
                acmeDir = await acme.GetDirectoryAsync();

                SaveState(acmeDir, "directory.json");

                acme.Directory = acmeDir;
            }

            await acme.GetNonceAsync();

            if (account == null || accountKey == null)
            {
                account = await acme.CreateAccountAsync(new[] { "mailto:" + Settings.Default.Contacts }, true);

                accountKey = new AccountKey
                {
                    KeyType   = acme.Signer.JwsAlg,
                    KeyExport = acme.Signer.Export()
                };

                SaveState(account, "account.json");
                SaveState(accountKey, "account_key.json");

                acme.Account = account;
            }

            return(acme);
        }
        public async Task RunAccountFlow(KeyAlgorithm algorithm)
        {
            var dirUri = await IntegrationHelper.GetAcmeUriV1();

            var key = new AccountKey(algorithm);

            using (var client = new AcmeClient(IntegrationHelper.GetAcmeHttpHandler(dirUri)))
            {
                client.Use(key.Export());
                var reg = await client.NewRegistraton();

                reg.Data.Agreement = reg.GetTermsOfServiceUri();

                await client.UpdateRegistration(reg);

                var newKey = new AccountKey().Export();
                await client.ChangeKey(reg, newKey);

                await client.DeleteRegistration(reg);
            }
        }
Example #5
0
 public override void SaveToStream(Stream s)
 {
     using (BinaryWriter bw = new BinaryWriter(s, Encoding.ASCII, true))
     {
         bw.Write((uint)SignerAccount);
         bw.Write(NumberOfOperations);
         bw.Write((uint)TargetAccount);
         bw.Write(Amount);
         bw.Write(Fee);
         Payload.SaveToStream(bw);
         AccountKey.SaveToStream(s, false);
         if (TransactionStyle == TransferType.BuyAccount || TransactionStyle == TransferType.TransactionAndBuyAccount)
         {
             bw.Write((byte)TransactionStyle);
             bw.Write(AccountPrice);
             bw.Write((uint)SellerAccount);
             NewAccountKey.SaveToStream(s, false);
         }
         Signature.SaveToStream(s);
     }
 }
Example #6
0
        private static async Task TestAccountChange(PermissionSet accountPermissions, long previousBalance, long newBalance)
        {
            PermissionBasedValidator validator = CreateValidator(
                new string[0],
                new Dictionary <string, PermissionSet>()
            {
                ["/"]   = PermissionSet.Unset,
                ["/a/"] = accountPermissions
            });

            Dictionary <AccountKey, AccountStatus> accounts = new Dictionary <AccountKey, AccountStatus>()
            {
                [AccountKey.Parse("/a/", "/b/")] = new AccountStatus(AccountKey.Parse("/a/", "/b/"), previousBalance, ByteString.Empty)
            };

            ParsedMutation mutation = new ParsedMutation(
                new[] { new AccountStatus(AccountKey.Parse("/a/", "/b/"), newBalance, ByteString.Empty) },
                new KeyValuePair <RecordKey, ByteString> [0]);

            await validator.Validate(mutation, new SignatureEvidence[0], accounts);
        }
Example #7
0
        public async void Account_GetBillingSummary_valid()
        {
            // Arrange
            MockHttpMessageHandler mockHttp = MockTools.GetNewMockHandler();

            mockHttp.When(HttpMethod.Get, "*/billing").Respond(HttpStatusCode.OK, "application/json", JsonConvert.SerializeObject(CorrectBillingSummary));

            AccountKey accKey = new AccountKey();

            accKey.SetToken("17989543-2154-6867-3566-71474693165007735103-0594-4591-2132-259238857481", mockHttp);

            Account account = new Account(accKey);

            // Act
            BillingSummary summary = await account.GetBillingSummary();

            // Assert
            Assert.Equal(CorrectBillingSummary.Balance, summary.Balance);
            Assert.Equal(CorrectBillingSummary.BillingRecords.Length, summary.BillingRecords.Length);
            Assert.Equal(CorrectBillingSummary.BillingRecords[0].Timestamp, summary.BillingRecords[0].Timestamp);
        }
        public async Task <UserKeyPair> CurrentKeyPairAsync()
        {
            if (string.IsNullOrEmpty(_apiClient.Identity.User))
            {
                throw new InvalidOperationException("The account service requires a user.");
            }

            try
            {
                AccountKey accountKey = await _apiClient.MyAccountKeysCurrentAsync().Free();

                if (accountKey == null)
                {
                    return(null);
                }
                return(accountKey.ToUserKeyPair(Identity.Passphrase));
            }
            catch (UnauthorizedException uaex)
            {
                throw new PasswordException("Credentials are not valid for server access.", uaex);
            }
        }
Example #9
0
        internal void SaveToStream(BinaryWriter bw, bool writeLengths = true)
        {
            ushort len = 0;
            long   pos = bw.BaseStream.Position;

            if (writeLengths)
            {
                bw.Write(len);
            }
            switch (State)
            {
            case AccountState.Normal:
                AccountKey.SaveToStream(bw.BaseStream, false);
                break;

            case AccountState.Sale:
                bw.Write((ushort)1000);
                AccountKey.SaveToStream(bw.BaseStream, false);
                bw.Write(LockedUntilBlock);
                bw.Write(Price);
                bw.Write(AccountToPayPrice);
                NewPublicKey.SaveToStream(bw.BaseStream, false);
                break;

            case AccountState.Unknown:
                break;

            default: throw new Exception("Invalid account state");
            }
            long size    = bw.BaseStream.Position - pos - 2;
            long reverse = bw.BaseStream.Position;

            bw.BaseStream.Position = pos;
            if (writeLengths)
            {
                bw.Write((ushort)size);
            }
            bw.BaseStream.Position = reverse;
        }
Example #10
0
        public void GivenValidUploadOption_WhenBuild_ShouldSucceed()
        {
            var tempZipFile = Path.Combine(Path.GetTempPath(), "zipFile1.mlPackage");

            File.WriteAllText(tempZipFile, "hello");

            try
            {
                var args = new string[]
                {
                    "upload",
                    $"PackageFile={tempZipFile}",
                    "modelName=ml-model-temp",
                    "VersionId=v10-0-0-1",
                    "Store:ContainerName=containerName",
                    "Store:AccountName=accountName",
                    "Store:AccountKey=dummyKey",
                };

                IOption option = new OptionBuilder()
                                 .SetArgs(args)
                                 .Build();

                option.Upload.Should().BeTrue();
                option.PackageFile.Should().Be(tempZipFile);
                option.ModelName.Should().Be("ml-model-temp");
                option.VersionId.Should().Be("v10-0-0-1");

                option.Store.Should().NotBeNull();
                option.Store !.ContainerName.Should().Be("containerName");
                option.Store !.AccountName.Should().Be("accountName");
                option.Store !.AccountKey.Should().Be("dummyKey");
            }
            finally
            {
                File.Delete(tempZipFile);
            }
        }
        private async Task EnsureClient()
        {
            var caUri = new Uri(config.CertAuthorityUrl);

            var account = await accountStore.GetAccountAsync();

            if (account != null && account.Account.Kid.Contains(caUri.Host) == false)
            {
                logger.LogWarning("Fetched account KID doesn't contain CA host, ignoring fetched account");
                account = null;
            }

            var client = new AcmeProtocolClient(caUri, null, account?.Account, account?.Signer, usePostAsGet: true, logger: logger);

            client.Directory = await client.GetDirectoryAsync();

            // get nonce, used to communicate w/ server
            await client.GetNonceAsync();

            if (account == null)
            {
                // make request to create account
                var contactEmails = new[] { "mailto:" + config.ContactEmail };
                var newAccount    = await client.CreateAccountAsync(contactEmails, termsOfServiceAgreed : true);

                var accountKey = new AccountKey
                {
                    KeyType   = client.Signer.JwsAlg,
                    KeyExport = client.Signer.Export()
                };

                await accountStore.StoreAccountAsync(newAccount, accountKey);

                client.Account = newAccount;
            }

            this.client = client;
        }
Example #12
0
 internal override void SaveToStream(Stream s)
 {
     base.SaveToStream(s);
     using (MemoryStream ms = new MemoryStream())
     {
         using (BinaryWriter bw = new BinaryWriter(ms, Encoding.Default, true))
         {
             bw.Write(ServerPort);
             AccountKey.SaveToStream(ms);
             bw.Write(Timestamp);
             Block.SaveToStream(ms);
             NodeServers.SaveToStream(ms);
             Version.SaveToStream(bw);
             bw.Write(WorkSum);
         }
         DataLength = (int)ms.Length;
         using (BinaryWriter bw = new BinaryWriter(s, Encoding.Default, true))
         {
             bw.Write(DataLength);
         }
         ms.Position = 0;
         ms.CopyTo(s);
     }
 }
Example #13
0
        public async Task Validate_ComputeAddress()
        {
            PermissionBasedValidator validator = CreateValidator(
                new string[] { "0123456789abcdef11223344" },
                new Dictionary <string, PermissionSet>()
            {
                ["/"]   = PermissionSet.Unset,
                ["/a/"] = PermissionSet.AllowAll
            });

            Dictionary <AccountKey, AccountStatus> accounts = new Dictionary <AccountKey, AccountStatus>()
            {
                [AccountKey.Parse("/a/", "/b/")] = new AccountStatus(AccountKey.Parse("/a/", "/b/"), 150, ByteString.Empty)
            };

            ParsedMutation mutation = new ParsedMutation(
                new[] { new AccountStatus(AccountKey.Parse("/a/", "/b/"), 100, ByteString.Empty) },
                new KeyValuePair <RecordKey, ByteString>[] { });

            await validator.Validate(
                mutation,
                new[] { new SignatureEvidence(ByteString.Parse("0123456789abcdef"), ByteString.Parse("11223344")) },
                accounts);
        }
 async Task<long> GetAccountBalance(string account, string asset)
 {
     var lAsset = LedgerPath.Parse(asset);
     var aFrom = new AccountKey(LedgerPath.Parse(account), lAsset);
     var r = await Engine.GetAccounts(new[] { aFrom });
     return r[aFrom].Balance;
 }
        public async Task SetAccountAsync(Account value)
        {
            this.accountInitialized = true;

            if (!AccountKey.KeyComparer.Equals(this.accountKey, value))
            {
                this.accountKey = value;
                this.IsAuthenticated = value != null && !value.NeedsReauthentication;

                await this.authenticationManager.SetCurrentVSAccountAsync(value);
                this.OnAuthenticationChanged();
            }
        }
        public void AccountKey_Invalid_token(string apiKey)
        {
            AccountKey          accKey    = null;
            BunnyTokenException exception = Assert.Throws <BunnyTokenException>(() => { accKey = new AccountKey(apiKey); });

            Assert.Equal(apiKey, exception.Token);
            Assert.Equal("Account token is invalid!", exception.Message);
            Assert.Null(accKey);
        }
        public void AccountKey_Valid_token(string apiKey)
        {
            AccountKey accKey = new AccountKey(apiKey);

            Assert.Equal(apiKey, accKey.Token);
        }
 /// <summary>
 /// Verify required values are present
 /// </summary>
 public void Verify()
 {
     ConnectionString.VerifyNotEmpty(nameof(ConnectionString));
     AccountKey.VerifyNotEmpty(nameof(AccountKey));
     DatabaseName.VerifyNotEmpty(nameof(DatabaseName));
 }
Example #19
0
        public void Account_Invalid_StorageKey(AccountKey accKey)
        {
            BunnyTokenException exception = Assert.Throws <BunnyTokenException>(() => { new Account(accKey); });

            Assert.Equal("Invalid AccountKey provided!", exception.Message);
        }
        public async Task <string> PublicKeyAsync(string email)
        {
            AccountKey accountKey = await _client.GetPublicApiKeyAllAccountsOtherUserPublicKeyAsync(email);

            return(accountKey.KeyPair.PublicPem);
        }
        public void AccountStatus_ArgumentNullException()
        {
            ArgumentNullException exception;

            exception = Assert.Throws <ArgumentNullException>(() => new AccountStatus(null, 1, ByteString.Parse("ab")));
            Assert.Equal("accountKey", exception.ParamName);

            exception = Assert.Throws <ArgumentNullException>(() => new AccountStatus(AccountKey.Parse("/account/", "/asset/"), 1, null));
            Assert.Equal("version", exception.ParamName);
        }
 public static async Task<AccountStatus> GetAccount(this IStorageEngine store, AccountKey account)
 {
     return (await store.GetAccounts(new[] { account })).First().Value;
 }
 public AccountKeyResponse()
 {
     KeyPair = new AccountKey[0];
 }
Example #24
0
        private void VerifyCredentials(object sender, EventArgs e)
        {
            var name           = ServiceName.Text;
            var invalidCharHit = false;

            foreach (var character in PathConsts.InvalidCharacters)
            {
                if (name?.Contains(character) == true)
                {
                    invalidCharHit = true;
                }
            }
            if (string.IsNullOrEmpty(name) || invalidCharHit)
            {
                this.ShowWarning(this.Localize("Online.BadName"), this.Localize("Online.IllegalName"), () => {
                    ServiceName.BecomeFirstResponder();
                });
                return;
            }

            var endpoint = EndpointSuffix.Text;

            if (string.IsNullOrEmpty(endpoint))
            {
                this.ShowWarning(this.Localize("Online.BadCredential"), this.Localize("Azure.BadEndpoint"), () => {
                    EndpointSuffix.BecomeFirstResponder();
                });
                return;
            }

            var accountName = AccountName.Text;

            var accessKey = AccountKey.Text;

            if (string.IsNullOrEmpty(accessKey))
            {
                this.ShowWarning(this.Localize("Online.BadCredential"), this.Localize("Azure.BadAccountKey"), () => {
                    AccountKey.BecomeFirstResponder();
                });
                return;
            }

            var container = Container.Text;

            if (string.IsNullOrEmpty(container))
            {
                this.ShowWarning(this.Localize("Online.BadCredential"), this.Localize("Azure.BadContainer"), () => {
                    Container.BecomeFirstResponder();
                });
                return;
            }

            if (!Globals.Database.IsStorageNameUnique(name))
            {
                this.ShowWarning(this.Localize("Online.ServiceAlreadyExists"), this.Localize("Online.ChooseADifferentName"), () => {
                    ServiceName.BecomeFirstResponder();
                });
                return;
            }

            string connection;

            if (endpoint.Contains(accountName, StringComparison.Ordinal))
            {
                accountName = null;
            }
            if (endpoint.StartsWith("http://", StringComparison.Ordinal))
            {
                endpoint = endpoint.Replace("http://", "https://");
            }
            if (endpoint.StartsWith("https://", StringComparison.Ordinal))
            {
                if (string.IsNullOrEmpty(accountName))
                {
                    if (string.IsNullOrEmpty(accessKey))
                    {
                        connection = endpoint;
                    }
                    else
                    {
                        connection = $"BlobEndpoint={endpoint};SharedAccessSignature={accessKey}";
                    }
                }
                else
                {
                    this.ShowError(this.Localize("Azure.BadAccount"), this.Localize("Azure.EndpointAndNameMismatch"));
                    return;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(accountName))
                {
                    this.ShowError(this.Localize("Online.BadCredential"), this.Localize("Azure.BadAccountName"));
                    return;
                }
                else
                {
                    connection = $"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accessKey};EndpointSuffix={endpoint}";
                }
            }

            var hud = MBProgressHUD.ShowHUD(NavigationController.View, true);

            hud.Label.Text = this.Localize("Online.Verifying");

            Task.Run(() => {
                var config = new AzureBlobConfig {
                    ConnectionString = connection,
                    BlobName         = container
                };

                if (config.Verify())
                {
                    try
                    {
                        Globals.CloudManager.AddStorageProvider(Globals.CloudManager.PersonalClouds[0].Id, Guid.NewGuid(), name, config, visibility);
                        InvokeOnMainThread(() => {
                            hud.Hide(true);
                            NavigationController.DismissViewController(true, null);
                        });
                    }
                    catch
                    {
                        InvokeOnMainThread(() => {
                            hud.Hide(true);
                            this.ShowError(this.Localize("Azure.CannotAddService"), this.Localize("Error.Internal"));
                        });
                    }
                }
                else
                {
                    InvokeOnMainThread(() => {
                        hud.Hide(true);
                        this.ShowError(this.Localize("Error.Authentication"), this.Localize("Azure.Unauthorized"));
                    });
                }
            });
        }
 [InlineData("A3-RTN9SA-DY9445Y-FF96X6E7B-GPFA95R9")]  // Too short for A3 after removing of "-"
 public void Parse_throws_on_invalid_key_format(string key)
 {
     Exceptions.AssertThrowsInternalError(() => AccountKey.Parse(key), "Invalid account key");
 }
        private void VerifyCredentials(object sender, EventArgs e)
        {
            var name           = ServiceName.Text;
            var invalidCharHit = false;

            foreach (var character in VirtualFileSystem.InvalidCharacters)
            {
                if (name?.Contains(character) == true)
                {
                    invalidCharHit = true;
                }
            }
            if (string.IsNullOrEmpty(name) || invalidCharHit)
            {
                this.ShowAlert(this.Localize("Online.BadName"), this.Localize("Online.IllegalName"), action => {
                    ServiceName.BecomeFirstResponder();
                });
                return;
            }

            var endpoint = EndpointSuffix.Text;

            if (string.IsNullOrEmpty(endpoint))
            {
                this.ShowAlert(this.Localize("Online.BadCredential"), this.Localize("Azure.BadEndpoint"), action => {
                    EndpointSuffix.BecomeFirstResponder();
                });
                return;
            }

            var accountName = AccountName.Text;

            /*
             * if (string.IsNullOrEmpty(accountName) &&
             *  (endpoint == "core.windows.net" || endpoint == "blob.core.windows.net" ||
             *  endpoint == "core.chinacloudapi.cn" || endpoint == "blob.core.chinacloudapi.cn"))
             * {
             *  this.ShowAlert(this.Localize("Online.BadCredential"), this.Localize("Azure.BadAccountName"), action => {
             *      AccountName.BecomeFirstResponder();
             *  });
             *  return;
             * }
             */

            var accessKey = AccountKey.Text;

            if (string.IsNullOrEmpty(accessKey))
            {
                this.ShowAlert(this.Localize("Online.BadCredential"), this.Localize("Azure.BadAccountKey"), action => {
                    AccountKey.BecomeFirstResponder();
                });
                return;
            }

            var container = Container.Text;

            if (string.IsNullOrEmpty(container))
            {
                this.ShowAlert(this.Localize("Online.BadCredential"), this.Localize("Azure.BadContainer"), action => {
                    Container.BecomeFirstResponder();
                });
                return;
            }

            if (!Globals.Database.IsStorageNameUnique(name))
            {
                this.ShowAlert(this.Localize("Online.ServiceAlreadyExists"), this.Localize("Online.ChooseADifferentName"), action => {
                    ServiceName.BecomeFirstResponder();
                });
                return;
            }

            string connection;

            if (endpoint.Contains(accountName, StringComparison.Ordinal))
            {
                accountName = null;
            }
            if (endpoint.StartsWith("http://", StringComparison.Ordinal))
            {
                endpoint = endpoint.Replace("http://", "https://");
            }
            if (endpoint.StartsWith("https://", StringComparison.Ordinal))
            {
                if (string.IsNullOrEmpty(accountName))
                {
                    if (string.IsNullOrEmpty(accessKey))
                    {
                        connection = endpoint;
                    }
                    else
                    {
                        connection = $"BlobEndpoint={endpoint};SharedAccessSignature={accessKey}";
                    }
                }
                else
                {
                    this.ShowAlert(this.Localize("Azure.BadAccount"), this.Localize("Azure.EndpointAndNameMismatch"));
                    return;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(accountName))
                {
                    this.ShowAlert(this.Localize("Online.BadCredential"), this.Localize("Azure.BadAccountName"));
                    return;
                }
                else
                {
                    connection = $"DefaultEndpointsProtocol=https;AccountName={accountName};AccountKey={accessKey};EndpointSuffix={endpoint}";
                }
            }

            var alert = UIAlertController.Create(this.Localize("Online.Verifying"), null, UIAlertControllerStyle.Alert);

            PresentViewController(alert, true, () => {
                Task.Run(() => {
                    var config = new AzureBlobConfig {
                        ConnectionString = connection,
                        BlobName         = container
                    };

                    if (config.Verify())
                    {
                        try
                        {
                            Globals.CloudManager.AddStorageProvider(Globals.CloudManager.PersonalClouds[0].Id, Guid.NewGuid(), name, config, visibility);
                            InvokeOnMainThread(() => {
                                DismissViewController(true, () => {
                                    NavigationController.DismissViewController(true, null);
                                });
                            });
                        }
                        catch
                        {
                            InvokeOnMainThread(() => {
                                DismissViewController(true, () => {
                                    this.ShowAlert(this.Localize("Azure.CannotAddService"), this.Localize("Error.Internal"));
                                });
                            });
                        }
                    }
                    else
                    {
                        InvokeOnMainThread(() => {
                            DismissViewController(true, () => {
                                this.ShowAlert(this.Localize("Error.Authentication"), this.Localize("Azure.Unauthorized"));
                            });
                        });
                    }
                });
            });
        }
        private async Task TransfertInternal(string from, string to, long amount, string asset)
        {
            var lAsset = LedgerPath.Parse(asset);
            var aFrom = new AccountKey(LedgerPath.Parse(from), lAsset);
            var aTo = new AccountKey(LedgerPath.Parse(to), lAsset);
            var accounts = await Engine.GetAccounts(new[] { aFrom, aTo });
            var adFrom = accounts[aFrom];
            var adTo = accounts[aTo];

            var rFrom = new Record(aFrom.Key.ToBinary(), LongToByteString(adFrom.Balance - amount), adFrom.Version);
            var rTo = new Record(aTo.Key.ToBinary(), LongToByteString(adTo.Balance + amount), adTo.Version);

            Mutation m = new Mutation(ByteString.Empty, new[] { rFrom, rTo }, ByteString.Empty);

            int c = System.Threading.Interlocked.Increment(ref gcounter);

            Transaction t = new Transaction(
                new ByteString(MessageSerializer.SerializeMutation(m)),
                DateTime.UtcNow,
                new ByteString(BitConverter.GetBytes(c))
            );

            await Engine.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(t)) });
            //Output.WriteLine($"{prefix} - {from} ==> {to} Success Retry : {tryCount}");
        }
Example #28
0
 public void GetHashCode_Success()
 {
     Assert.Equal(AccountKey.Parse("/abc/", "/def/").GetHashCode(), AccountKey.Parse("/abc/", "/def/").GetHashCode());
 }
Example #29
0
 public void Equals_Object()
 {
     Assert.True(AccountKey.Parse("/abc/", "/def/").Equals((object)AccountKey.Parse("/abc/", "/def/")));
 }
        public async Task StoreAccountAsync(AccountDetails details, AccountKey key)
        {
            await this.secretClient.SetSecretAsync(AccountDetailsSecret, JsonConvert.SerializeObject(details));

            await this.secretClient.SetSecretAsync(AccountKeySecret, JsonConvert.SerializeObject(key));
        }