Esempio n. 1
0
        public static async Task <string> TransferAsync(Web3 web3, string contractAddress, string recipient, BigInteger amount, BigInteger gas, BigInteger gasPrice)
        {
            IContractTransactionHandler <TransferFunction> transferHandler = web3.Eth.GetContractTransactionHandler <TransferFunction>();

            var transfer = new TransferFunction()
            {
                To          = recipient,
                TokenAmount = amount,
                Gas         = gas,
                GasPrice    = Web3.Convert.ToWei(gasPrice, UnitConversion.EthUnit.Gwei)
            };

            TransactionReceipt transactionTransferReceipt = await transferHandler.SendRequestAndWaitForReceiptAsync(contractAddress, transfer).ConfigureAwait(false);

            return(transactionTransferReceipt.TransactionHash);
        }
Esempio n. 2
0
        public async Task UpsertAsync(RPC.Eth.DTOs.Transaction transaction, TransactionReceipt receipt, bool failed, HexBigInteger timeStamp, bool hasVmStack = false, string error = null)
        {
            var tx = new CosmosTransaction();

            tx.Map(transaction);
            tx.Map(receipt);

            tx.Failed     = failed;
            tx.TimeStamp  = (long)timeStamp.Value;
            tx.Error      = error ?? string.Empty;
            tx.HasVmStack = hasVmStack;

            tx.UpdateRowDates();

            await UpsertDocumentAsync(tx);
        }
        public TransactionResult ThenExpectAnEvent <TEventDTO>(TEventDTO expectedEvent) where TEventDTO : IEventDTO, new()
        {
            TestLogger.LogExpectedEvent(expectedEvent);

            var events = TransactionReceipt.DecodeAllEvents <TEventDTO>();

            var eventFirst = events.FirstOrDefault();

            Assert.NotNull(eventFirst);

            Stateprinter.Assert.AreEqual(
                Stateprinter.PrintObject(expectedEvent),
                Stateprinter.PrintObject(eventFirst.Event));

            return(this);
        }
