public async Task AnnounceTransferTransactionWithMosaicWithMessage()
        {
            var keyPair = KeyPair.CreateFromPrivateKey(Config.PrivateKeyMain);

            var account = new Account("E45030D2A22D97FDC4C78923C4BBF7602BBAC3B018FFAD2ED278FB49CD6F218C", NetworkType.Types.MIJIN_TEST);

            var transaction = TransferTransaction.Create(
                NetworkType.Types.MIJIN_TEST,
                Deadline.CreateHours(2),
                account.Address,
                new List <Mosaic> {
                Mosaic.CreateFromIdentifier("nem:xem", 100000000000)
            },
                PlainMessage.Create("hello")
                ).SignWith(keyPair);

            listener.TransactionStatus(Address.CreateFromPublicKey(transaction.Signer, NetworkType.Types.MIJIN_TEST))
            .Subscribe(e =>
            {
                Console.WriteLine(e.Status);
            });

            await new TransactionHttp("http://" + Config.Domain + ":3000").Announce(transaction);

            var status = await listener.ConfirmedTransactionsGiven(Address.CreateFromPublicKey(transaction.Signer, NetworkType.Types.MIJIN_TEST)).Take(1);

            Assert.AreEqual(keyPair.PublicKeyString, status.Signer.PublicKey);
        }
