public void Serialize_WithSupportedTransaction_ShouldInvokePayloadSerializer( int version, int id, params byte[] expected) { // Arrange. var tx = new FakeTransaction(null, null, id, version); var serializer = new FakeTransactionPayloadSerializer(tx.Id); var subject = new TransactionSerializer(new[] { serializer }); var writer = new ArrayBufferWriter <byte>(); serializer.StubbedSerialize .Setup(f => f(It.IsAny <IBufferWriter <byte> >(), It.IsAny <Elysium.Transaction>())) .Callback((IBufferWriter <byte> writer, Elysium.Transaction tx) => { writer.Write(new ReadOnlySpan <byte>(expected, 4, expected.Length - 4)); }); // Act. subject.Serialize(writer, tx); // Assert. Assert.Equal(expected, writer.WrittenSpan.ToArray()); serializer.StubbedSerialize.Verify(f => f(writer, tx), Times.Once()); }
public void SerializeToSmsText_NoDescription_Exception() { var target = new TransactionSerializer(new Transaction()); Assert.Throws(Is.TypeOf <ArgumentException>() .And.Message.EqualTo("Description must be defined"), () => { target.SerializeToSmsText(); }); }
/// <summary> /// Create a new transaction checkout /// </summary> /// <param name="credentials">PagSeguro credentials</param> /// <param name="checkout"></param> /// <returns cref="T:Uol.PagSeguro.Transaction"><c>Transaction</c></returns> public static Transaction CreateCheckout(Credentials credentials, Checkout checkout) { PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "TransactionService.Register() - begin")); try { using (HttpWebResponse response = HttpURLConnectionUtil.GetHttpPostConnection( PagSeguroConfiguration.TransactionsUri.AbsoluteUri, BuildTransactionUrl(credentials, checkout), credentials.IsSandbox() ) ) { using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { Transaction transaction = new Transaction(); TransactionSerializer.Read(reader, transaction); PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "TransactionService.Register() - end {0}", transaction)); return(transaction); } } } catch (WebException exception) { PagSeguroServiceException pse = HttpURLConnectionUtil.CreatePagSeguroServiceException((HttpWebResponse)exception.Response); PagSeguroTrace.Error(String.Format(CultureInfo.InvariantCulture, "TransactionService.Register() - error {0}", pse)); throw pse; } }
/// <summary> /// Returns a transaction from a notification code /// </summary> /// <param name="credentials">PagSeguro credentials</param> /// <param name="notificationCode">Transaction notification code</param> /// <returns><c cref="T:Uol.PagSeguro.Transaction">Transaction</c></returns> public static Transaction CheckTransaction(Credentials credentials, string notificationCode, bool preApproval) { PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - begin", notificationCode)); try { using (HttpWebResponse response = HttpURLConnectionUtil.GetHttpGetConnection(BuildTransactionNotificationUrl(credentials, notificationCode, preApproval))) { using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { Transaction transaction = new Transaction(); TransactionSerializer.Read(reader, transaction, preApproval); PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - end {1}", notificationCode, transaction)); return(transaction); } } } catch (WebException exception) { PagSeguroServiceException pse = HttpURLConnectionUtil.CreatePagSeguroServiceException((HttpWebResponse)exception.Response); PagSeguroTrace.Error( String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - error {1}", notificationCode, pse)); throw pse; } }
/// <summary> /// Returns a transaction from a notification code /// </summary> /// <param name="credentials">PagSeguro credentials</param> /// <param name="notificationCode">Transaction notification code</param> /// <returns><c cref="T:Uol.PagSeguro.Transaction">Transaction</c></returns> public static Transaction CheckTransaction(Credentials credentials, string notificationCode) { PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - begin", notificationCode)); try { using (var response = HttpURLConnectionUtil.GetHttpGetConnection(BuildTransactionNotificationUrl(credentials, notificationCode))) { using (XmlReader reader = XmlReader.Create(response.Content.ReadAsStreamAsync().Result)) { Transaction transaction = new Transaction(); TransactionSerializer.Read(reader, transaction); PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - end {1}", notificationCode, transaction)); return(transaction); } } } catch (System.Exception exception) { PagSeguroServiceException pse = HttpURLConnectionUtil.CreatePagSeguroServiceException(exception); PagSeguroTrace.Error( String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - error {1}", notificationCode, pse)); throw pse; } }
public async Task <Hash32> Invoke(Transaction tx) { var ts = new TransactionSerializer(); var request = new SendTransactionRequestMessage(ts.Serialize(tx)); var response = await Invoke(request); return(response.Result); }
public void SerializeToSmsText_TransactionWithOnlyDescriptionAndAmount_Text() { var transaction = CreateValidTransaction(); var target = new TransactionSerializer(transaction); var actual = target.SerializeToSmsText(); Assert.AreEqual("Test transaction with some accents | Transação de teste com alguns acentos 123.45", actual); }
public void SerializeToSmsText_TransactionWithAccount_TextWithAccount() { var transaction = CreateValidTransaction(); transaction.AccountName = "Bancão"; var target = new TransactionSerializer(transaction); var actual = target.SerializeToSmsText(); Assert.AreEqual( "Test transaction with some accents | Transação de teste com alguns acentos 123.45 acct:Bancão", actual); }
public void SerializeToSmsText_TransactionIncome_TextWithPlusAmount() { var transaction = CreateValidTransaction(); transaction.Type = TransactionType.Income; var target = new TransactionSerializer(transaction); var actual = target.SerializeToSmsText(); Assert.AreEqual("Test transaction with some accents | Transação de teste com alguns acentos +123.45", actual); }
public void SerializeToSmsText_NotExpenseOrIncome_Exception() { var target = new TransactionSerializer(new Transaction { Description = "test", Amount = 1, Type = TransactionType.Loan }); Assert.Throws(Is.TypeOf <ArgumentException>() .And.Message.EqualTo("Only expense or income transactions can be serialized to SMS text"), () => { target.SerializeToSmsText(); }); }
public void SerializeToSmsText_TransactionWithTags_TextWithTags() { var transaction = CreateValidTransaction(); transaction.TagNames.AddRange(new[] { "tagOne", "tagTwo", "tagTrês" }); var target = new TransactionSerializer(transaction); var actual = target.SerializeToSmsText(); Assert.AreEqual( "Test transaction with some accents | Transação de teste com alguns acentos 123.45 tags:tagOne,tagTwo,tagTrês", actual); }
public void SerializeToSmsText_TransactionWithStatus_TextWithStatus() { var transaction = CreateValidTransaction(); transaction.Status = TransactionStatus.Pending; var target = new TransactionSerializer(transaction); var actual = target.SerializeToSmsText(); Assert.AreEqual( "Test transaction with some accents | Transação de teste com alguns acentos 123.45 status:pending", actual); }
public void SerializeToSmsText_TransactionWithDate_TextWithDate() { var transaction = CreateValidTransaction(); transaction.Date = new DateTime(2015, 6, 22, 0, 0, 0, DateTimeKind.Utc); var target = new TransactionSerializer(transaction); var actual = target.SerializeToSmsText(); Assert.AreEqual( "Test transaction with some accents | Transação de teste com alguns acentos 123.45 date:2015-06-22", actual); }
public async Task <Hash32> Invoke(Transaction tx) { var ts = new TransactionSerializer(); var request = new SendTransactionRequestMessage(ts.Serialize(tx)); var response = await Invoke(request); if (response.IsSuccess) { return(new Hash32(response.result.Replace("0x", ""))); } throw new Exception(response.Error.Message); }
public async Task <bool> AddTransactionAsSms(Transaction transaction) { var serializer = new TransactionSerializer(transaction); var builder = CreateRequestBuilder("add_transaction", Method.POST); var request = builder.Request; request.AddParameter("format", "sms", ParameterType.GetOrPost); request.AddParameter("text", serializer.SerializeToSmsText()); var executeRequestAsync = await ExecuteRequestAsync <AddTransactionResponse>(request); return(executeRequestAsync.TransactionAdded); }
public async Task <GetTransactionByHashResponseMessage.TransactionInfo> Invoke(Hash32 hash) { var request = new GetTransactionByHashRequestMessage(hash); var response = await Invoke(request); var tx = new TransactionSerializer().Deserialize(response.Result); return(new GetTransactionByHashResponseMessage.TransactionInfo( tx, ((string)response.Result["txIndex"]).ToBigInteger(), ((string)response.Result["blockHeight"]).ToBigInteger(), (string)response.Result["blockHash"] )); }
public void TestSerializer() { var tx = new Transaction { Version = "0x0", CellDeps = new CellDep[] { new CellDep { OutPoint = new OutPoint { TxHash = "0xbffab7ee0a050e2cb882de066d3dbf3afdd8932d6a26eda44f06e4b23f0f4b5a", Index = "0x0", }, DepType = "code", } }, HeaderDeps = Array.Empty <string>(), Inputs = Array.Empty <Input>(), Outputs = new Output[] { new Output { Capacity = "0x" + 100000000000.ToString("x"), Lock = new Script { CodeHash = "0x9e3b3557f11b2b3532ce352bfe8017e9fd11d154c4c7f9b7aaaa1e621b539a08", HashType = "data", Args = "0xe2193df51d78411601796b35b17b4f8f2cd85bd0", } }, new Output { Capacity = "0x" + 4900000000000.ToString("x"), Lock = new Script { CodeHash = "0x9e3b3557f11b2b3532ce352bfe8017e9fd11d154c4c7f9b7aaaa1e621b539a08", HashType = "data", Args = "0x36c329ed630d6ce750712a477543672adab57f4c", } } }, OutputsData = new string[] { "0x", "0x" }, Witnesses = new string[] { "0x" }, }; var expected = "0x4c02905db773301f73bbc6cd5a400c928caf410bbb13136f6f48bec0a79c22e4"; Assert.Equal(TransactionSerializer.HexStringToBytes(expected), Blake2bHasher.ComputeHash(new RawTransactionSerializer(tx).Serialize())); }
/// <summary> /// Returns a transaction from a notification code /// </summary> /// <param name="credentials">PagSeguro credentials</param> /// <param name="notificationCode">Transaction notification code</param> /// <returns><c cref="T:Uol.PagSeguro.Transaction">Transaction</c></returns> public static Transaction CheckTransaction(Credentials credentials, string notificationCode) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (String.IsNullOrEmpty(notificationCode)) { throw new ArgumentNullException("notificationCode"); } UriBuilder uriBuilder = new UriBuilder(PagSeguroConfiguration.NotificationUri); StringBuilder pathBuilder = new StringBuilder(uriBuilder.Path); pathBuilder.Append('/'); pathBuilder.Append(WebUtility.UrlEncode(notificationCode)); pathBuilder.Append('/'); uriBuilder.Path = pathBuilder.ToString(); uriBuilder.Query = ServiceHelper.EncodeCredentialsAsQueryString(credentials); WebRequest request = WebRequest.Create(uriBuilder.Uri); request.Method = ServiceHelper.GetMethod; request.Timeout = PagSeguroConfiguration.RequestTimeout; PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - begin", notificationCode)); try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { Transaction transaction = new Transaction(); TransactionSerializer.Read(reader, transaction); PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - end {1}", notificationCode, transaction)); return(transaction); } } } catch (WebException exception) { PagSeguroServiceException pse = ServiceHelper.CreatePagSeguroServiceException((HttpWebResponse)exception.Response); PagSeguroTrace.Error( String.Format(CultureInfo.InvariantCulture, "NotificationService.CheckTransaction(notificationCode={0}) - error {1}", notificationCode, pse)); throw pse; } }
public void SerializeToSmsText_TransactionWithAllData_TextWithAllData() { var transaction = CreateValidTransaction(); transaction.TagNames.AddRange(new[] { "tagOne", "tagTwo", "tagTrês" }); transaction.AccountName = "Bancão"; transaction.Date = new DateTime(2015, 6, 22, 0, 0, 0, DateTimeKind.Utc); transaction.Status = TransactionStatus.Pending; var target = new TransactionSerializer(transaction); var actual = target.SerializeToSmsText(); Assert.AreEqual( "Test transaction with some accents | Transação de teste com alguns acentos 123.45 tags:tagOne,tagTwo,tagTrês acct:Bancão date:2015-06-22 status:pending", actual); }
public async Task <IActionResult> BuildClaim([FromBody] BuildClaimTransactionRequest request) { if (request == null) { return(BadRequest(ErrorResponse.Create("Unable to deserialize request"))); } var addressValid = _addressValidator.IsAddressValid(request.Address); if (!addressValid) { return(BadRequest(ErrorResponse.Create("Invalid address"))); } var built = await _transactionBuilder.BuildClaimTransactions(request.Address); var aggregate = await _operationRepository.GetOrInsert(request.OperationId, () => OperationAggregate.StartNew(request.OperationId, fromAddress: request.Address, toAddress: request.Address, amount: built.availiableGas, assetId: Constants.Assets.Gas.AssetId, fee: 0, includeFee: false)); if (aggregate.IsBroadcasted) { return(Conflict()); } if (!built.tx.Claims.Any()) { return(Accepted(new BuiltClaimTransactionResponse { ClaimedGas = MoneyConversionHelper.ToContract(built.availiableGas, Constants.Assets.Gas.AssetId), AllGas = MoneyConversionHelper.ToContract(built.unclaimedGas, Constants.Assets.Gas.AssetId), TransactionContext = TransactionSerializer.Serialize(built.tx, TransactionType.ClaimTransaction) })); } return(Ok(new BuiltClaimTransactionResponse { ClaimedGas = MoneyConversionHelper.ToContract(built.availiableGas, Constants.Assets.Gas.AssetId), AllGas = MoneyConversionHelper.ToContract(built.unclaimedGas, Constants.Assets.Gas.AssetId), TransactionContext = TransactionSerializer.Serialize(built.tx, TransactionType.ClaimTransaction) })); }
public async Task <IActionResult> BroadcastTransaction([FromBody] BroadcastTransactionRequest request) { if (request == null) { return(BadRequest(ErrorResponse.Create("Unable to deserialize request"))); } var aggregate = await _operationRepository.GetOrDefault(request.OperationId); if (aggregate == null) { return(BadRequest(ErrorResponse.Create($"Operation {request.OperationId} not found"))); } Transaction tx; try { tx = TransactionSerializer.Deserialize(request.SignedTransaction).transaction; } catch (InvalidTransactionException) { return(BadRequest(ErrorResponse.Create($"{nameof(request.SignedTransaction)} is invalid"))); } if (aggregate.IsBroadcasted) { return(Conflict()); } try { await _transactionBroadcaster.BroadcastTransaction(tx, aggregate); } catch (TransactionAlreadyBroadcastedException) { return(Conflict()); } aggregate.OnBroadcasted(DateTime.UtcNow); await _operationRepository.Save(aggregate); return(Ok()); }
public IActionResult Sign([FromBody] SignTransactionRequest request) { if (!ModelState.IsValid) { return(BadRequest(ErrorResponseFactory.Create(ModelState))); } try { var txWrapper = TransactionSerializer.Deserialize(request.TransactionContext); var tx = txWrapper.transaction; var keyPair = new KeyPair(Wallet.GetPrivateKeyFromWif(request.PrivateKeys.Single())); var signature = Transaction.Sign(keyPair, tx, false); var invocationScript = NeoModules.Core.Helper.HexToBytes(("40" + signature.ToHexString())); var verificationScript = Helper.CreateSignatureRedeemScript(keyPair.PublicKey); tx.Witnesses = new[] { new Witness { InvocationScript = invocationScript, VerificationScript = verificationScript } }; return(Ok(new SignedTransactionResponse { SignedTransaction = TransactionSerializer.Serialize(tx, txWrapper.type) })); } catch (Exception e) { return(BadRequest(ErrorResponse.Create(e.ToAsyncString()))); } }
/// <summary> /// Finds a transaction with a matching transaction code /// </summary> /// <param name="credentials">PagSeguro credentials</param> /// <param name="transactionCode">Transaction code</param> /// <returns cref="T:Uol.PagSeguro.Transaction"><c>Transaction</c></returns> public static Transaction SearchByCode(Credentials credentials, string transactionCode) { PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "TransactionSearchService.SearchByCode(transactionCode={0}) - begin", transactionCode)); try { using (HttpWebResponse response = HttpURLConnectionUtil.GetHttpGetConnection(BuildSearchUrlByCode(credentials, transactionCode))) { using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { Transaction transaction = new Transaction(); TransactionSerializer.Read(reader, transaction); PagSeguroTrace.Info(String.Format(CultureInfo.InvariantCulture, "TransactionSearchService.SearchByCode(transactionCode={0}) - end {1}", transactionCode, transaction)); return(transaction); } } } catch (WebException exception) { PagSeguroServiceException pse = HttpURLConnectionUtil.CreatePagSeguroServiceException((HttpWebResponse)exception.Response); PagSeguroTrace.Error(String.Format(CultureInfo.InvariantCulture, "TransactionSearchService.SearchByCode(transactionCode={0}) - error {1}", transactionCode, pse)); throw pse; } }
/// <summary> /// Initializes a new instance of the <see cref="TransactionSigner"/> class. /// </summary> public TransactionSigner(CoinParameters coinParameters, TransactionSerializer serializer) { this.CoinParameters = coinParameters; this.Serializer = serializer; }
/// <summary> /// Create a transaction builder for a given coin. /// Some other Blockchain coins have different serializes of network parameters, /// this is calculated when creating the builder. /// </summary> public static TransactionBuilder Create(CoinParameters param) { AddressUtil.PopulateCoinParameters(param); // todo: move factory selector in a configuration file var lst = new List <string> { "BTC", "TRC", "GRC", "DOGE", "DASH", "RDD", "XPM", "LTC", "NMC", "QRK", "PPC", "MTR", "GB", "SHM", "CRX", "UBIQ", "ARG", "ZYD", "DLC", "STRAT", "SH" }; if (lst.Contains(param.CoinTag)) { var ser = new TransactionSerializer(param); // coin scale can be found in util.h (static const int64_t COIN = 100000000) param.CoinScale = 100000000; param.TransactionVersion = 1; if (param.CoinTag == "QRK") { param.CoinScale = 100000; } if (param.CoinTag == "PPC") { param.CoinScale = 1000000; ser = new TransactionSerializerTimeStamped(param); } if (param.CoinTag == "GRC") { ser = new TransactionSerializerGridcoin(param); } if (param.CoinTag == "RDD") { param.TransactionVersion = 2; ser = new TransactionSerializerReddcoin(param); } if (param.CoinTag == "MTR") { ser = new TransactionSerializerTimeStamped(param); } if (param.CoinTag == "GB") { ser = new TransactionSerializerTimeStamped(param); } if (param.CoinTag == "SHM") { ser = new TransactionSerializerTimeStamped(param); } if (param.CoinTag == "CRX") { ser = new TransactionSerializerTimeStamped(param); } if (param.CoinTag == "UBIQ") { ser = new TransactionSerializerTimeStamped(param); } if (param.CoinTag == "STRAT") { ser = new TransactionSerializerTimeStamped(param); } if (param.CoinTag == "DST") { ser = new TransactionSerializerTimeStamped(param); return(new DeStreamTransactionBuilder(param, ser, new TransactionSigner(param, ser))); } var builder = new TransactionBuilder(param, ser, new TransactionSigner(param, ser)); return(builder); } return(new TransactionBuilderClient()); }
protected TransactionBuilder(CoinParameters param, TransactionSerializer serializer, TransactionSigner signer) { this.CoinParameters = param; this.Serializer = serializer; this.Signer = signer; }
public DeStreamTransactionBuilder(CoinParameters param, TransactionSerializer serializer, TransactionSigner signer) : base(param, serializer, signer) { }
public void Setup() { _fileProcessor = new HellenicFileProcessor(); _transactionSerializer = new TransactionSerializer(); }
public async Task <IActionResult> BuildSingle([FromBody] BuildSingleTransactionRequest request) { if (request == null) { return(BadRequest(ErrorResponse.Create("Unable to deserialize request"))); } if (!new [] { Constants.Assets.Neo.AssetId, Constants.Assets.Gas.AssetId }.Contains(request.AssetId)) { return(BadRequest(ErrorResponse.Create("Invalid assetId"))); } var amount = MoneyConversionHelper.FromContract(request.Amount, request.AssetId); if (amount <= 0) { return(BadRequest(ErrorResponse.Create($"Amount can't be less or equal to zero: {amount}"))); } if (request.AssetId == Constants.Assets.Neo.AssetId && amount % 1 != 0) { return(BadRequest($"The minimum unit of NEO is 1 and tokens cannot be subdivided.: {amount}")); } var toAddressValid = _addressValidator.IsAddressValid(request.ToAddress); if (!toAddressValid) { return(BadRequest(ErrorResponse.Create("Invalid toAddress"))); } var fromAddressValid = _addressValidator.IsAddressValid(request.FromAddress); if (!fromAddressValid) { return(BadRequest(ErrorResponse.Create("Invalid fromAddress"))); } if (!ModelState.IsValidOperationId(request.OperationId)) { return(BadRequest(ErrorResponseFactory.Create(ModelState))); } if ((await _operationRepository.GetOrDefault(request.OperationId))?.IsBroadcasted ?? false) { return(Conflict()); } Transaction tx; decimal fee = 0; switch (request.AssetId) { case Constants.Assets.Neo.AssetId: (tx, fee) = await _transactionBuilder.BuildNeoContractTransactionAsync(request.FromAddress, request.ToAddress, amount, request.IncludeFee); break; case Constants.Assets.Gas.AssetId: tx = await _transactionBuilder.BuildGasTransactionAsync(request.FromAddress, request.ToAddress, amount); break; default: throw new ArgumentException("Unknown switch", nameof(request.AssetId)); } await _operationRepository.GetOrInsert(request.OperationId, () => OperationAggregate.StartNew(request.OperationId, fromAddress: request.FromAddress, toAddress: request.ToAddress, amount: amount, assetId: request.AssetId, fee: fee, includeFee: request.IncludeFee)); return(Ok(new BuildTransactionResponse { TransactionContext = TransactionSerializer.Serialize(tx, TransactionType.ContractTransaction) })); }
public TransactionSerializerTests() { this.payload1 = new FakeTransactionPayloadSerializer(0); this.payload2 = new FakeTransactionPayloadSerializer(1); this.subject = new TransactionSerializer(new[] { this.payload1, this.payload2 }); }