Esempio n. 4
0
        public async Task <IEnumerable <Rental> > GetAllContractsFromTenant(string tenant, string password)
        {
            var abi =
                @"[ { 'constant': true, 'inputs': [ { 'name': '', 'type': 'bytes32' }, { 'name': '', 'type': 'uint256' } ], 'name': 'rentals', 'outputs': [ { 'name': 'tenant', 'type': 'address' }, { 'name': 'tenant', 'type': 'address' }, { 'name': 'depositeAmount', 'type': 'uint256' }, { 'name': 'rentalPrice', 'type': 'uint256' }, { 'name': 'endtime', 'type': 'uint256' }, { 'name': 'itemId', 'type': 'uint256' } ], 'payable': false, 'stateMutability': 'view', 'type': 'function' }, { 'constant': false, 'inputs': [ { 'name': 'key', 'type': 'bytes32' }, { 'name': 'tenant', 'type': 'address' }, { 'name': 'depositeAmount', 'type': 'uint256' }, { 'name': 'rentalPrice', 'type': 'uint256' }, { 'name': 'endtime', 'type': 'uint256' }, { 'name': 'itemId', 'type': 'uint256' } ], 'name': 'StoreRental', 'outputs': [ { 'name': 'success', 'type': 'bool' } ], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function' } ]";

            var byteCode =
                "0x608060405234801561001057600080fd5b50610447806100206000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630a8d65b614610051578063152aa7ca1461011b575b600080fd5b34801561005d57600080fd5b5061008a6004803603810190808035600019169060200190929190803590602001909291905050506101ac565b604051808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001838152602001828152602001965050505050505060405180910390f35b34801561012757600080fd5b506101926004803603810190808035600019169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001909291908035906020019092919080359060200190929190505050610244565b604051808215151515815260200191505060405180910390f35b6000602052816000526040600020818154811015156101c757fe5b9060005260206000209060060201600091509150508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060020154908060030154908060040154908060050154905086565b600061024e6103b8565b60c0604051908101604052808873ffffffffffffffffffffffffffffffffffffffff1681526020013373ffffffffffffffffffffffffffffffffffffffff1681526020018781526020018681526020018581526020018481525090506000808960001916600019168152602001908152602001600020819080600181540180825580915050906001820390600052602060002090600602016000909192909190915060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160020155606082015181600301556080820151816004015560a0820151816005015550505060019150509695505050505050565b60c060405190810160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200160008152602001600081526020016000815250905600a165627a7a72305820dfeb2f0f92f01e63c77c245a21f721864d33077e40ee06fcfdccb6c2c38b0e5c0029";


            //a managed account uses personal_sendTransanction with the given password, this way we don't need to unlock the account for a certain period of time
            var account = new ManagedAccount(tenant, password);

            //using the specific geth web3 library to allow us manage the mining.
            var web3    = new Nethereum.Web3.Web3("http://127.0.0.1:7545");
            var receipt = new TransactionReceipt();

            try
            {
                receipt = await web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(byteCode, tenant, new HexBigInteger(900000));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }



            var contractAddress = receipt.ContractAddress;

            var contract          = web3.Eth.GetContract(abi, contractAddress);
            var documentsFunction = contract.GetFunction("rentals");

            var result = new Rental();

            try
            {
                result = await documentsFunction.CallDeserializingToObjectAsync <Rental>("key1", 0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(null);
        }
Esempio n. 5
0
 public ReceiptForRpc(Keccak txHash, TransactionReceipt receipt)
 {
     TransactionHash   = txHash;
     TransactionIndex  = receipt.Index;
     BlockHash         = receipt.BlockHash;
     BlockNumber       = receipt.BlockNumber;
     CumulativeGasUsed = receipt.GasUsedTotal;
     GasUsed           = receipt.GasUsed;
     From            = receipt.Sender;
     To              = receipt.Recipient;
     ContractAddress = receipt.ContractAddress;
     Logs            = receipt.Logs.Select((l, idx) => new LogEntryForRpc(receipt, l, idx)).ToArray();
     LogsBloom       = receipt.Bloom;
     Root            = receipt.PostTransactionState;
     Status          = receipt.StatusCode;
     Error           = receipt.Error;
 }
Esempio n. 6
0
        public dynamic SendEtherToExchange(dynamic transactionDto, dynamic walletDto, string toAddress)
        {
            try
            {
                dynamic obj            = null;
                string  url            = GetRPCUrl(walletDto.Network);
                string  mKey           = CryptoLib.Decrypt(walletDto.MasterKey);
                string  mneumonicWords = CryptoLib.Decrypt(walletDto.Mnemonic);
                string  passphrase     = CryptoLib.Decrypt(walletDto.PassPhrase);
                var     account        = GetAccount(mneumonicWords, passphrase, transactionDto.AddressIndex);
                Web3    web3           = new Web3(account, url);
                var     gasPrice       = Nethereum.Signer.Transaction.DEFAULT_GAS_PRICE;
                // var gasPrice = Web3.Convert.ToWei(1.5, UnitConversion.EthUnit.Gwei);
                var gasLimit = Nethereum.Signer.Transaction.DEFAULT_GAS_LIMIT;
                var balance  = web3.Eth.GetBalance.SendRequestAsync(account.Address).Result;

                //TODO: Check fee and use default fee
                var fee    = gasPrice * gasLimit;
                var maxfee = Web3.Convert.ToWei(transactionDto.MaxFee.GetValueOrDefault(), UnitConversion.EthUnit.Ether);

                if (fee >= maxfee)
                {
                    fee = Web3.Convert.ToWei(transactionDto.DefaultFees.GetValueOrDefault(), UnitConversion.EthUnit.Ether);
                }
                var amountToSend        = balance - fee;
                var amountToSendInEther = UnitConversion.Convert.FromWei(amountToSend, 18);

                TransactionReceipt receipt = web3.Eth.GetEtherTransferService().TransferEtherAndWaitForReceiptAsync(toAddress, amountToSendInEther, UnitConversion.Convert.FromWei(gasPrice, 9), gasLimit).Result;
                if (receipt != null)
                {
                    if (receipt.Status.Value == 1)
                    {
                        obj = new ExpandoObject();
                        obj.TransactionHash = receipt.TransactionHash;
                        obj.Fees            = UnitConversion.Convert.FromWei(fee, 18);
                        obj.Amount          = amountToSendInEther;
                        obj.TotalAmount     = UnitConversion.Convert.FromWei(balance, 18);
                    }
                }
                return(obj);
            }
            catch (Exception ex)
            {
                throw new Exception();
            }
        }
Esempio n. 7
0
        public static ContractHandler DeployRSKKeyManagmentContract(Web3 web3,
                                                                    TransactionReceipt transactionReceiptDeployment,
                                                                    out string contractAddress)
        {
            var rSKKeyManagementDeployment = new RSKKeyManagementDeployment();

            transactionReceiptDeployment = web3.Eth.GetContractDeploymentHandler <RSKKeyManagementDeployment>()
                                           .SendRequestAndWaitForReceiptAsync(rSKKeyManagementDeployment)
                                           .ConfigureAwait(false)
                                           .GetAwaiter()
                                           .GetResult();

            contractAddress = transactionReceiptDeployment.ContractAddress;
            var contractHandler = web3.Eth.GetContractHandler(contractAddress);

            return(contractHandler);
        }
        public async Task Excludes_Contract_Creation_Calls_For_Other_Contracts()
        {
            var builder = new ContractSpecificFilterBuilder(ContractAddress1);

            var tx = new Transaction {
                To = null
            };
            var receipt = new TransactionReceipt {
                ContractAddress = AnotherAddress
            };

            Assert.True(await
                        builder.FilterContainer.TransactionFilters.IsMatchAsync((tx)));

            Assert.False(await
                         builder.FilterContainer.TransactionReceiptFilters.IsMatchAsync((receipt)));
        }
Esempio n. 9
0
        /// <summary>
        /// Get Receipt Proof
        /// </summary>
        /// <param name="transactionId"></param>
        /// <returns></returns>
        public async Task <TransactionReceiptResponse> GetReceiptProof(string transactionId)
        {
            if (!String.IsNullOrEmpty(SyncerUrl))
            {
                try
                {
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri(SyncerUrl);
                    HttpResponseMessage response = await client.GetAsync($"tx/{transactionId}/receipt/proof");

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        string contentString = await response.Content.ReadAsStringAsync();

                        TransactionReceiptResponse receiptProofResponse = JsonConvert.DeserializeObject <TransactionReceiptResponse>(contentString);
                        return(receiptProofResponse);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"Could not fetch the Receipt Proof from the syncer URL because {ex.Message}");
                }
            }
            else
            {
                try
                {
                    EthGetTransactionReceipt transactionByHash = ParentWeb3.Eth.Transactions.GetTransactionReceipt;
                    TransactionReceipt       tx = await transactionByHash.SendRequestAsync(transactionId);

                    TransactionReceiptResponse transactionReceiptResponse = new TransactionReceiptResponse()
                    {
                        Value = tx
                    };

                    return(transactionReceiptResponse);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Could not fetch te receipt proof because {ex.Message}");
                }
            }


            return(null);
        }
Esempio n. 10
0
        public static TransactionReceiptVO CreateSampleTransaction()
        {
            Block block = new Block {
                Number = new HexBigInteger(new BigInteger(10))
            };
            var tx = new Transaction
            {
                BlockNumber      = block.Number,
                TransactionHash  = "0x19ce02e0b4fdf5cfee0ed21141b38c2d88113c58828c771e813ce2624af127cd",
                TransactionIndex = new HexBigInteger(new BigInteger(0))
            };

            var receipt = new TransactionReceipt {
            };

            return(new TransactionReceiptVO(block, tx, receipt, false));
        }
Esempio n. 11
0
        public void AddTransaction(TransactionReceipt transaction)
        {
            /* write transaction to storage */
            var prefixTx = EntryPrefix.TransactionByHash.BuildPrefix(transaction.Hash);

            _rocksDbContext.Save(prefixTx, transaction.ToByteArray());
            /* add transaction to pool */
            var raw  = _rocksDbContext.Get(EntryPrefix.TransactionPool.BuildPrefix());
            var pool = raw != null?raw.ByteArrayToTransactionHashList() : new List <UInt256>();

            if (pool.Contains(transaction.Hash))
            {
                return;
            }
            pool.Add(transaction.Hash);
            _rocksDbContext.Save(EntryPrefix.TransactionPool.BuildPrefix(), pool.TransactionHashListToByteArray());
        }
Esempio n. 12
0
        /// <summary>
        /// Check transaction confirmations
        /// </summary>
        /// <param name="txId">The transaction hash</param>
        /// <returns>Tuple<Null => Unconfirmed else the number of confirmations, Succeeded or Failed></returns>
        public async Task <Tuple <ulong?, bool> > getTransactionConfirmations(string txId)
        {
            TransactionReceipt transactionReceipt = await _web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txId);

            if (transactionReceipt != null)
            {
                return(new Tuple <ulong?, bool>(
                           !transactionReceipt.BlockNumber.Value.IsZero
                    ? (ulong)transactionReceipt.BlockNumber.Value - await getLastBlock()
                    : (ulong?)null,
                           transactionReceipt.Status.Value == 1));
            }
            else
            {
                return(new Tuple <ulong?, bool>(null, false));
            }
        }