Ejemplo n.º 2
0
        public static async Task getResponse()
        {
            try
            {
                Account account = Account.CreateFromPrivateKey("5cd5a454be8045056bd3c5e67c20dea92a8eb4921351d850f0249983a804a903", NetworkType.Types.TEST_NET);
                KeyPair keyPair = account.KeyPair;


                var transaction = TransferTransaction.Create(
                    NetworkType.Types.TEST_NET,
                    Deadline.CreateHours(2),
                    Address.CreateFromEncoded("TB2Z7J-R2K3BZ-2TRS6D-H5747F-Y3XKUM-BNWCI4-BPDJ"),
                    new List <Mosaic> {
                    Xem.CreateRelative(10)
                },
                    PlainMessage.Create("Well shit. W/ mosaic")
                    );


                SignedTransaction signedTransaction = transaction.SignWith(keyPair);

                TransactionResponse response = await new TransactionHttp("http://" + Config.Domain + ":7890").Announce(signedTransaction);
                Console.WriteLine(response.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
        public async Task AnnounceMultisigTransaction()
        {
            var cosignatory     = KeyPair.CreateFromPrivateKey("8db858dcc8e2827074498204b3829154ec4c4f24d13738d3f501003b518ef256");
            var multisigAccount = PublicAccount.CreateFromPublicKey("29c4a4aa674953749053c8a35399b37b713dedd5d002cb29b3331e56ff1ea65a", NetworkType.Types.TEST_NET);
            var recipient       = new Account("E45030D2A22D97FDC4C78923C4BBF7602BBAC3B018FFAD2ED278FB49CD6F218C", NetworkType.Types.TEST_NET);

            var transaction = TransferTransaction.Create(
                NetworkType.Types.TEST_NET,
                Deadline.CreateHours(2),
                recipient.Address,
                new List <Mosaic> {
                Mosaic.CreateFromIdentifier("nem:xem", 1000000)
            },
                PlainMessage.Create("hello")
                );

            var multisigTransaction = MultisigTransaction.Create(
                NetworkType.Types.TEST_NET,
                Deadline.CreateHours(1),
                transaction
                ).SignWith(cosignatory, multisigAccount);

            var response = await new TransactionHttp("http://" + Config.Domain + ":7890").Announce(multisigTransaction);

            Assert.AreEqual("SUCCESS", response.Message);
        }
Ejemplo n.º 4
0
        private static IMessage GetMessage(JObject msg)
        {
            try
            {
                var msgType = msg["type"].ToObject <int>();
                var payload = msg["payload"].ToObject <string>().FromHex();

                switch (MessageTypeExtension.GetRawValue(msgType))
                {
                case MessageType.PLAIN_MESSAGE:
                    if (payload.Length <= 0)
                    {
                        return(EmptyMessage.Create());
                    }
                    return(PlainMessage.Create(Encoding.UTF8.GetString(payload)));

                case MessageType.SECURED_MESSAGE:
                    return(SecureMessage.CreateFromEncodedPayload(payload));

                default:
                    return(EmptyMessage.Create());
                }
            }
            catch (Exception)
            {
                return(EmptyMessage.Create());
            }
        }
Ejemplo n.º 5
0
        public async Task <object> TestingTransfer(string from, string privateKey, string to, IAsset asset, decimal amount)
        {
            var nodeHttp    = new NodeHttp(_nemUrl);
            var networkType = await nodeHttp.GetNetworkType();

            var networkTime    = (int)(await nodeHttp.GetExtendedNodeInfo()).NisInfo.CurrentTime;
            var toAddressParts = to.Split(AddressSeparator);
            var message        = toAddressParts.Length > 1
                ? PlainMessage.Create(toAddressParts[1]) as IMessage
                : EmptyMessage.Create();
            var mosaic = Mosaic.CreateFromIdentifier(asset.AssetId, (ulong)asset.ToBaseUnit(amount));
            var fee    = await TransferTransaction.CalculateFee(networkType, message, new[] { mosaic }, new NamespaceMosaicHttp(_nemUrl));

            var tx = TransferTransaction.Create(
                networkType,
                new Deadline(networkTime + _expiresInSeconds),
                fee.fee,
                Address.CreateFromEncoded(toAddressParts[0]),
                new List <Mosaic> {
                mosaic
            },
                message,
                networkTime);
            var signed = tx.SignWith(KeyPair.CreateFromPrivateKey(privateKey));
            var result = await new TransactionHttp(_nemUrl).Announce(signed);

            return(result);
        }
        public static async System.Threading.Tasks.Task CreateTransactionAsync(int xpxAmount, List <Account> recipients)
        {
            foreach (var recipient in recipients)
            {
                var client              = new SiriusClient("http://bctestnet1.brimstone.xpxsirius.io:3000");
                var networkType         = client.NetworkHttp.GetNetworkType().Wait();
                var mosaicToTransfer    = NetworkCurrencyMosaic.CreateRelative((ulong)xpxAmount);
                var transferTransaction = TransferTransaction.Create(
                    Deadline.Create(),
                    recipient.Address,
                    new List <Mosaic>()
                {
                    mosaicToTransfer
                },
                    PlainMessage.Create("Transfered " + xpxAmount.ToString() + " successfully."),
                    NetworkType.TEST_NET
                    );


                var generationHash = await client.BlockHttp.GetGenerationHash();

                var signedTransaction = senderAccount.Sign(transferTransaction, generationHash);
                await client.TransactionHttp.Announce(signedTransaction);

                var newAccountInfo = await client.AccountHttp.GetAccountInfo(senderAccount.Address);

                Console.WriteLine("Sent " + Convert.ToInt32(xpxAmount) + " XPX to: \n");
                Console.WriteLine($"{nameof(newAccountInfo)} : {newAccountInfo}");
            }
        }
        public async Task Should_Serialize_And_Sign_TransactionAsync()
        {
            var account2 = Account.CreateFromPrivateKey("D54AC0CB0FF50FB44233782B3A6B5FDE2F1C83B9AE2F1352119F93713F3AB923", NetworkType.TEST_NET);
            // var nonce = MosaicNonce.CreateRandom();
            var account = Account.CreateFromPrivateKey("feab2970d23c9a6f0170adf9b846575831c63084bcf1f0d7e70644818c546017", NetworkType.TEST_NET);
            // var mosaicId = MosaicId.CreateFromNonce(nonce, account.PublicAccount.PublicKey);
            var mosaicToTransfer = NetworkCurrencyMosaic.CreateRelative(1000);

            var transferTransaction = TransferTransaction.Create(Deadline.Create(),
                                                                 Recipient.From(Address.CreateFromRawAddress("VDVLDGVUEZ2X2CB5AZLOVHV6UK4DPCQHHWHCV75T")),
                                                                 new List <Mosaic>()
            {
                mosaicToTransfer
            },
                                                                 PlainMessage.Create("test-message"),
                                                                 NetworkType.TEST_NET
                                                                 );

            var generationHash = "B750FC8ADD9FAB8C71F0BB90B6409C66946844F07C5CADB51F27A9FAF219BFC7";

            var signedTransaction = account.Sign(transferTransaction, generationHash);

            //var payload = signedTransaction.Payload;

            signedTransaction.Payload.Should().NotBeNullOrEmpty();
            signedTransaction.Hash.Should().NotBeNullOrEmpty();
        }
Ejemplo n.º 8
0
        public void ShouldCreateAggregateTransactionAndSignWithMultipleCosignatories()
        {
            TransferTransaction transferTx = TransferTransaction.Create(
                NetworkType.Types.MIJIN_TEST,
                FakeDeadline.Create(),
                new Address("SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC", NetworkType.Types.MIJIN_TEST),
                new List <Mosaic>(),
                PlainMessage.Create("test-message")

                );

            AggregateTransaction aggregateTx = AggregateTransaction.CreateComplete(
                NetworkType.Types.MIJIN_TEST,
                FakeDeadline.Create(),
                new List <Transaction>()
            {
                transferTx.ToAggregate(new PublicAccount("B694186EE4AB0558CA4AFCFDD43B42114AE71094F5A1FC4A913FE9971CACD21D", NetworkType.Types.MIJIN_TEST))
            });

            Account cosignatoryAccount  = new Account("2a2b1f5d366a5dd5dc56c3c757cf4fe6c66e2787087692cf329d7a49a594658b", NetworkType.Types.MIJIN_TEST);
            Account cosignatoryAccount2 = new Account("b8afae6f4ad13a1b8aad047b488e0738a437c7389d4ff30c359ac068910c1d59", NetworkType.Types.MIJIN_TEST);

            SignedTransaction signedTransaction = cosignatoryAccount.SignTransactionWithCosignatories(aggregateTx, new List <Account>()
            {
                cosignatoryAccount2
            });

            Assert.AreEqual("2D010000", signedTransaction.Payload.Substring(0, 8));
            Assert.AreEqual("5100000051000000", signedTransaction.Payload.Substring(240, 16));
        }
        public async Task <Account> GenerateAccountWithCurrency(ulong amount)
        {
            var account = Account.GenerateNewAccount(NetworkType);
            var mosaic  = NetworkCurrencyMosaic.CreateRelative(amount);
            var message = PlainMessage.Create("Send some money");
            var tx      = await Transfer(SeedAccount, account.Address, mosaic, message, GenerationHash);

            return(account);
        }
        public async Task Should_Announce_Aggregate_Transaction_Signed_Aggregate_Transaction()
        {
            var account = Account.GenerateNewAccount(Fixture.NetworkType);
            var mosaic  = NetworkCurrencyMosaic.CreateAbsolute(1);
            var message = PlainMessage.Create("c#__ SDK plain message test");
            var result  = await Fixture.AggregateTransfer(Fixture.SeedAccount, account.Address, mosaic, message, Fixture.GenerationHash);

            Log.WriteLine($"Transaction confirmed {result.TransactionInfo.Hash}");
            result.TransactionInfo.Hash.Should().NotBeNullOrWhiteSpace();
            result.TransactionType.Should().Be(EntityType.AGGREGATE_COMPLETE);
        }
 internal static TransferTransaction CreateInnerTransferTransaction(String signer)
 {
     return(TransferTransaction.Create(
                NetworkType.Types.MIJIN_TEST,
                Deadline.CreateHours(2),
                Address.CreateFromEncoded("SAAA57DREOPYKUFX4OG7IQXKITMBWKD6KXTVBBQP"),
                new List <Mosaic> {
         Mosaic.CreateFromIdentifier("nem:xem", 10)
     },
                PlainMessage.Create("hey")));
 }
        public async Task <Account> GenerateAccountAndSendSomeMoney(int amount)
        {
            var networkType = Client.NetworkHttp.GetNetworkType().Wait();
            var account     = Account.GenerateNewAccount(networkType);

            var money = (ulong)amount;

            var mosaicToTransfer = NetworkCurrencyMosaic.CreateRelative(money);

            var transferTransaction = TransferTransaction.Create(
                Deadline.Create(),
                account.Address,
                new List <Mosaic>()
            {
                // mosaicToTransfer
            },
                PlainMessage.Create("transferTest"),
                networkType);

            var signedTransaction = SeedAccount.Sign(transferTransaction, Environment.GenerationHash);

            WatchForFailure(signedTransaction);
            try
            {
                await WebSocket.Listener.Open();

                var tx = WebSocket.Listener.ConfirmedTransactionsGiven(account.Address).Take(1).Timeout(TimeSpan.FromSeconds(100));


                await Client.TransactionHttp.Announce(signedTransaction);

                var result = await tx;

                if (result.IsConfirmed())
                {
                    return(account);
                }
                else
                {
                    throw new Exception($"Unable to send money to account {account.Address.Plain}");
                }
            }
            finally
            {
                try
                {
                    // WebSocket.Listener.Close();
                }
                catch (Exception)
                {
                    //do nothing
                }
            }
        }
        public async Task Should_Announce_Transfer_Transaction_With_NetworkCurrencyMosaic_PlainMessage()
        {
            var account = Account.GenerateNewAccount(Fixture.NetworkType);
            var mosaic  = NetworkCurrencyMosaic.CreateRelative(10);
            var message = PlainMessage.Create("Test message");
            var result  = await Fixture.Transfer(Fixture.SeedAccount, account.Address, mosaic, message, Fixture.GenerationHash);

            Log.WriteLine($"Transaction confirmed {result.TransactionInfo.Hash}");
            result.TransactionInfo.Hash.Should().NotBeNullOrWhiteSpace();
            //result.TransactionType.Should().Be(EntityType.TRANSFER);
            ((TransferTransaction)result).Message.GetMessageType().Should().Be(MessageType.PLAIN_MESSAGE.GetValueInByte());
        }
        internal static TransferTransaction CreateInnerTransferTransaction(string mosaic, ulong amount = 10)
        {
            return(TransferTransaction.Create(
                       NetworkType.Types.MIJIN_TEST,
                       Deadline.CreateHours(2),
                       Address.CreateFromEncoded("SAAA57-DREOPY-KUFX4O-G7IQXK-ITMBWK-D6KXTV-BBQP"),
                       new List <Mosaic> {
                Mosaic.CreateFromIdentifier(mosaic, amount)
            },
                       PlainMessage.Create("hey")

                       ));
        }
Ejemplo n.º 15
0
        public async Task <TransactionResponse> Send(object data)
        {
            var cosignatory     = KeyPair.CreateFromPrivateKey("8db858dcc8e2827074498204b3829154ec4c4f24d13738d3f501003b518ef256");
            var secondCosig     = KeyPair.CreateFromPrivateKey("cfe47dd9801a5d4fe37183e8f6ca49fff532a2fe6fe099436df93b3d62fe17d5");
            var multisigAccount = PublicAccount.CreateFromPublicKey("29c4a4aa674953749053c8a35399b37b713dedd5d002cb29b3331e56ff1ea65a", NetworkType.Types.TEST_NET);
            var recipient       = new Account("E45030D2A22D97FDC4C78923C4BBF7602BBAC3B018FFAD2ED278FB49CD6F218C", NetworkType.Types.TEST_NET);

            var transaction = TransferTransaction.Create(
                NetworkType.Types.TEST_NET,
                Deadline.CreateHours(2),
                recipient.Address,
                new List <Mosaic> {
                Mosaic.CreateFromIdentifier("nem:xem", 1000000)
            },
                PlainMessage.Create("hello")
                );

            var multisigTransaction = MultisigTransaction
                                      .Create(NetworkType.Types.TEST_NET, Deadline.CreateHours(1), transaction)
                                      .SignWith(cosignatory, multisigAccount);



            TransactionResponse response = await new TransactionHttp(host).Announce(multisigTransaction);

            var signatureTransaction = CosignatureTransaction.Create(
                NetworkType.Types.TEST_NET,
                Deadline.CreateHours(1),
                "59f5f7cbbdaa996b8d3c45ce814280aab3b5d322a98fe95c00ae516cf436172d",
                multisigAccount.Address
                ).SignWith(secondCosig);

            TransactionResponse response2 = await new TransactionHttp(host).Announce(signatureTransaction);

            //var localVarPath = "/transaction/announce";
            //var client = new RestClient(host);
            //var request = new RestRequest(localVarPath, Method.POST);
            //request.AddParameter("application/json", data, ParameterType.RequestBody);
            //var resp = client.Execute(request);

            if (response.Status == "1")
            {
                TransactionInfo transactionInfo = new TransactionInfo
                {
                    Id = 1, Hash = response.Hash, InnerHash = response.InnerHash
                };
                _transactionInfoRepository.AddTransaction(transactionInfo);
            }

            return(null);
        }
        public async Task Should_Send_Some_Money_To_New_Account()
        {
            var aliceAccount = await Fixture.GenerateAccountWithCurrency(500);



            var tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(aliceAccount.Address).Take(1);

            Log.WriteLine($"Alice Account {aliceAccount.Address.Plain} \r\n Private Key: {aliceAccount.PrivateKey} \r\n Public Key {aliceAccount.PublicKey}");

            const ulong amount           = (ulong)10;
            var         mosaicToTransfer = NetworkCurrencyMosaic.CreateRelative(amount);

            var transferTransaction = TransferTransaction.Create(
                Deadline.Create(),
                aliceAccount.Address,
                new List <Mosaic>()
            {
                mosaicToTransfer
            },
                PlainMessage.Create("transferTest"),
                Fixture.NetworkType);

            var signedTransaction = Fixture.SeedAccount.Sign(transferTransaction, Fixture.GenerationHash);

            Log.WriteLine($"Going to send {amount} XPP to {aliceAccount.Address.Pretty} with transaction {signedTransaction.Hash}");
            Fixture.WatchForFailure(signedTransaction);
            await Fixture.SiriusClient.TransactionHttp.Announce(signedTransaction);

            var result = await tx;

            Log.WriteLine($"Request confirmed with public key {result.Signer.PublicKey}");

            var aliceAccountInfo = await Fixture.SiriusClient.AccountHttp.GetAccountInfo(aliceAccount.Address);

            aliceAccountInfo.Mosaics[0]?.Amount.Should().BeGreaterThan(0);

            var outgoingTxs = Fixture.SiriusClient.AccountHttp.OutgoingTransactions(aliceAccountInfo.PublicAccount).Wait();

            var recipientAddress = "VDG4WG-FS7EQJ-KFQKXM-4IUCQG-PXUW5H-DJVIJB-OXJG";
            var address          = Address.CreateFromRawAddress(recipientAddress);

            var mosaicAmounts = (from TransferTransaction t in outgoingTxs
                                 where t.TransactionType == EntityType.TRANSFER &&
                                 t.Recipient.Address.Plain == address.Plain &&
                                 t.Mosaics.Count == 1 &&
                                 t.Mosaics[0].HexId == NetworkCurrencyMosaic.Id.HexId
                                 select(long) t.Mosaics[0].Amount).ToList();

            Console.WriteLine($"Total xpx send to account {address.Plain} is {mosaicAmounts.Sum()}");
        }
Ejemplo n.º 17
0
 protected IMessage RetrieveMessage(JObject msg)
 {
     if (msg["payload"].ToString().Substring(0, 2) == "fe" && Regex.IsMatch(msg["payload"].ToString(), @"\A\b[0-9a-fA-F]+\b\Z"))
     {
         return(new HexMessage(msg["payload"].ToString().FromHex()));
     }
     if (int.Parse(msg["type"].ToString()) == 1)
     {
         return(PlainMessage.Create(Encoding.UTF8.GetString(msg["payload"].ToString().FromHex())));
     }
     if (int.Parse(msg["type"].ToString()) == 2)
     {
         return(new SecureMessage(msg["payload"].ToString().FromHex()));
     }
     throw new Exception("invalid message type");
 }
        public async Task Should_Send_Money_From_Multsi_From_1To2_Cosignatory()
        {
            var recipient = Account.GenerateNewAccount(Fixture.NetworkType);

            Log.WriteLine($"MultiSig account {Fixture.MultiSigAccount}");
            Log.WriteLine($"Recipient account {recipient}");
            Log.WriteLine($"Cosignatory1 account {Fixture.Cosignatory1}");
            var transferTransaction = TransferTransaction.Create(
                Deadline.Create(),
                Recipient.From(recipient.Address),
                new List <Mosaic> {
                NetworkCurrencyMosaic.CreateAbsolute(10)
            },
                PlainMessage.Create("sending 10 prx.xpx"),
                Fixture.NetworkType);

            var aggregateTransaction = AggregateTransaction.CreateComplete(
                Deadline.Create(),
                new List <Transaction> {
                transferTransaction.ToAggregate(Fixture.MultiSigAccount.PublicAccount)
            },
                Fixture.NetworkType);

            var signedTransaction = Fixture.Cosignatory1.Sign(aggregateTransaction, Fixture.GenerationHash);

            var cosignatory1ConfirmedTx = Fixture.SiriusWebSocketClient.Listener
                                          .ConfirmedTransactionsGiven(Fixture.Cosignatory1.Address).Take(1)
                                          .Timeout(TimeSpan.FromSeconds(2000));

            Log.WriteLine($"Going to announce aggregate bonded transaction {signedTransaction.Hash}");
            await Fixture.SiriusClient.TransactionHttp.Announce(signedTransaction);

            var result = await cosignatory1ConfirmedTx;

            Thread.Sleep(5000);

            if (result.IsConfirmed())
            {
                var recipientAccountInfo = await Fixture.SiriusClient.AccountHttp.GetAccountInfo(recipient.Address);

                Log.WriteLine($"Recipient info {recipientAccountInfo.Address}");

                recipientAccountInfo.Mosaics.Should().HaveCount(1);
                recipientAccountInfo.Mosaics[0].Amount.Should().Be(10);
            }
        }
        public async Task AnnounceTransaction(ulong amount = 10)
        {
            var keyPair =
                KeyPair.CreateFromPrivateKey(Config.PrivateKeyMain);

            var transaction = TransferTransaction.Create(
                NetworkType.Types.MIJIN_TEST,
                Deadline.CreateHours(2),
                Address.CreateFromEncoded("SCEYFB35CYFF2U7UZ32RYXXZ5JTPCSKU4P6BRXZR"),
                new List <Mosaic> {
                Mosaic.CreateFromIdentifier("nem:xem", amount)
            },
                PlainMessage.Create("hello")
                ).SignWith(keyPair);

            await new TransactionHttp("http://" + Config.Domain + ":3000").Announce(transaction);
        }
        public async Task Should_Send_Some_Money_To_New_Account()
        {
            // var aliceAccount = await Fixture.GenerateAccountWithCurrency(100000);

            var aliceAccount = Account.CreateFromPrivateKey("101a4dfcffe3d5abddee535c0c7fa7bb386b99eb7c19f0c73cdc3837c5844477", Fixture.NetworkType);

            var tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(aliceAccount.Address).Take(1);

            Log.WriteLine($"Alice Account {aliceAccount.Address.Plain} \r\n Private Key: {aliceAccount.PrivateKey} \r\n Public Key {aliceAccount.PublicKey}");

            const ulong amount           = (ulong)1000;
            var         mosaicToTransfer = NetworkCurrencyMosaic.CreateRelative(amount);

            var transferTransaction = TransferTransaction.Create(
                Deadline.Create(),
                aliceAccount.Address,
                new List <Mosaic>()
            {
                mosaicToTransfer
            },
                PlainMessage.Create("transferTest"),
                Fixture.NetworkType);

            var signedTransaction = Fixture.SeedAccount.Sign(transferTransaction, Fixture.GenerationHash);

            Log.WriteLine($"Going to send {amount} XPP to {aliceAccount.Address.Pretty} with transaction {signedTransaction.Hash}");
            Fixture.WatchForFailure(signedTransaction);

            await Fixture.SiriusClient.TransactionHttp.Announce(signedTransaction);

            var result = await tx;

            Log.WriteLine($"Request confirmed with public key {result.Signer.PublicKey}");

            var aliceAccountInfo = await Fixture.SiriusClient.AccountHttp.GetAccountInfo(aliceAccount.Address);

            Log.WriteLine($"Alice Account Info: {aliceAccountInfo.Mosaics[0]}");

            aliceAccountInfo.Mosaics[0]?.Amount.Should().BeGreaterThan(0);

            var outgoingTxs = Fixture.SiriusClient.AccountHttp.OutgoingTransactions(PublicAccount.CreateFromPublicKey(result.Signer.PublicKey, Fixture.NetworkType)).Wait();

            outgoingTxs.Transactions.Count().Should().BeGreaterThan(0);
            Log.WriteLine($"Complete");
        }
Ejemplo n.º 21
0
        public IMessage CreateMessage(ProximaxMessagePayloadModel messagePayload, string senderPrivateKey,
                                      string recipientPublicKeyRaw,
                                      string recipientAddress, bool useBlockchainSecureMessage)
        {
            CheckParameter(messagePayload != null, "messagePayload is required");

            var jsonPayload = messagePayload.ToJson();

            if (useBlockchainSecureMessage)
            {
                var recipientPublicKey =
                    this.GetRecipientPublicKey(senderPrivateKey, recipientPublicKeyRaw, recipientAddress);
                return(SecureMessage.Create(jsonPayload, senderPrivateKey, recipientPublicKey));
            }
            else
            {
                return(PlainMessage.Create(jsonPayload));
            }
        }
Ejemplo n.º 22
0
        internal new TransferTransaction Apply(string input)
        {
            var tx = JsonConvert.DeserializeObject <TransferTransactionInfoDTO>(input);

            var txInfo   = TransactionInfo.Create(tx.Meta.Height, tx.Meta.Index, tx.Meta.Id, tx.Meta.Hash, tx.Meta.MerkleComponentHash);
            var deadline = new Deadline(tx.Transaction.Deadline);
            var mosaics  = tx.Transaction.Mosaics.Select(m => new Mosaic(new MosaicId(BitConverter.ToUInt64(m.MosaicId.FromHex(), 0)), m.Amount)).ToList();

            IMessage message;

            try
            {
                message = PlainMessage.Create(Encoding.UTF8.GetString(tx.Transaction.Message.Payload.FromHex()));
            }
            catch (Exception)
            {
                try
                {
                    message = PlainMessage.Create(tx.Transaction.Message.Payload);
                }
                catch (Exception)
                {
                    message = EmptyMessage.Create();
                }
            }

            return(new TransferTransaction(
                       ExtractNetworkType(tx.Transaction.Version),
                       ExtractTransactionVersion(tx.Transaction.Version),
                       deadline,
                       tx.Transaction.Fee,
                       Address.CreateFromEncoded(tx.Transaction.Recipient),
                       mosaics,
                       message,
                       tx.Transaction.Signature,
                       new PublicAccount(tx.Transaction.Signer, ExtractNetworkType(tx.Transaction.Version)),
                       txInfo
                       ));
        }
Ejemplo n.º 23
0
        public void Should_Serialize_And_Sign_Transaction()
        {
            var mosaics = new List <Mosaic>()
            {
                new Mosaic((new MosaicId(992621222383397347)), 20)
            };

            var transferTransaction = TransferTransaction.Create(Deadline.Create(1),
                                                                 Recipient.From(new Address("SBILTA367K2LX2FEXG5TFWAS7GEFYAGY7QLFBYKC", NetworkType.MIJIN_TEST)),
                                                                 mosaics,
                                                                 PlainMessage.Create("test-message"),
                                                                 NetworkType.MIJIN_TEST,
                                                                 0
                                                                 );
            var account           = Account.CreateFromPrivateKey("26b64cb10f005e5988a36744ca19e20d835ccc7c105aaa5f3b212da593180930", NetworkType.MIJIN_TEST);
            var generationHash    = "B750FC8ADD9FAB8C71F0BB90B6409C66946844F07C5CADB51F27A9FAF219BFC7";
            var signedTransaction = transferTransaction.SignWith(account, generationHash);

            // var payload = signedTransaction.Payload;
            signedTransaction.Payload.Should().NotBeNullOrEmpty();
            signedTransaction.Hash.Should().NotBeNullOrEmpty();
        }
        public async Task Should_Announce_Transfer_Transaction_With_Default_Fee()
        {
            var account = Account.GenerateNewAccount(Fixture.NetworkType);
            var mosaic  = NetworkCurrencyMosaic.CreateRelative(10);
            var message = PlainMessage.Create("Test message");

            var builder = new TransferTransactionBuilder();

            var transferTransaction = builder
                                      .SetNetworkType(Fixture.NetworkType)
                                      .SetDeadline(Deadline.Create())
                                      .SetMosaics(new List <Mosaic>()
            {
                mosaic
            })
                                      .SetRecipient(Recipient.From(account.Address))
                                      .SetMessage(message)
                                      .SetFeeCalculationStrategy(FeeCalculationStrategyType.LOW)
                                      .Build();


            var signedTransaction = Fixture.SeedAccount.Sign(transferTransaction, Fixture.GenerationHash);

            Fixture.WatchForFailure(signedTransaction);

            //Log.WriteLine($"Going to announce transaction {signedTransaction.Hash}");

            var tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(Fixture.SeedAccount.Address).Take(1);

            await Fixture.SiriusClient.TransactionHttp.Announce(signedTransaction);

            var result = await tx;

            Log.WriteLine($"Transaction confirmed {result.TransactionInfo.Hash}");
            result.TransactionInfo.Hash.Should().NotBeNullOrWhiteSpace();
            //result.TransactionType.Should().Be(EntityType.TRANSFER);
            ((TransferTransaction)result).Message.GetMessageType().Should().Be(MessageType.PLAIN_MESSAGE.GetValueInByte());
        }
Ejemplo n.º 25
0
        public static async Task <bool> TransferTest()
        {
            KeyPair keyPair = KeyPair.CreateFromPrivateKey(Config.PrivateKeyMain);

            TransferTransaction transaction = TransferTransaction.Create(
                NetworkType.Types.TEST_NET,
                Deadline.CreateHours(2),
                Address.CreateFromEncoded("TBZQXJ-N7JNQL-N7ZAMC-HFFZAU-WBMPB4-4RMIZU-XKNQ"),
                new List <Mosaic> {
                Mosaic.CreateFromIdentifier("nem:xem", 1000000)
            },
                PlainMessage.Create("Sr Alejo")
                );

            SignedTransaction signedTransaction = transaction.SignWith(keyPair);

            Console.WriteLine(signedTransaction.Hash);
            Console.WriteLine(transaction.Fee);
            TransactionResponse response = await
                                           new TransactionHttp("http://" + Config.Domain + ":7890").Announce(signedTransaction);

            return(true);
        }
Ejemplo n.º 26
0
        public async Task CanSignMultisigTransaction()
        {
            var cosignatory     = new KeyPair("8db858dcc8e2827074498204b3829154ec4c4f24d13738d3f501003b518ef256");
            var secondCosig     = new KeyPair("cfe47dd9801a5d4fe37183e8f6ca49fff532a2fe6fe099436df93b3d62fe17d5");
            var multisigAccount = new PublicAccount("29c4a4aa674953749053c8a35399b37b713dedd5d002cb29b3331e56ff1ea65a", NetworkType.Types.TEST_NET);
            var recipient       = new PrivateAccount("E45030D2A22D97FDC4C78923C4BBF7602BBAC3B018FFAD2ED278FB49CD6F218C", NetworkType.Types.TEST_NET);

            var transaction = TransferTransaction.Create(
                NetworkType.Types.TEST_NET,
                Deadline.CreateHours(2),
                recipient.Address,
                new List <MosaicAmount> {
                new MosaicAmount("nem:xem", 1000000)
            },
                PlainMessage.Create("hello")
                );

            var multisigTransaction = MultisigTransaction
                                      .Create(NetworkType.Types.TEST_NET, Deadline.CreateHours(1), transaction)
                                      .SignWith(cosignatory, multisigAccount);

            var response = await new TransactionHttp("http://" + Config.Domain + ":7890").Announce(multisigTransaction);

            Assert.AreEqual("SUCCESS", response.Message);

            var signatureTransaction = CosignatureTransaction.Create(
                NetworkType.Types.TEST_NET,
                Deadline.CreateHours(1),
                "59f5f7cbbdaa996b8d3c45ce814280aab3b5d322a98fe95c00ae516cf436172d",
                multisigAccount.Address
                ).SignWith(secondCosig);

            var response2 = await new TransactionHttp("http://" + Config.Domain + ":7890").Announce(signatureTransaction);

            Assert.AreEqual("FAILURE_MULTISIG_NO_MATCHING_MULTISIG", response2.Message);
        }
Ejemplo n.º 27
0
        public async Task <(string transactionContext, decimal fee, long expiration)> BuildTransactionAsync(Guid operationId,
                                                                                                            IAsset asset, IReadOnlyList <IOperationAction> actions, bool includeFee)
        {
            // from one side NEM supports single sender and single receiver per transaction,
            // from the other side we support single asset per transaction,
            // finally only single transfers are allowed

            if (actions.Count != 1)
            {
                throw new ArgumentException("Transaction must contain a single transfer only");
            }

            var nodeHttp    = new NodeHttp(_nemUrl);
            var networkType = await nodeHttp.GetNetworkType();

            var action         = actions[0];
            var toAddressParts = action.To.Split(AddressSeparator);
            var toAddress      = toAddressParts[0];
            var memo           = toAddressParts.Length > 1
                ? toAddressParts[1]
                : "";
            var message = !string.IsNullOrEmpty(memo)
                ? PlainMessage.Create(memo) as IMessage
                : EmptyMessage.Create();
            var mosaic = Mosaic.CreateFromIdentifier(asset.AssetId, (ulong)asset.ToBaseUnit(action.Amount));
            var fee    = await TransferTransaction.CalculateFee(networkType, message, new[] { mosaic }, new NamespaceMosaicHttp(_nemUrl));

            if (includeFee)
            {
                try
                {
                    checked
                    {
                        if (mosaic.NamespaceName == Xem.NamespaceName &&
                            mosaic.MosaicName == Xem.MosaicName)
                        {
                            mosaic.Amount -= fee.fee;
                        }

                        // only single transfers are supported,
                        // so there must be single levy

                        var levy = fee.levies.SingleOrDefault();

                        if (levy != null &&
                            mosaic.NamespaceName == levy.NamespaceName &&
                            mosaic.MosaicName == levy.MosaicName)
                        {
                            mosaic.Amount -= levy.Amount;
                        }
                    }
                }
                catch (OverflowException)
                {
                    throw new BlockchainException(BlockchainErrorCode.AmountIsTooSmall, "Amount is less than fee");
                }
            }

            // check balances of FromAddress for all required assets

            var fromAddress = action.From.Split(AddressSeparator)[0];
            var owned       = await new AccountHttp(_nemUrl).MosaicsOwned(Address.CreateFromEncoded(fromAddress));
            var required    = fee.levies
                              .Append(Xem.CreateAbsolute(fee.fee))
                              .Append(mosaic)
                              .GroupBy(m => new { m.NamespaceName, m.MosaicName })
                              .Select(g => new Mosaic(g.Key.NamespaceName, g.Key.MosaicName, g.Aggregate(0UL, (v, m) => v += m.Amount)))
                              .ToList();

            foreach (var req in required)
            {
                var own = owned.FirstOrDefault(m => m.NamespaceName == req.NamespaceName && m.MosaicName == req.MosaicName)?.Amount ?? 0UL;
                if (own < req.Amount)
                {
                    throw new BlockchainException(BlockchainErrorCode.NotEnoughBalance,
                                                  $"Not enough {req.NamespaceName}:{req.MosaicName}");
                }
            }

            var networkTime = (int)(await nodeHttp.GetExtendedNodeInfo()).NisInfo.CurrentTime;

            var tx = TransferTransaction.Create(
                networkType,
                new Deadline(networkTime + _expiresInSeconds),
                fee.fee,
                Address.CreateFromEncoded(toAddress),
                new List <Mosaic> {
                mosaic
            },
                message,
                networkTime);

            return(
                tx.ToJson(),
                Convert.ToDecimal(fee.fee * 1e-6),
                tx.Deadline.GetInstant()
                );
        }
        public async Task Should_Link_Namespace_To_An_Account()
        {
            var company = Account.GenerateNewAccount(Fixture.NetworkType);

            await Fixture.SiriusWebSocketClient.Listener.Open();

            var tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(company.Address).Take(1);

            #region Create account and send some money to it

            Log.WriteLine($"Alice Account {company.Address.Plain} \r\n Private Key: {company.PrivateKey} \r\n Public Key {company.PublicKey}");

            const ulong amount           = (ulong)150;
            var         mosaicToTransfer = NetworkCurrencyMosaic.CreateRelative(amount);

            var transferTransaction = TransferTransaction.Create(
                Deadline.Create(),
                company.Address,
                new List <Mosaic>()
            {
                mosaicToTransfer
            },
                PlainMessage.Create("transferTest"),
                Fixture.NetworkType);

            var signedTransaction = Fixture.SeedAccount.Sign(transferTransaction, Fixture.GenerationHash);
            Log.WriteLine($"Going to send {amount} XPP to {company.Address.Pretty} with transaction {signedTransaction.Hash}");

            await Fixture.SiriusClient.TransactionHttp.Announce(signedTransaction);

            var result = await tx;

            Log.WriteLine($"Request confirmed with public key {result.Signer.PublicKey}");

            var companyAccountInfo = await Fixture.SiriusClient.AccountHttp.GetAccountInfo(company.Address);

            Log.WriteLine($"Account {companyAccountInfo.Address.Plain} with initial mosaic {companyAccountInfo.Mosaics[0]}");

            companyAccountInfo.Mosaics[0]?.Amount.Should().BeGreaterThan(0);

            #endregion Create account and send some money to it

            #region register new namespace

            var namespaceName = "nsp" + Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6);
            var registerNamespaceTransaction = RegisterNamespaceTransaction.CreateRootNamespace(
                Deadline.Create(),
                namespaceName,
                10000,
                Fixture.NetworkType
                );

            var registeredNsSignedTransaction = company.Sign(registerNamespaceTransaction, Fixture.GenerationHash);

            tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(company.Address).Take(1)
                 .Timeout(TimeSpan.FromSeconds(3000));

            await Fixture.SiriusClient.TransactionHttp.Announce(registeredNsSignedTransaction);

            Log.WriteLine(
                $"Registered namespace {namespaceName} for account {company.Address.Plain} with transaction {registeredNsSignedTransaction.Hash}");

            result = await tx;

            Log.WriteLine($"Request confirmed with transaction {result.TransactionInfo.Hash}");

            var expectedId = new NamespaceId(namespaceName);

            var nsInfo = await Fixture.SiriusClient.NamespaceHttp.GetNamespace(expectedId);

            Log.WriteLine(
                $"Retrieved namespace {namespaceName} successfully. The namespace HexId {nsInfo.Id.HexId}");
            nsInfo.Should().NotBeNull();

            companyAccountInfo = await Fixture.SiriusClient.AccountHttp.GetAccountInfo(company.Address);

            Log.WriteLine($"Account {companyAccountInfo.Address.Plain} with mosaic {companyAccountInfo.Mosaics[0]} after registered namespace");

            #endregion register new namespace

            #region Link namespace to the address

            /*var addressAliasTransaction = AliasTransaction.CreateForAddress(
             *  company.Address,
             *  nsInfo.Id,
             *  AliasActionType.LINK,
             *  Deadline.Create(),
             *  Fixture.NetworkType
             * );*/

            var builder = AliasTransactionBuilder.CreateForAddress();
            var addressAliasTransaction = builder
                                          .SetNamespaceId(nsInfo.Id)
                                          .SetDeadline(Deadline.Create())
                                          .SetNetworkType(Fixture.NetworkType)
                                          .SetFeeCalculationStrategy(FeeCalculationStrategyType.LOW)
                                          .Link(company.Address)
                                          .Build();

            tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(company.Address).Take(1);

            var aliasSignedTransaction = company.Sign(addressAliasTransaction, Fixture.GenerationHash);

            Fixture.WatchForFailure(aliasSignedTransaction);

            await Fixture.SiriusClient.TransactionHttp.Announce(aliasSignedTransaction);

            result = await tx;

            Log.WriteLine($"Request confirmed with aliasSignedTransaction transaction {aliasSignedTransaction.Hash}");

            nsInfo = await Fixture.SiriusClient.NamespaceHttp.GetNamespace(expectedId);

            nsInfo.Should().NotBeNull();
            nsInfo.HasAlias.Should().BeTrue();
            nsInfo.Alias.Address.Plain.Should().BeEquivalentTo(company.Address.Plain);

            #endregion Link namespace to the address

            #region Send mosaic to namespace instead of address

            transferTransaction = TransferTransaction.Create(
                Deadline.Create(),
                nsInfo.Id,
                new List <Mosaic>()
            {
                NetworkCurrencyMosaic.CreateRelative(10)
            },
                PlainMessage.Create("Send to namespace"),
                Fixture.NetworkType);

            tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(Fixture.SeedAccount.Address).Take(1)
                 .Timeout(TimeSpan.FromSeconds(3000));

            var nsSignedTransferTransaction = Fixture.SeedAccount.Sign(transferTransaction, Fixture.GenerationHash);

            Fixture.WatchForFailure(nsSignedTransferTransaction);

            await Fixture.SiriusClient.TransactionHttp.Announce(nsSignedTransferTransaction);

            var result2 = await tx;

            Log.WriteLine($"Request confirmed with transaction {result2.TransactionInfo.Hash}");

            companyAccountInfo = await Fixture.SiriusClient.AccountHttp.GetAccountInfo(company.Address);

            Log.WriteLine($"Account {companyAccountInfo.Address.Plain} with mosaic {companyAccountInfo.Mosaics[0]} after transfer to the alias");

            //var expectedMosaicAmount = Convert.ToUInt64(Math.Pow(10, 6)) * (150 - 100 + 10);

            companyAccountInfo.Mosaics[0]?.Amount.Should().BeGreaterThan(0);

            #endregion Send mosaic to namespace instead of address
        }
Ejemplo n.º 29
0
        public async Task Should_Link_Namespace_To_Mosaic()
        {
            #region Create mosaic

            var account = await Fixture.GenerateAccountWithCurrency(1500);

            var nonce = MosaicNonce.CreateRandom();

            var mosaicDefinitionTransaction = MosaicDefinitionTransaction.Create(
                nonce,
                MosaicId.CreateFromNonce(nonce, account.PublicAccount.PublicKey),
                Deadline.Create(),
                MosaicProperties.Create(
                    supplyMutable: true,
                    transferable: true,
                    levyMutable: false,
                    divisibility: 0,
                    duration: 1000
                    ),
                Fixture.NetworkType);

            var mosaicSupplyChangeTransaction = MosaicSupplyChangeTransaction.Create(
                Deadline.Create(),
                mosaicDefinitionTransaction.MosaicId,
                MosaicSupplyType.INCREASE,
                1000000,
                Fixture.NetworkType);

            var aggregateTransaction = AggregateTransaction.CreateComplete(
                Deadline.Create(),
                new List <Transaction>
            {
                mosaicDefinitionTransaction.ToAggregate(account.PublicAccount),
                mosaicSupplyChangeTransaction.ToAggregate(account.PublicAccount)
            },
                Fixture.NetworkType);

            var signedTransaction = account.Sign(aggregateTransaction, Fixture.GenerationHash);

            Log.WriteLine($"Going to announce transaction {signedTransaction.Hash}");

            var tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(account.Address).Take(1)
                     .Timeout(TimeSpan.FromSeconds(3000));

            await Fixture.SiriusClient.TransactionHttp.Announce(signedTransaction);

            var result = await tx;
            Log.WriteLine($"Request confirmed with transaction {result.TransactionInfo.Hash}");

            var mosaicInfo = await Fixture.SiriusClient.MosaicHttp.GetMosaic(mosaicDefinitionTransaction.MosaicId);

            mosaicInfo.Should().NotBeNull();
            mosaicInfo.Divisibility.Should().Be(0);
            mosaicInfo.Duration.Should().Be(1000);
            mosaicInfo.IsLevyMutable.Should().BeFalse();
            mosaicInfo.IsSupplyMutable.Should().BeTrue();
            mosaicInfo.IsTransferable.Should().BeTrue();
            mosaicInfo.Supply.Should().Be(1000000);
            #endregion

            #region register new namespace
            var namespaceName = "nsp" + Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6);
            var registerNamespaceTransaction = RegisterNamespaceTransaction.CreateRootNamespace(
                Deadline.Create(),
                namespaceName,
                100,
                Fixture.NetworkType
                );

            var registeredNsSignedTransaction = account.Sign(registerNamespaceTransaction, Fixture.GenerationHash);

            tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(account.Address).Take(1)
                 .Timeout(TimeSpan.FromSeconds(3000));

            await Fixture.SiriusClient.TransactionHttp.Announce(registeredNsSignedTransaction);

            Log.WriteLine(
                $"Registered namespace {namespaceName} for account {account.Address.Plain} with transaction {registeredNsSignedTransaction.Hash}");

            result = await tx;

            Log.WriteLine($"Request confirmed with transaction {result.TransactionInfo.Hash}");

            var expectedId = new NamespaceId(namespaceName);

            var nsInfo = await Fixture.SiriusClient.NamespaceHttp.GetNamespace(expectedId);

            Log.WriteLine(
                $"Retrieved namespace {namespaceName} successfully. The namespace HexId {nsInfo.Id.HexId}");
            nsInfo.Should().NotBeNull();
            #endregion

            #region Link namespace to the mosaic
            var mosaicAliasTransaction = AliasTransaction.CreateForMosaic(
                mosaicInfo.MosaicId,
                nsInfo.Id,
                AliasActionType.LINK,
                Deadline.Create(),
                Fixture.NetworkType
                );

            tx = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(account.Address).Take(1);

            var aliasSignedTransaction = account.Sign(mosaicAliasTransaction, Fixture.GenerationHash);

            Fixture.WatchForFailure(aliasSignedTransaction);

            await Fixture.SiriusClient.TransactionHttp.Announce(aliasSignedTransaction);

            result = await tx;

            Log.WriteLine($"Request confirmed with transaction {result.TransactionInfo.Hash}");


            nsInfo = await Fixture.SiriusClient.NamespaceHttp.GetNamespace(expectedId);

            nsInfo.Should().NotBeNull();
            nsInfo.HasAlias.Should().BeTrue();
            nsInfo.Alias.Type.Should().BeEquivalentTo(AliasType.MOSAIC_ID);
            nsInfo.Alias.MosaicId.HexId.Should().BeEquivalentTo(mosaicInfo.MosaicId.HexId);

            #endregion

            #region Send mosaic using namespace alias to recipient

            var newAccount = Account.GenerateNewAccount(Fixture.NetworkType);

            var transferTransaction = TransferTransaction.Create(
                Deadline.Create(),
                Recipient.From(newAccount.Address),
                new List <Mosaic>()
            {
                new Mosaic(nsInfo.Id, 10)
            },
                PlainMessage.Create("Send some mosaic to new address"),
                Fixture.NetworkType);

            var tx2 = Fixture.SiriusWebSocketClient.Listener.ConfirmedTransactionsGiven(newAccount.Address).Take(1)
                      .Timeout(TimeSpan.FromSeconds(3000));

            var nsSignedTransferTransaction = account.Sign(transferTransaction, Fixture.GenerationHash);

            Fixture.WatchForFailure(nsSignedTransferTransaction);

            await Fixture.SiriusClient.TransactionHttp.Announce(nsSignedTransferTransaction);

            var result2 = await tx2;

            Log.WriteLine($"Request confirmed with transaction {result2.TransactionInfo.Hash}");

            var newAccountInfo = await Fixture.SiriusClient.AccountHttp.GetAccountInfo(newAccount.Address);

            Log.WriteLine($"Account {newAccountInfo.Address.Plain} with mosaic {newAccountInfo.Mosaics[0]} after transfer to the namespace alias");

            var expectedMosaicAmount = Convert.ToUInt64(10);
            newAccountInfo.Mosaics[0].Id.Id.Should().Be(mosaicInfo.MosaicId.Id);
            newAccountInfo.Mosaics[0]?.Amount.Should().Be(expectedMosaicAmount);
            #endregion
        }
Ejemplo n.º 30
0
        public void CanCreateMessage()
        {
            var plainMessage = PlainMessage.Create("Hello");

            Assert.AreEqual("Hello", plainMessage.GetStringPayload());
        }