public void Recover() { string beneficiaryPub = "ak_twR4h7dEcUtc2iSEDv8kB7UFJJDGiEDQCXr85C3fYF8FdVdyo"; BaseKeyPair keyPair = new BaseKeyPair("79816BBF860B95600DDFABF9D81FEE81BDB30BE823B17D80B9E48BE0A7015ADF"); Assert.AreEqual(beneficiaryPub, keyPair.PublicKey); }
public void PaymentSplitContractTest() { Account account = fluentClient.ConstructAccount(baseKeyPair); BaseKeyPair rec1 = BaseKeyPair.Generate(); BaseKeyPair rec2 = BaseKeyPair.Generate(); BaseKeyPair rec3 = BaseKeyPair.Generate(); //map(address, int) Dictionary <string, int> input = new Dictionary <string, int>(); input.Add(rec1.PublicKey, 40); input.Add(rec2.PublicKey, 40); input.Add(rec3.PublicKey, 20); decimal paymentValue = 1m.ToAettos(Unit.AE); string paymentSplitterSource = File.ReadAllText(Path.Combine(ResourcePath, "contracts", "PaymentSplitter.aes"), Encoding.UTF8); Contract contract = account.ConstructContract(paymentSplitterSource); ContractReturn depReturn = contract.MeasureAndDeploy(0, 0, Constants.BaseConstants.MINIMAL_GAS_PRICE, "init", input).WaitForFinish(TimeSpan.FromSeconds(30)); Assert.IsTrue(depReturn.Events.Any(a => a.Name == "AddingInitialRecipients")); ContractReturn callReturn = contract.MeasureAndCall("payAndSplit", Constants.BaseConstants.MINIMAL_GAS_PRICE, (ulong)paymentValue).WaitForFinish(TimeSpan.FromSeconds(30)); Assert.IsTrue(callReturn.Events.Any(a => a.Name == "PaymentReceivedAndSplitted")); Assert.AreEqual(new BigInteger(paymentValue * 0.4m), fluentClient.ConstructAccount(rec1).Balance); Assert.AreEqual(new BigInteger(paymentValue * 0.4m), fluentClient.ConstructAccount(rec2).Balance); Assert.AreEqual(new BigInteger(paymentValue * 0.2m), fluentClient.ConstructAccount(rec3).Balance); }
public void OracleTest() { BaseKeyPair kp = BaseKeyPair.Generate(); Account oracleAccount = fluentClient.ConstructAccount(kp); Account account = fluentClient.ConstructAccount(baseKeyPair); ulong money = (ulong)1m.ToAettos(Unit.AE); bool result = account.SendAmount(oracleAccount.KeyPair.PublicKey, money).WaitForFinish(TimeSpan.FromSeconds(30)); Assert.IsTrue(result); oracleAccount.Refresh(); Assert.AreEqual(oracleAccount.Balance, money); OracleServer <CityQuery, TemperatureResponse> query = oracleAccount.RegisterOracle <CityQuery, TemperatureResponse>().WaitForFinish(TimeSpan.FromSeconds(30)); CityTemperatureService svc = new CityTemperatureService(); svc.Server = query; Task.Factory.StartNew(svc.Start); OracleClient <CityQuery, TemperatureResponse> reg = account.GetOracle <CityQuery, TemperatureResponse>(query.OracleId); TemperatureResponse resp = reg.Ask(new CityQuery { City = "montevideo" }).WaitForFinish(TimeSpan.FromSeconds(300)); Assert.AreEqual(resp.TemperatureCelsius, 24); resp = reg.Ask(new CityQuery { City = "sofia" }).WaitForFinish(TimeSpan.FromSeconds(30)); Assert.AreEqual(resp.TemperatureCelsius, 25); resp = reg.Ask(new CityQuery { City = "hell" }).WaitForFinish(TimeSpan.FromSeconds(30)); Assert.AreEqual(resp.TemperatureCelsius, 2000); svc.Stop(); }
public void GenerateKeyPair() { BaseKeyPair keyPair = BaseKeyPair.Generate(); Assert.IsNotNull(keyPair); Assert.IsTrue(Encoding.IsAddressValid(keyPair.PublicKey)); Assert.IsTrue(keyPair.PublicKey.StartsWith("ak_")); int length = keyPair.PublicKey.Length; Assert.IsTrue(length <= 53 && length >= 51); }
/** * create an unsigned native namepreclaim transaction * * */ public void BuildNativeNamePreclaimTransaction() { string sender = BaseKeyPair.Generate().PublicKey; BigInteger salt = Crypto.GenerateNamespaceSalt(); ulong nonce = 1; ulong ttl = 100; NamePreclaimTransaction namePreclaimTx = nativeClient.CreateNamePreClaimTransaction(sender, validDomain, salt, nonce, ttl); NamePreclaimTransaction namePreclaimTxDebug = debugClient.CreateNamePreClaimTransaction(sender, validDomain, salt, nonce, ttl); UnsignedTx unsignedTxNative = namePreclaimTx.CreateUnsignedTransaction(); UnsignedTx unsignedTx = namePreclaimTxDebug.CreateUnsignedTransaction(); Assert.AreEqual(unsignedTxNative.TX, unsignedTx.TX); }
public void RecoverFromFile() { Configuration cfg = ServiceProvider.GetService <Configuration>(); string walletFileSecret = "aeternity"; string expectedPubKey = "ak_2hSFmdK98bhUw4ar7MUdTRzNQuMJfBFQYxdhN9kaiopDGqj3Cr"; string keystore = File.ReadAllText(Path.Combine(ResourcePath, "keystore.json"), Encoding.UTF8); Keystore store = new Keystore(keystore); byte[] privateKey = store.RecoverPrivateKey(cfg.Argon2Mode, walletFileSecret); BaseKeyPair keyPair = new BaseKeyPair(Hex.ToHexString(privateKey)); Assert.AreEqual(expectedPubKey, keyPair.PublicKey); }
public void InitPS() { paymentSplitterSource = File.ReadAllText(Path.Combine(ResourcePath, "contracts", "PaymentSplitter.aes"), Encoding.UTF8); initialReceiver1 = BaseKeyPair.Generate(); initialReceiver2 = BaseKeyPair.Generate(); initialReceiver3 = BaseKeyPair.Generate(); logger.LogInformation("Initial receiver 1: " + initialReceiver1.PublicKey); logger.LogInformation("Initial receiver 2: " + initialReceiver2.PublicKey); logger.LogInformation("Initial receiver 3: " + initialReceiver3.PublicKey); initialWeights.Add(initialReceiver1.PublicKey, 40); initialWeights.Add(initialReceiver2.PublicKey, 40); initialWeights.Add(initialReceiver3.PublicKey, 20); Assert.AreEqual(3, initialWeights.Count); }
public void PostUpdateTx() { BaseKeyPair keyPair = new BaseKeyPair(TestConstants.BENEFICIARY_PRIVATE_KEY); Account account = nativeClient.GetAccount(keyPair.PublicKey); ulong nonce = account.Nonce + 1; BigInteger salt = Crypto.GenerateNamespaceSalt(); ulong ttl = 0; string domain = TestConstants.DOMAIN + random.Next() + TestConstants.NAMESPACE; /** create a new namespace to update later */ NamePreclaimTransaction namePreclaimTx = nativeClient.CreateNamePreClaimTransaction(keyPair.PublicKey, domain, salt, nonce, ttl); UnsignedTx unsignedTx = namePreclaimTx.CreateUnsignedTransaction(); Tx signedTx = nativeClient.SignTransaction(unsignedTx, keyPair.PrivateKey); PostTxResponse postTxResponse = nativeClient.PostTx(logger, signedTx); Assert.AreEqual(postTxResponse.TXHash, Encoding.ComputeTxHash(signedTx.TX)); BigInteger fee = NameServiceBiding.GetDefaultBidFee(domain); NameClaimTransaction nameClaimTx = nativeClient.CreateNameClaimTransaction(keyPair.PublicKey, domain, salt, fee, Constants.BaseConstants.NAME_FEE, nonce + 1, ttl); UnsignedTx unsignedClaimTx = nameClaimTx.CreateUnsignedTransaction(); Tx signedClaimTx = nativeClient.SignTransaction(unsignedClaimTx, keyPair.PrivateKey); PostTxResponse postClaimTxResponse = nativeClient.PostTx(logger, signedClaimTx); NameEntry nameEntry = nativeClient.GetNameId(domain); ulong initialTTL = nameEntry.Ttl; logger.LogInformation($"Created namespace {domain} with salt {salt} and nameEntry {nameEntry} in tx {postClaimTxResponse.TXHash} for update test"); /** finished creating namespace */ ulong nameTtl = 10000; ulong clientTtl = 50; account = nativeClient.GetAccount(keyPair.PublicKey); nonce = account.Nonce + 1; NameUpdateTransaction nameUpdateTx = nativeClient.CreateNameUpdateTransaction(keyPair.PublicKey, nameEntry.Id, nonce, ttl, clientTtl, nameTtl, new List <NamePointer>()); UnsignedTx unsignedUpdateTx = nameUpdateTx.CreateUnsignedTransaction(); Tx signedUpdateTx = nativeClient.SignTransaction(unsignedUpdateTx, keyPair.PrivateKey); PostTxResponse postUpdateTxResponse = nativeClient.PostTx(logger, signedUpdateTx); Assert.AreEqual(postUpdateTxResponse.TXHash, Encoding.ComputeTxHash(signedUpdateTx.TX)); nameEntry = nativeClient.GetNameId(domain); logger.LogInformation($"Updated namespace {domain} with salt {salt} and nameEntry {nameEntry} in tx {postClaimTxResponse.TXHash} for update test"); ulong updatedTTL = nameEntry.Ttl; // subtract 40000 because initial default ttl is 50000 and updated ttl was 10000 ulong diffTtl = initialTTL - updatedTTL; Assert.IsTrue(diffTtl <= 40000); if (diffTtl < 40000) { logger.LogInformation($"Diff of Ttl is {diffTtl}, this happens when meanwhile new blocks are mined"); } }
public void BuildNativeSpendTransactionTest() { string sender = BaseKeyPair.Generate().PublicKey; string recipient = BaseKeyPair.Generate().PublicKey; BigInteger amount = 1000; string payload = ""; ulong ttl = 100; ulong nonce = 5; SpendTransaction spendTx = nativeClient.CreateSpendTransaction(sender, recipient, amount, payload, ttl, nonce); SpendTransaction spendTxDebug = debugClient.CreateSpendTransaction(sender, recipient, amount, payload, ttl, nonce); UnsignedTx unsignedTxNative = spendTx.CreateUnsignedTransaction(); UnsignedTx unsignedTx = spendTxDebug.CreateUnsignedTransaction(); Assert.AreEqual(unsignedTx.TX, unsignedTxNative.TX); }
public void PostNameClaimTx() { BaseKeyPair keyPair = new BaseKeyPair(TestConstants.BENEFICIARY_PRIVATE_KEY); Account account = nativeClient.GetAccount(keyPair.PublicKey); BigInteger salt = Crypto.GenerateNamespaceSalt(); ulong nonce = account.Nonce + 1; ulong ttl = 0; NamePreclaimTransaction namePreclaimTx = nativeClient.CreateNamePreClaimTransaction(keyPair.PublicKey, validDomain, salt, nonce, ttl); UnsignedTx unsignedTx = namePreclaimTx.CreateUnsignedTransaction(); NamePreclaimTransaction namePreclaimTxDebug = debugClient.CreateNamePreClaimTransaction(keyPair.PublicKey, validDomain, salt, nonce, ttl); UnsignedTx unsignedTxDebug = namePreclaimTxDebug.CreateUnsignedTransaction(); Assert.AreEqual(unsignedTxDebug.TX, unsignedTx.TX); Tx signedTx = nativeClient.SignTransaction(unsignedTx, keyPair.PrivateKey); logger.LogInformation("Signed NamePreclaimTx: " + signedTx.TX); PostTxResponse postTxResponse = nativeClient.PostTx(logger, signedTx); logger.LogInformation("NamePreclaimTx hash: " + postTxResponse.TXHash); Assert.AreEqual(postTxResponse.TXHash, Encoding.ComputeTxHash(signedTx.TX)); BigInteger fee = NameServiceBiding.GetDefaultBidFee(validDomain); NameClaimTransaction nameClaimTx = nativeClient.CreateNameClaimTransaction(keyPair.PublicKey, validDomain, salt, fee, Constants.BaseConstants.NAME_FEE, nonce + 1, ttl); UnsignedTx unsignedClaimTx = nameClaimTx.CreateUnsignedTransaction(); NameClaimTransaction nameClaimTxDebug = debugClient.CreateNameClaimTransaction(keyPair.PublicKey, validDomain, salt, fee, Constants.BaseConstants.NAME_FEE, nonce + 1, ttl); UnsignedTx unsignedClaimTxDebug = nameClaimTxDebug.CreateUnsignedTransaction(); Assert.AreEqual(unsignedClaimTxDebug.TX, unsignedClaimTx.TX); Tx signedClaimTx = nativeClient.SignTransaction(unsignedClaimTx, keyPair.PrivateKey); logger.LogInformation("Signed NameClaimTx: " + signedClaimTx.TX); postTxResponse = nativeClient.PostTx(logger, signedClaimTx); logger.LogInformation($"Using namespace {validDomain} and salt {salt} for committmentId {Encoding.GenerateCommitmentHash(validDomain, salt)}"); logger.LogInformation("NameClaimTx hash: " + postTxResponse.TXHash); }
public static void Init(TestContext context) { IConfiguration cfg = new ConfigurationBuilder().AddJsonFile("appsettings.json", true).AddEnvironmentVariables().Build(); ServiceCollection services = new ServiceCollection(); ILoggerFactory fact = new LoggerFactory(new ILoggerProvider[] { new DebugLoggerProvider() }); Configuration ncfg = new Configuration(fact, cfg); services.AddSingleton(fact); services.AddSingleton(cfg); services.AddSingleton(ncfg); ServiceProvider = services.BuildServiceProvider(); string path = Directory.GetCurrentDirectory(); do { if (!File.Exists(Path.Combine(path, "resources", "keystore.json"))) { int l = path.LastIndexOf(Path.DirectorySeparatorChar); path = l == -1 ? null : path.Substring(0, l); } else { ResourcePath = Path.Combine(path, "resources"); break; } } while (path != null); logger = fact.CreateLogger <BaseTest>(); logger.LogInformation("--------------------------- Using following environment ---------------------------"); logger.LogInformation($"{"baseUrl"}:{ncfg.BaseUrl}"); logger.LogInformation($"{"contractBaseUrl"}:{ncfg.ContractBaseUrl}"); Configuration cf = GetNewConfiguration(); cf.NativeMode = false; cf.Network = Constants.Network.DEVNET; debugClient = new FlatClient(cf); cf = GetNewConfiguration(); cf.NativeMode = true; cf.Network = Constants.Network.DEVNET; nativeClient = new FlatClient(cf); baseKeyPair = new BaseKeyPair(TestConstants.BENEFICIARY_PRIVATE_KEY); fluentClient = new Client(cf); }
/** @param context */ public void PostRevokeTx() { BaseKeyPair keyPair = new BaseKeyPair(TestConstants.BENEFICIARY_PRIVATE_KEY); string nameId = nativeClient.GetNameId(validDomain).Id; Account account = nativeClient.GetAccount(keyPair.PublicKey); ulong nonce = account.Nonce + 1; ulong ttl = 0; NameRevokeTransaction nameRevokeTx = nativeClient.CreateNameRevokeTransaction(keyPair.PublicKey, nameId, nonce, ttl); UnsignedTx unsignedTx = nameRevokeTx.CreateUnsignedTransaction(); Tx signedTx = nativeClient.SignTransaction(unsignedTx, keyPair.PrivateKey); logger.LogInformation("Signed NameRevokeTx: " + signedTx.TX); PostTxResponse postTxResponse = nativeClient.PostTx(logger, signedTx); logger.LogInformation("NameRevokeTx hash: " + postTxResponse.TXHash); Assert.AreEqual(postTxResponse.TXHash, Encoding.ComputeTxHash(signedTx.TX)); Assert.ThrowsException <ApiException <Error> >(() => nativeClient.GetNameIdAsync(validDomain).TimeoutAsync(TestConstants.NUM_TRIALS_DEFAULT).RunAndUnwrap(), "Not Found"); logger.LogInformation("Validated, that namespace {validDomain} is revoked"); }
public void PostSpendTxTest() { // get the currents accounts nonce in case a transaction is already // created and increase it by one Account account = nativeClient.GetAccount(baseKeyPair.PublicKey); BaseKeyPair kp = BaseKeyPair.Generate(); string recipient = kp.PublicKey; BigInteger amount = 1000000000000000000; string payload = ""; ulong ttl = 0; ulong nonce = account.Nonce + 1; SpendTransaction spendTx = nativeClient.CreateSpendTransaction(baseKeyPair.PublicKey, recipient, amount, payload, ttl, nonce); UnsignedTx unsignedTxNative = spendTx.CreateUnsignedTransaction(); Tx signedTx = nativeClient.SignTransaction(unsignedTxNative, baseKeyPair.PrivateKey); PostTxResponse txResponse = nativeClient.PostTransaction(signedTx); logger.LogInformation("SpendTx hash: " + txResponse.TXHash); Assert.AreEqual(txResponse.TXHash, Encoding.ComputeTxHash(signedTx.TX)); }
internal static async Task <Account> CreateAsync(FlatClient client, BaseKeyPair keypair, CancellationToken token = default(CancellationToken)) { Account fac = new Account(); Generated.Models.Account ac = null; try { ac = await client.GetAccountAsync(keypair.PublicKey, token).ConfigureAwait(false); } catch (ApiException <Error> e) { if (!e.Result.Reason.ToLowerInvariant().Contains("not found")) { throw; } } fac.Nonce = ac?.Nonce ?? 0; fac.Balance = ac?.Balance ?? 0; fac.KeyPair = keypair; fac.Client = client; return(fac); }
public Task <Account> ConstructAccountAsync(BaseKeyPair keypair, CancellationToken token = default(CancellationToken)) => Account.CreateAsync(FlatClient, keypair, token);
internal static Account Create(FlatClient client, Generated.Models.Account account, BaseKeyPair keypair) { Account fac = new Account(); fac.Nonce = account?.Nonce ?? 0; fac.Balance = account?.Balance ?? 0; fac.KeyPair = keypair; fac.Client = client; return(fac); }
public Account ConstructAccount(Generated.Models.Account account, BaseKeyPair keypair) => Account.Create(FlatClient, account, keypair);
public static ClientModels.Account ConstructAccount(this Client client, BaseKeyPair keypair) => ClientModels.Account.CreateAsync(client.FlatClient, keypair).RunAndUnwrap();
public void MnemonicTest() { MnemonicKeyPair generatedKeyPair = client.GenerateMasterMnemonicKeyPair(DefaultPassword); MnemonicKeyPair restoredKeyPairWithSamePWD = MnemonicKeyPair.RecoverMnemonicKeyPair(generatedKeyPair.MnemonicSeedWords, DefaultPassword); MnemonicKeyPair restoredKeyPairWithoutPWD = MnemonicKeyPair.RecoverMnemonicKeyPair(generatedKeyPair.MnemonicSeedWords, null); // mnemonic keypair recovered from word seed list is same Assert.AreEqual(Hex.ToHexString(generatedKeyPair.PrivateKey), Hex.ToHexString(restoredKeyPairWithSamePWD.PrivateKey)); // mnemonic keypair recovered from word seed list without password is not same Assert.AreNotEqual(Hex.ToHexString(generatedKeyPair.PrivateKey), Hex.ToHexString(restoredKeyPairWithoutPWD.PrivateKey)); // mnemonic keypair cannot be generated due to small entropy Configuration cfg = GetNewConfiguration(); cfg.EntropySizeInByte = 2; FlatClient cl = new FlatClient(cfg); Assert.ThrowsException <AException>(() => cl.GenerateMasterMnemonicKeyPair(null)); // default vector recover test List <string> mnemonic = new List <string> { "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "about" }; string privateKeyAsHex = "61ae3ed32d9c82749be2f4bf122ea01de434705de3662ed416394df9be045ea9d8607b3a21a3d35529c0f4f60c7f3ddc782ce928d73dae02b0aad92ba38bd94f"; string publicKeyAsHex = "ak_2eJ4Jk8F9yc1Hn4icG2apyExwrXcxZZADYLGDiMkyfoSpPSEM3"; MnemonicKeyPair restoredDefault = MnemonicKeyPair.RecoverMnemonicKeyPair(mnemonic, DefaultPassword); BaseKeyPair restoredBaseKeyPair = Encoding.CreateBaseKeyPair(restoredDefault.ToRawKeyPair()); Assert.AreEqual(publicKeyAsHex, restoredBaseKeyPair.PublicKey); Assert.AreEqual(privateKeyAsHex, restoredBaseKeyPair.PrivateKey); // hd derivation keys restore test mnemonic = new List <string> { "legal", "winner", "thank", "year", "wave", "sausage", "worth", "useful", "legal", "winner", "thank", "yellow" }; MnemonicKeyPair master = MnemonicKeyPair.RecoverMnemonicKeyPair(mnemonic, DefaultPassword); MnemonicKeyPair masterNoPWD = MnemonicKeyPair.RecoverMnemonicKeyPair(mnemonic, ""); Dictionary <string, string> derivedKeys = File.ReadAllLines(Path.Combine(ResourcePath, "derivedKeys.properties")).Select(a => a.Split('=')).ToDictionary(a => a[0], a => a[1]); /** * make sure every that derived keys can be restored and that the hardened * keys differ */ for (int i = 0; i < 20; i++) { // derive different keys BaseKeyPair generatedDerivedKey = Encoding.CreateBaseKeyPair(master.DerivedKey(true).ToRawKeyPair()); BaseKeyPair notHardendedKey = Encoding.CreateBaseKeyPair(master.DerivedKey(false).ToRawKeyPair()); BaseKeyPair generatedDerivedKeyNoPwd = Encoding.CreateBaseKeyPair(masterNoPWD.DerivedKey(true).ToRawKeyPair()); BaseKeyPair generatedDerivedKeyWithCustomPath = Encoding.CreateBaseKeyPair(master.DerivedKey(true, "4711'/4712'").ToRawKeyPair()); // assert that the generated keys are the same Assert.AreEqual(derivedKeys[generatedDerivedKey.PublicKey], generatedDerivedKey.PrivateKey); // make sure, not hardended keys differ Assert.ThrowsException <KeyNotFoundException>(() => derivedKeys[notHardendedKey.PublicKey]); // make sure, keys derived from master with same mnemonics but different pwd // are different Assert.ThrowsException <KeyNotFoundException>(() => derivedKeys[generatedDerivedKeyNoPwd.PublicKey]); // make sure, keys from other derivation path differ Assert.ThrowsException <KeyNotFoundException>(() => derivedKeys[generatedDerivedKeyWithCustomPath.PublicKey]); } // hd derivation keys not possible from derived key test" mnemonic = new List <string> { "letter", "advice", "cage", "absurd", "amount", "doctor", "acoustic", "avoid", "letter", "advice", "cage", "above" }; master = MnemonicKeyPair.RecoverMnemonicKeyPair(mnemonic, DefaultPassword); MnemonicKeyPair generatedDerivedKey2 = master.DerivedKey(true); Assert.ThrowsException <AException>(() => generatedDerivedKey2.DerivedKey(true), "Given mnemonicKeyPair object does not contain the master key"); }