Esempio n. 13
0
        private async Task ProcessUndecodedEvents(TransactionReceipt transactionReceipt)
        {
            try
            {
                foreach (var log in transactionReceipt.Logs)
                {
                    var contractAddress = log["address"].ToObject <string>();

                    if (!IsKnownAddress(contractAddress))
                    {
                        continue;
                    }

                    var evt = new UndecodedEvent
                    {
                        TransactionHash = transactionReceipt.TransactionHash,
                        Index           = log["logIndex"].ToObject <string>(),
                        OriginAddress   = contractAddress,
                        Data            = log["data"].ToObject <string>(),
                        Topics          = log["topics"].ToObject <string[]>(),
                        ObservedAt      = DateTime.UtcNow,
                        Id = Guid.NewGuid().ToString(),
                    };

                    await _undecodedEventPublishingService.PublishAsync(evt);

                    _log.Info($"{nameof(UndecodedEvent)} has been published", evt);
                }
            }
            catch (Exception e)
            {
                #region Logging

                _log.Error
                (
                    e,
                    $"Failed to process undecoded transaction [{transactionReceipt.TransactionHash}].",
                    new { transactionHash = transactionReceipt.TransactionHash }
                );

                #endregion

                throw;
            }
        }
Esempio n. 14
0
        public bool VerifyTransactionImmediately(TransactionReceipt receipt, bool useNewChainId, bool cacheEnabled)
        {
            if (receipt is null)
            {
                throw new ArgumentNullException(nameof(receipt));
            }

            /* validate transaction hash */
            if (!receipt.Hash.Equals(receipt.FullHash(useNewChainId)))
            {
                return(false);
            }

            try
            {
                /* try to verify signature using public key cache to avoid EC recover */
                if (cacheEnabled && _publicKeyCache.TryGetValue(receipt.Transaction.From, out var publicKey))
                {
                    return(VerifyTransactionImmediately(receipt, publicKey, useNewChainId));
                }

                /* recover EC to get public key from signature to compute address */
                publicKey = receipt.RecoverPublicKey(useNewChainId);
                var address = publicKey.GetAddress();

                /* check if recovered address from public key is valid */
                if (!address.Equals(receipt.Transaction.From))
                {
                    return(false);
                }

                /* try to remember public key for this address */
                if (cacheEnabled)
                {
                    _publicKeyCache.Add(receipt.Transaction.From, publicKey);
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning($"Failed to verify transaction: {ex}");
                return(false);
            }

            return(true);
        }
Esempio n. 15
0
        private async Task DeployWatchdogsAsync()
        {
            string transactionHash = await WatchdogService.DeployContractAsync(
                Web3, AddressFrom, new string[] { AddressFrom, AddressFrom2 },
                new BigInteger(2), new HexBigInteger(3905820));

            Assert.NotNull(transactionHash);

            TransactionReceipt receipt = await
                                         Web3.Eth.Transactions.GetTransactionReceipt.
                                         SendRequestAsync(transactionHash);

            Watchdogs = new WatchdogService(Web3, receipt.ContractAddress);

            transactionHash = await IDController.SetWatchDogsAsync(AddressFrom, Watchdogs.GetAddress(), new HexBigInteger(3905820));

            Assert.NotNull(transactionHash);
        }
Esempio n. 16
0
        /// <summary>
        /// Waits for this transactin to be processed.
        /// WARNING: not supported in webgl builds!
        /// </summary>
        /// <param name="tokenSource">Cancellation source</param>
        /// <returns>Receipt of the transaction</returns>
        public async Task <TransactionReceipt> Wait(CancellationTokenSource tokenSource = null)
        {
            TransactionReceipt receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(TxId);

            while (receipt == null)
            {
                if (tokenSource != null && tokenSource.IsCancellationRequested)
                {
                    break;
                }
                await Task.Delay(1000); //TODO: in webgl build this must be swapped for sth else!!

                //This could be rewritten if we support websocket connections, or we could also create some external mechanism for waiting
                //so this could be overwriten by custom implementations
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(TxId);
            }
            return(receipt);
        }
Esempio n. 17
0
 public TransactionResult(TransactionReceipt receipt)
 {
     TransactionHash   = receipt.TransactionHash;
     TransactionIndex  = receipt.TransactionIndex.Value;
     BlockHash         = receipt.BlockHash;
     BlockNumber       = receipt.BlockNumber.Value;
     CumulativeGasUsed = receipt.CumulativeGasUsed.Value;
     GasUsed           = receipt.GasUsed.Value;
     ContractAddress   = receipt.ContractAddress;
     if (receipt.Status.Value == 1)
     {
         Status = "Transaction succeeded.";
     }
     else
     {
         Status = "Transaction failed!";
     }
 }
Esempio n. 18
0
        public ParityLikeTxTrace ParityTrace(Keccak txHash, ParityTraceTypes parityTraceTypes)
        {
            byte[] traceBytes = _traceDb.Get(txHash);
            if (traceBytes != null)
            {
                return(Rlp.Decode <ParityLikeTxTrace>(traceBytes));
            }

            TransactionReceipt transactionReceipt = _receiptStorage.Get(txHash);
            Block block = _blockTree.FindBlock(transactionReceipt.BlockNumber);

            if (block == null)
            {
                throw new InvalidOperationException("Only historical blocks");
            }

            return(ParityTrace(block, txHash, parityTraceTypes));
        }
Esempio n. 19
0
        protected async Task DeployIDControllerAsync()
        {
            string transactionHash = await IDControllerService.DeployContractAsync(
                Web3, AddressFrom, ID.GetAddress(), new HexBigInteger(3905820));

            Assert.NotNull(transactionHash);

            TransactionReceipt receipt = await
                                         Web3.Eth.Transactions.GetTransactionReceipt.
                                         SendRequestAsync(transactionHash);

            IDController = new IDControllerService(Web3, receipt.ContractAddress);

            //Change the owner of the ID to make the ID controller the owner
            transactionHash = await ID.ChangeOwnerAsync(AddressFrom, IDController.GetAddress(), new HexBigInteger(3905820));

            Assert.NotNull(transactionHash);
        }
        /// <inheritdoc />
        /// <summary>
        /// </summary>
        /// <returns></returns>
        /// <exception cref="T:src.Contract.ContractException">Thrown if the transaction can not be completed</exception>
        public async Task ConfirmUpdate()
        {
            IContractTransactionHandler <ConfirmUpdateFunction> updateTxHandler = _web3.Eth.GetContractTransactionHandler <ConfirmUpdateFunction>();
            ConfirmUpdateFunction updateTx = new ConfirmUpdateFunction
            {
                FromAddress = _validatorAddress,
                Gas         = new BigInteger(500000)
            };

            TransactionReceipt confirmResponse = await updateTxHandler.SendRequestAndWaitForReceiptAsync(_ncContractAddress, updateTx);

            bool?hasErrors = confirmResponse.HasErrors();

            if (hasErrors.HasValue && hasErrors.Value)
            {
                throw new ContractException("Unable to confirm update");
            }
        }
Esempio n. 21
0
        private OperatingError _InvokeContract(
            UInt160 addressTo, byte[] input, TransactionReceipt receipt,
            IBlockchainSnapshot snapshot, bool isSystemContract
            )
        {
            var transaction = receipt.Transaction;
            var context     = new InvocationContext(receipt.Transaction.From, snapshot, receipt);

            try
            {
                if (receipt.GasUsed > transaction.GasLimit)
                {
                    return(OperatingError.OutOfGas);
                }
                var result = ContractInvoker.Invoke(addressTo, context, input, transaction.GasLimit - receipt.GasUsed);
                receipt.GasUsed += result.GasUsed;
                if (result.Status != ExecutionStatus.Ok)
                {
                    return(OperatingError.ContractFailed);
                }

                if (receipt.GasUsed > transaction.GasLimit)
                {
                    return(OperatingError.OutOfGas);
                }
                /* this OnSystemContractInvoked is useful for internal communication (for example - during keyGeneration) */
                if (isSystemContract)
                {
                    OnSystemContractInvoked?.Invoke(this, context);
                }
                return(OperatingError.Ok);
            }
            catch (OutOfGasException e)
            {
                receipt.GasUsed += e.GasUsed;
            }
            catch (Exception e)
            {
                Logger.LogWarning($"Failed contract execution: {e}");
                return(OperatingError.InvalidContract);
            }

            return(OperatingError.OutOfGas);
        }
Esempio n. 22
0
        private async Task ProcessTransferEvents(TransactionReceipt transactionReceipt)
        {
            try
            {
                var events = DecodeAllEventsAndFilter <SentEventDTO>(transactionReceipt);

                foreach (var @event in events)
                {
                    if (string.IsNullOrEmpty(@event.Event.From) || string.IsNullOrEmpty(@event.Event.To))
                    {
                        continue;
                    }

                    var evt = new TransferEvent
                    {
                        SourceAddress   = @event.Event.From,
                        TargetAddress   = @event.Event.To,
                        Amount          = Money18.CreateFromAtto(@event.Event.Amount),
                        EventIndex      = (int)@event.Log.LogIndex.Value,
                        TransactionHash = @event.Log.TransactionHash,
                        ObservedAt      = DateTime.UtcNow,
                    };

                    await _transferEventPublishingService.PublishAsync(evt);

                    _log.Info($"{nameof(TransferEvent)} has been published", evt);
                }
            }
            catch (Exception e)
            {
                #region Logging

                _log.Error
                (
                    e,
                    $"Failed to process transfer events from transaction [{transactionReceipt.TransactionHash}].",
                    new { transactionHash = transactionReceipt.TransactionHash }
                );

                #endregion

                throw;
            }
        }
        public async Task UpsertAsync(Nethereum.RPC.Eth.DTOs.Transaction transaction,
                                      TransactionReceipt transactionReceipt,
                                      bool failed,
                                      HexBigInteger timeStamp, bool hasVmStack = false, string error = null)
        {
            var transactionEntity = Nethereum.BlockchainStore.SQL.Transaction.CreateTransaction(transaction,
                                                                                                transactionReceipt,
                                                                                                failed, timeStamp, hasVmStack, error);

            try
            {
                TransactionList.Add(transactionEntity);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            //await InsertOrUpdate(transactionEntity);
        }
Esempio n. 24
0
        /// <summary>
        /// Verify Transaction:
        ///  1. raw transaction in hex
        ///  2. raw signature in hex
        /// </summary>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public string VerifyTransaction(string[] arguments)
        {
            var  tx            = Transaction.Parser.ParseFrom(arguments[1].HexToBytes());
            bool useNewChainId = HardforkHeights.IsHardfork_9Active(_blockManager.GetHeight() + 1);
            var  sig           = arguments[2].HexToBytes().ToSignature(useNewChainId);
            var  accepted      = new TransactionReceipt
            {
                Transaction = tx,
                Hash        = tx.FullHash(sig, useNewChainId),
                Signature   = sig
            };
            var txValid  = _transactionManager.Verify(accepted, useNewChainId) == OperatingError.Ok;
            var sigValid = _transactionManager.VerifySignature(accepted, useNewChainId, true) == OperatingError.Ok;

            Console.WriteLine($"Tx Hash: {accepted.Hash}");
            Console.WriteLine("Transaction validity: " + txValid);
            Console.WriteLine(sigValid ? "Signature validity: OK" : "Signature validity: INVALID");
            return($"{txValid && sigValid}");
        }
Esempio n. 25
0
        public async Task RegisterUsername()
        {
            try {
                string username;

                if (!_contractService.ContractDeployed("UserService"))
                {
                    throw new Exception("The contract is not deployed");
                }

                string contract_ad = _contractService.GetAddressDeployedContract("UserService");

                do
                {
                    Console.Write("No username registered, Please provide a username: "******"Registering username for {0} gas", gasprice.Value.ToString());
                TransactionReceipt receipt = await _functionHandler.SendRequestAndWaitForReceiptAsync(contract_ad, addFunction);

                if (receipt.Failed())
                {
                    throw new Exception("Something went wrong");
                }

                //Decode event
                //List<EventLog<>> events = receipt.DecodeAllEvents<>
            } catch (Exception e) {
                _logger.LogError("Something went wrong with the RegisterUsername function: {0}", e.Message);
                Console.WriteLine("Something went wrong with Registering a username");
                Console.Beep();
                System.Environment.Exit(1);
            }
        }
Esempio n. 26
0
        public async Task ProcessTransactionAsync(
            Transaction transaction,
            TransactionReceipt transactionReceipt,
            HexBigInteger blockTimestamp)
        {
            var     transactionHash = transaction.TransactionHash;
            var     hasStackTrace   = false;
            JObject stackTrace      = null;
            var     error           = string.Empty;
            var     hasError        = transactionReceipt.Failed();

            if (EnabledVmProcessing)
            {
                try
                {
                    stackTrace = await _vmStackProxy
                                 .GetTransactionVmStack(transactionHash)
                                 .ConfigureAwait(false);
                }
                catch
                {
                }

                if (stackTrace != null)
                {
                    error         = _vmStackErrorChecker.GetError(stackTrace);
                    hasError      = !string.IsNullOrEmpty(error);
                    hasStackTrace = true;

                    await _transactionVmStackHandler.HandleAsync
                        (new TransactionVmStack(transactionHash, transaction.To, stackTrace));
                }
            }

            await _transactionHandler.HandleTransactionAsync(
                new TransactionWithReceipt(
                    transaction,
                    transactionReceipt,
                    hasError,
                    blockTimestamp,
                    error,
                    hasStackTrace));
        }
        public List <byte[]> GetMessageHashes(TransactionReceipt receipt)
        {
            var sentMessagesEvents = receipt.DecodeAllEvents <SentMessageEventDTO>();

            Debug.WriteLine(Event <SentMessageEventDTO> .GetEventABI().Sha3Signature);
            var sentMessages = new List <byte[]>();

            foreach (var sentMessageEvent in sentMessagesEvents)
            {
                var relayMessage = new RelayMessageXDomainFunction();
                relayMessage.Message      = sentMessageEvent.Event.Message;
                relayMessage.MessageNonce = sentMessageEvent.Event.MessageNonce;
                relayMessage.Target       = sentMessageEvent.Event.Target;
                relayMessage.Sender       = sentMessageEvent.Event.Sender;
                sentMessages.Add(Sha3Keccack.Current.CalculateHash(relayMessage.GetCallData()));
            }

            return(sentMessages);
        }
Esempio n. 28
0
        public void Test_InvalidMintController()
        {
            var tx       = new TransactionReceipt();
            var context  = new InvocationContext(_mintCntrlAdd, _stateManager.LastApprovedSnapshot, tx);
            var contract = new NativeTokenContract(context);

            // set minter
            {
                var input = ContractEncoder.Encode(Lrc20Interface.MethodSetMinter, _minterAdd);
                var call  = _contractRegisterer.DecodeContract(context, ContractRegisterer.NativeTokenContract, input);
                Assert.IsNotNull(call);
                var frame = new SystemContractExecutionFrame(call !, context, input, 100_000_000);
                Assert.AreEqual(ExecutionStatus.Ok, contract.SetMinter(_minterAdd, frame));
                var decoder = new ContractDecoder(frame.ReturnValue);
                var res     = decoder.Decode("uint160")[0] as UInt160 ?? throw new Exception("Invalid return value format");
                Assert.AreEqual(_minterAdd, res);
            }


            // set the allowedSupply
            {
                context  = new InvocationContext(_stateManager.LastApprovedSnapshot.Balances.GetMinter(), _stateManager.LastApprovedSnapshot, tx);
                contract = new NativeTokenContract(context);

                var input = ContractEncoder.Encode(Lrc20Interface.MethodSetAllowedSupply, Money.Parse("10000"));
                var call  = _contractRegisterer.DecodeContract(context, ContractRegisterer.NativeTokenContract, input);
                Assert.IsNotNull(call);
                var frame = new SystemContractExecutionFrame(call !, context, input, 100_000_000);
                Assert.AreEqual(ExecutionStatus.ExecutionHalted, contract.SetAllowedSupply(Money.Parse("10000").ToUInt256(), frame));
            }

            // verify allowedSupply
            {
                var input = ContractEncoder.Encode(Lrc20Interface.MethodGetAllowedSupply);
                var call  = _contractRegisterer.DecodeContract(context, ContractRegisterer.NativeTokenContract, input);
                Assert.IsNotNull(call);
                var frame = new SystemContractExecutionFrame(call !, context, input, 100_000_000);
                Assert.AreEqual(ExecutionStatus.Ok, contract.GetAllowedSupply(frame));
                var decoder = new ContractDecoder(frame.ReturnValue);
                var res     = decoder.Decode("uint256")[0] as UInt256 ?? throw new Exception("Invalid return value format");
                Assert.AreEqual(Money.Parse("0"), res.ToMoney());
            }
        }
        private ContractDeployment GetContractDeployment <T>() where T : ContractDeploymentMessage, new()
        {
            T contract = new T();
            ContractDeployment      deployment = null;
            WatchContractDeployment watchContractDeployment = null;
            SimpleStorageDeployment simpleStorageDeployment = null;

            if (contract is WatchContractDeployment)
            {
                watchContractDeployment = contract as WatchContractDeployment;
            }
            else if (contract is SimpleStorageDeployment)
            {
                simpleStorageDeployment = contract as SimpleStorageDeployment;
            }
            try {
                deployment = this.context.ContractDeployments.Where(s => s.ByteCode == contract.ByteCode && s.ServerUrl == this.url).First();
            } catch (InvalidOperationException ex) {
                logger.LogError($"contract does not currently exist: {ex}");
            }
            if (deployment == null)
            {
                deployment = new ContractDeployment();
                if (watchContractDeployment != null)
                {
                    watchContractDeployment.GasPrice = 0;
                    TransactionReceipt receipt = WatchContractService.DeployContractAndWaitForReceiptAsync(web3, watchContractDeployment).GetAwaiter().GetResult();
                    deployment.DeploymentAddress = receipt.ContractAddress;
                    deployment.ByteCode          = watchContractDeployment.ByteCode;
                }
                else if (simpleStorageDeployment != null)
                {
                    simpleStorageDeployment.GasPrice = 0;
                    TransactionReceipt receipt = SimpleStorageService.DeployContractAndWaitForReceiptAsync(web3, simpleStorageDeployment).GetAwaiter().GetResult();
                    deployment.DeploymentAddress = receipt.ContractAddress;
                    deployment.ByteCode          = simpleStorageDeployment.ByteCode;
                }
                deployment.ServerUrl = this.url;
                this.context.Add(deployment);
                this.context.SaveChanges();
            }
            return(deployment);
        }
        public async Task <string> Test()
        {
            //The compiled solidity contract to be deployed
            //contract test { function multiply(uint a) returns(uint d) { return a * 7; } }
            var contractByteCode =
                "0x606060405260728060106000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa1146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000600782029050606d565b91905056";

            var abi =
                @"[{""constant"":false,""inputs"":[{""name"":""a"",""type"":""uint256""}],""name"":""multiply"",""outputs"":[{""name"":""d"",""type"":""uint256""}],""type"":""function""}]";

            var addressFrom = "0x12890d2cce102216644c59dae5baed380d84830c";

            var web3 = new Web3();

            //deploy the contract, no need to use the abi as we don't have a constructor
            var transactionHash = await web3.Eth.DeployContract.SendRequestAsync(contractByteCode, addressFrom);

            //the contract should be mining now

            //get the contract address
            TransactionReceipt receipt = null;

            //wait for the contract to be mined to the address
            while (receipt == null)
            {
                await Task.Delay(500);

                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            var contract = web3.Eth.GetContract(abi, receipt.ContractAddress);

            //get the function by name
            var multiplyFunction = contract.GetFunction("multiply");

            //do a function call (not transaction) and get the result
            var result = await multiplyFunction.CallAsync <int>(69);

            //visual test
            return("The result of deploying a contract and calling a function to multiply 7 by 69 is: " + result +
                   " and should be 483");
        }