Example #1
0
        public async Task CreatedItemMatchesGetItem()
        {
            var bytes = new byte[] { 15, 97, 136, 0, 76, 187, 168, 28, 239, 85, 170, 23, 77, 81, 248, 159, };
            var str   = bytes.ToHexString();

            var collectionId = await CreateTestAliceCollection();

            var properties = Guid.NewGuid().ToByteArray();

            var createItem = new CreateItem(collectionId, properties, new Address(Configuration.Alice.Address));

            using var client = CreateClient();

            var itemCreatedTask = new TaskCompletionSource <ItemCreated>();

            client.ItemManagement.ItemCreated += (sender, created) =>
            {
                if (created.Key.CollectionId == collectionId)
                {
                    itemCreatedTask.SetResult(created);
                }
            };

            client.ItemManagement.CreateItem(createItem, new Address(Configuration.Alice.Address), Configuration.Alice.PrivateKey);

            var key = (await itemCreatedTask.Task.WithTimeout(TimeSpan.FromSeconds(30))).Key;

            var item = client.ItemManagement.GetNftItem(key);

            Assert.Equal(properties, item !.Data);
            Assert.Equal(collectionId, item !.CollectionId);
            Assert.Equal(AddressUtils.GetPublicKeyFromAddr(Configuration.Alice.Address).Bytes, item !.Owner.Bytes);
        }
Example #2
0
        public override async Task Process(NftIncomingTransaction transaction)
        {
            var account = AddressUtils.GetAddrFromPublicKey(new PublicKey()
            {
                Bytes = transaction.OwnerPublicKeyBytes
            });

            _logger.LogInformation("Calling Matcher.RegisterNftDeposit({Account}, {CollectionId}, {TokenId})", account, transaction.CollectionId, transaction.TokenId);
            await this.CallSubstrate(_logger,
                                     _configuration.MatcherContractPublicKey,
                                     _configuration.UniqueEndpoint,
                                     new Address()
            {
                Symbols = _configuration.MarketplaceUniqueAddress
            },
                                     _configuration.MarketplacePrivateKeyBytes,
                                     app => this.ContractCall(app, () => new RegisterNftDepositParameter()
            {
                User = new PublicKey()
                {
                    Bytes = transaction.OwnerPublicKeyBytes
                },
                CollectionId = transaction.CollectionId,
                TokenId      = transaction.TokenId
            }));

            _logger.LogInformation("Successfully called Matcher.RegisterNftDeposit({Account}, {CollectionId}, {TokenId})", account, transaction.CollectionId, transaction.TokenId);
        }
        public async Task CreateCollectionEmitsEvent()
        {
            var collectionName        = "1111";
            var collectionDescription = "1111";
            var tokenPrefix           = "1111";
            var mode = new CollectionMode(new Nft(200));

            var collectionCreatedTask = new TaskCompletionSource <Created>();
            var createCollection      = new CreateCollection(collectionName, collectionDescription, tokenPrefix, mode);

            using var blockClient = CreateClient();
            blockClient.CollectionManagement.CollectionCreated += (sender, @event) =>
            {
                if (AddressUtils.GetAddrFromPublicKey(@event.Account).Equals(Configuration.Alice.Address))
                {
                    collectionCreatedTask.SetResult(@event);
                }
            };

            using var client = CreateClient();
            client.CollectionManagement.CreateCollection(createCollection, new Address(Configuration.Alice.Address), Configuration.Alice.PrivateKey);

            await collectionCreatedTask.Task
            .WithTimeout(TimeSpan.FromMinutes(1));

            var created = collectionCreatedTask.Task.Result;

            Assert.NotNull(created);
            Output.WriteLine($"Created collection with id: {created.Id}");
        }
Example #4
0
    /// <summary>
    /// Checks to see if the text is a valid ethereum address
    /// </summary>
    /// <param name="address"> The current string in the address input field </param>
    private void AddressChanged(string address)
    {
        string updatedAddress = addressInputField.Text.ToLower();

        bool realEthereumAddress             = AddressUtils.IsValidEthereumAddress(updatedAddress);
        bool overridingOtherContactAddresses = contactsManager.ContactList.Contains(updatedAddress) && (!AddingContact ? updatedAddress != PreviousAddress : true);
        bool isRestrictedAddress             = restrictedAddressManager.IsRestrictedAddress(updatedAddress);

        addressInputField.Error = !realEthereumAddress || overridingOtherContactAddresses || isRestrictedAddress;

        if (!realEthereumAddress)
        {
            addressInputField.errorMessage.text = "Invalid address";
        }
        else if (overridingOtherContactAddresses)
        {
            addressInputField.errorMessage.text = "Address in use";
        }
        else if (isRestrictedAddress)
        {
            addressInputField.errorMessage.text = "Restricted address";
        }

        SetMainButtonInteractable();
    }
        /// <summary>
        /// Checks if the address is valid once the text is changed.
        /// </summary>
        private void CheckAddress()
        {
            string address = addressField.Text.ToLower();

            bool invalidEthereumAddress = !AddressUtils.IsValidEthereumAddress(address);
            bool isRestrictedAddress    = restrictedAddressManager.IsRestrictedAddress(address);

            addressField.Error = invalidEthereumAddress || isRestrictedAddress;

            if (invalidEthereumAddress)
            {
                addressField.errorMessage.text = "Invalid address";
            }
            else if (isRestrictedAddress)
            {
                addressField.errorMessage.text = "Restricted address";
            }

            if (!addressField.Error)
            {
                CheckIfSavedContact(address);
            }
            else
            {
                contactName.text = string.Empty;
            }
        }
    // public void GoToBldg(string address) {
    //  currentAddress = address;
    //  if (AddressUtils.isBldg(address)) {
    //      currentAddress = AddressUtils.generateInsideAddress (address);
    //  }
    //  AddressChanged ();
    // }

    // public void GoIn() {
    //  InputField input = GameObject.FindObjectOfType<InputField> ();
    //  currentAddress = input.text;
    //  AddressChanged ();
    // }


    // public void GoOut() {
    //  InputField input = GameObject.FindObjectOfType<InputField> ();

    //  currentAddress = AddressUtils.getContainerFlr(input.text);

    //  AddressChanged ();
    // }


    // public void GoUp() {
    //  InputField input = GameObject.FindObjectOfType<InputField> ();
    //  currentAddress = input.text;
    //  int level = AddressUtils.getFlrLevel(currentAddress);
    //  currentAddress = AddressUtils.replaceFlrLevel (currentAddress, level + 1);
    //  AddressChanged ();
    // }


    // public void GoDown() {
    //  InputField input = GameObject.FindObjectOfType<InputField> ();
    //  currentAddress = input.text;
    //  int level = AddressUtils.getFlrLevel(currentAddress);
    //  if (level > 0) {
    //      currentAddress = AddressUtils.replaceFlrLevel (currentAddress, level - 1);
    //  }
    //  AddressChanged ();
    // }


    public void AddressChanged()
    {
        Debug.Log("Address changed to: " + currentAddress);
        // InputField input = GameObject.FindObjectOfType<InputField> ();
        // if (input.text != currentAddress) {
        //  input.text = currentAddress;
        // }

        PlayerPrefs.SetString("currentAddress", currentAddress);

        // TODO validate address

        currentFlr = AddressUtils.extractFlr(currentAddress);

        // TODO check whether it changed

        // check whether we need to switch scene
        if (currentAddress.ToLower() == "g" && SceneManager.GetActiveScene().name == "Floor")
        {
            SceneManager.LoadScene("Ground");
            return;
        }
        if (currentAddress.ToLower() != "g" && SceneManager.GetActiveScene().name == "Ground")
        {
            SceneManager.LoadScene("Floor");
            return;
        }

        // load the new address
        switchAddress(currentAddress);
    }
Example #7
0
        public override async Task Process(QuoteIncomingTransaction quoteIncoming)
        {
            var account = AddressUtils.GetAddrFromPublicKey(new PublicKey()
            {
                Bytes = quoteIncoming.AccountPublicKeyBytes
            });

            _logger.LogInformation("Calling Matcher.RegisterDeposit({Account}, {Balance}, {QuoteId})", account, quoteIncoming.Amount, quoteIncoming.QuoteId);
            await this.CallSubstrate(_logger,
                                     _configuration.MatcherContractPublicKey,
                                     _configuration.UniqueEndpoint,
                                     new Address()
            {
                Symbols = _configuration.MarketplaceUniqueAddress
            },
                                     _configuration.MarketplacePrivateKeyBytes,
                                     app => this.ContractCall(app, () => new RegisterDepositParameter()
            {
                User = new PublicKey()
                {
                    Bytes = quoteIncoming.AccountPublicKeyBytes
                },
                DepositBalance = new Balance()
                {
                    Value = quoteIncoming.Amount
                },
                QuoteId = quoteIncoming.QuoteId
            }));

            _logger.LogInformation("Successfully called Matcher.RegisterDeposit({Account}, {Balance}, {QuoteId})", account, quoteIncoming.Amount, quoteIncoming.QuoteId);
        }
Example #8
0
        public async Task TransferFromChangesOwnerIfMadeByApprovedAccount()
        {
            var key = await CreateTestAliceItem();

            using var client = CreateClient();
            client.ItemManagement.Approve(new Approve(new Address(Configuration.Bob.Address), key),
                                          new Address(Configuration.Alice.Address), Configuration.Alice.PrivateKey);

            await WaitBlocks(2);

            client.ItemManagement.TransferFrom(new TransferFrom(new Address(Configuration.Alice.Address), new Address(Configuration.Charlie.Address), key, 0),
                                               new Address(Configuration.Bob.Address), Configuration.Bob.PrivateKey);

            await WaitBlocks(2);

            var item = client.ItemManagement.GetNftItem(key);

            Assert.Equal(AddressUtils.GetPublicKeyFromAddr(Configuration.Charlie.Address).Bytes, item !.Owner.Bytes);

            var approvedList = client.ItemManagement.GetApproved(key);

            if (approvedList != null)
            {
                Assert.DoesNotContain(approvedList.ApprovedAccounts, a => a.Bytes.ToHexString().Equals(AddressUtils.GetPublicKeyFromAddr(Configuration.Bob.Address).Bytes.ToHexString()));
            }
        }
        public void Ok()
        {
            BigInteger seed = new BigInteger(DateTime.Now.Ticks) << DateTime.Now.Second;

            var rnd       = new Random(BitConverter.ToInt32(seed.ToByteArray().Take(4).ToArray()));
            var publicKey = new byte[32];
            var secretKey = new byte[64];
            var payload   = new byte[64];

            rnd.NextBytes(publicKey);
            rnd.NextBytes(secretKey);
            rnd.NextBytes(payload);

            var pk = AddressUtils.GetPublicKeyFromAddr("5GWYBLjRtCQLXQmcyyRa6KaF1ihuqLjvVDE2gswJsEMxd9Qm");

            var kp  = new SR25519Keypair(pk.Bytes, secretKey);
            var sig = SR25519.Sign(payload, (ulong)payload.Length, kp);

            var arrayNotSame = new Func <byte[], bool>((btArr) => {
                return(btArr.GroupBy((i) => i).Count() > 50);
            });

            Assert.True(sig.Length == 64);
            Assert.True(arrayNotSame(sig));
        }
Example #10
0
        public string GetTypeEncoded()
        {
            var aupk = AddressUtils.GetPublicKeyFromAddr(Symbols);
            var str  = BitConverter.ToString(aupk.Bytes).Replace("-", "");

            return($"{Hash.GetStorageKey(Hasher.BLAKE2, aupk.Bytes)}{str}");
        }
        /// <summary>
        /// Polls for the transaction receipt of a transaction until a result is found.
        /// </summary>
        /// <param name="txHash"> The transaction hash to poll for a receipt. </param>
        /// <param name="networkUrl"> The network url of the transaction hash. </param>
        private IEnumerator PollForTransactionReceipt(string txHash, string networkUrl)
        {
            if (!AddressUtils.IsValidTransactionHash(txHash))
            {
                InternalInvokeError("Invalid transaction hash");
                yield return(null);
            }

            var request = new EthGetTransactionReceiptUnityRequest(networkUrl);

            do
            {
                yield return(Waiter);

                yield return(request.SendRequest(txHash));
            }while (request.Exception != null || request.Result == null);

            if (request.Result?.Status?.Value == 1)
            {
                InternalInvokeSuccess("Transaction successful!");
            }
            else
            {
                InternalInvokeError(request.Exception.Message);
            }
        }
        private async void SubmitRegisterProductExtrinsicAsync()
        {
            IsBusy = true;
            try
            {
                if (!App.IsPolkadotApiConnected)
                {
                    App.ConnectToNode();
                }

                _ = Task.Run(async() =>
                {
                    try
                    {
                        var ser = PolkadotApi.Serializer;

                        var sender = new Address("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY");
                        var pub    = AddressUtils.GetPublicKeyFromAddr(sender);
                        var secret = "0x33A6F3093F158A7109F679410BEF1A0C54168145E0CECB4DF006C1C2FFFB1F09925A225D97AA00682D6A59B95B18780C10D7032336E88F3442B42361F4A66011";

                        var encodedExtrinsic = ser.Serialize(new RegisterProductCall(
                                                                 new Identifier("00012345678905"), pub,
                                                                 //Empty.Instance
                                                                 //OneOf.OneOf<Empty, ProductPropertyList>.FromT0(Empty.Instance)
                                                                 new ProductPropertyList(new[] {
                            new ProductProperty(
                                new Identifier("name"),
                                new Identifier("Chocolate frog")
                                )
                        })
                                                                 )
                                                             );
                        Trace.WriteLine(encodedExtrinsic.ToPrefixedHexString());

                        var tcs = new TaskCompletionSource <string>();
                        var sid = PolkadotApi.SubmitAndSubcribeExtrinsic(encodedExtrinsic, "ProductRegistry", "register_product", sender, secret, str => tcs.SetResult(str));
                        Trace.WriteLine(sid);

                        var result = await tcs.Task.WithTimeout(TimeSpan.FromMinutes(1)).ConfigureAwait(false);
                        PolkadotApi.UnsubscribeStorage(sid);
                        Trace.WriteLine(result);
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex);
                    }
                });
            }
            catch (System.Exception ex)
            {
                Trace.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #13
0
        public TokensList?AddressTokens(AddressTokens addressTokens)
        {
            var publicKey = AddressUtils.GetPublicKeyFromAddr(addressTokens.Owner).Bytes;

            return(_nftClient.MakeCallWithReconnect(application =>
                                                    application.GetStorageObject <TokensList, DoubleMapKey <ulong, byte[]> >(
                                                        DoubleMapKey.Create(addressTokens.CollectionId, publicKey), Module,
                                                        AddressTokensStorage), _nftClient.Settings.MaxReconnectCount));
        }
        internal async Task LoadDataAsync()
        {
            IsBusy = true;
            try
            {
                await Task.Run(() =>
                {
                    try
                    {
                        var storedShipment = GetShipment(ShipmentId);
                        var products       = new List <ProductInfo>();
                        foreach (var productId in storedShipment.Products.ProductIds)
                        {
                            var storedProduct = GetProduct(productId.ToString());
                            products.Add(new ProductInfo
                            {
                                ProductId = productId.ToString(),
                                Owner     = AddressUtils.GetAddrFromPublicKey(storedProduct.Owner),
                                Props     = storedProduct.PropList.IsT1
                                    ? storedProduct.PropList.AsT1.Props.Select(p =>
                                                                               new ProductPropertyInfo {
                                    Name = p.Name.ToString(), Value = p.Value.ToString()
                                }).ToArray()
                                    : new ProductPropertyInfo[0],
                                Registered = DateTimeOffset.FromUnixTimeMilliseconds(storedProduct.Registered).LocalDateTime,
                            });
                        }

                        Device.BeginInvokeOnMainThread(() =>
                        {
                            Shipment =
                                new ShipmentInfo
                            {
                                ShipmentId = ShipmentId,
                                Owner      = AddressUtils.GetAddrFromPublicKey(storedShipment.Owner),
                                Status     = storedShipment.Status.Value.ToString(),
                                Products   = products.ToArray(),
                                Registered = DateTimeOffset.FromUnixTimeMilliseconds(storedShipment.Registered).LocalDateTime,
                                Delivered  = storedShipment.Delivered.IsT1
                                        ? DateTimeOffset.FromUnixTimeMilliseconds((long)storedShipment.Delivered.Value).LocalDateTime
                                        : (DateTime?)null
                            };
                            ShipmentOperationsVisible = true;
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex);
                        Toast.ShowShortToast("Error loading shipment.");
                    }
                });
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #15
0
        public async Task GetOwnerReturnsItCreatorAfterCreation()
        {
            var key = await CreateTestAliceItem();

            using var client = CreateClient();
            var owner = client.ItemManagement.GetOwner(key);

            Assert.Equal(AddressUtils.GetPublicKeyFromAddr(Configuration.Alice.Address).Bytes, owner !.Bytes);
        }
Example #16
0
        /// <summary>
        /// Signs the given transaction with the given private key.
        /// The result signature will be assigned to all inputs of the transaction.
        /// </summary>
        private static void signTransation(Transaction tx, EllipticCurve.PrivateKey privateKey)
        {
            var sig    = EllipticCurve.Ecdsa.sign(tx.Id, privateKey);
            var sigStr = AddressUtils.TxInSignatureFromSignatureAndPublicKey(sig, privateKey.publicKey());

            for (int i = 0, c = tx.Inputs.Count; i < c; ++i)
            {
                tx.Inputs[i].Signature = sigStr;
            }
        }
        private void SubmitTransferExtrinsic()
        {
            IsBusy = true;
            try
            {
                if (!App.IsPolkadotApiConnected)
                {
                    App.ConnectToNode();
                }

                _ = Task.Run(async() =>
                {
                    try
                    {
                        var sender = new Address("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY");
                        //var pub = AddressUtils.GetPublicKeyFromAddr(sender);
                        var secret    = "0x33A6F3093F158A7109F679410BEF1A0C54168145E0CECB4DF006C1C2FFFB1F09925A225D97AA00682D6A59B95B18780C10D7032336E88F3442B42361F4A66011";
                        var recipient = "5Ef1wcrhb5CVyZjpdYh9Keg81tgUPcsYi9uhNHC9uqjo7956";

                        var pub           = AddressUtils.GetPublicKeyFromAddr(recipient);
                        var compactAmount = Scale.EncodeCompactInteger(BigInteger.Parse("10"));

                        var buf = new byte[pub.Bytes.Length + compactAmount.Bytes.Length];
                        pub.Bytes.CopyTo(buf.AsMemory());
                        compactAmount.Bytes.CopyTo(buf.AsMemory(pub.Bytes.Length));
                        Trace.WriteLine("Transfer Buf: " + buf.ToPrefixedHexString());

                        var call        = new TransferCall(pub, BigInteger.Parse("10"));
                        var encodedCall = PolkadotApi.Serializer.Serialize(call);
                        Trace.WriteLine("Transfer Call: " + encodedCall.ToPrefixedHexString());

                        var tcs = new TaskCompletionSource <string>();
                        var sid = PolkadotApi.SubmitAndSubcribeExtrinsic(encodedCall, "balances", "transfer", sender, secret, str => tcs.SetResult(str));
                        Trace.WriteLine(sid);

                        var result = await tcs.Task.WithTimeout(TimeSpan.FromSeconds(30));
                        PolkadotApi.UnsubscribeStorage(sid);
                        Trace.WriteLine(result);
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex);
                    }
                });
            }
            catch (System.Exception ex)
            {
                Trace.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #18
0
    public void Create()
    {
        if (_savingInProgress)
        {
            return;
        }

        _savingInProgress = true;

        foreach (var validator in AllValidators())
        {
            validator.Validate();
        }

        if (AllValidators().SelectMany(v => v.ValidationErrors).Any())
        {
            return;
        }

        var size      = (uint)CustomDataSize();
        var address   = GameSettings.Address;
        var publicKey = AddressUtils.GetPublicKeyFromAddr(address);


        var fieldsSchema = _fieldScripts
                           .Select(f => new NftFieldSchema(f.FieldName, f.FieldSize ?? 0))
                           .ToList();


        void Cleanup()
        {
            NftClient.CollectionManagement.CollectionCreated -= Handler;
            _updateQueue.Enqueue(() => onCloseCollection?.Invoke());
            _savingInProgress = false;
        }

        void Handler(object sender, Created created)
        {
            if (publicKey.Bytes.SequenceEqual(created.Account.Bytes))
            {
                var schema = new NftCollectionSchema(fieldsSchema, created.Id);
                schema.Save();
                Cleanup();
            }
        }

        NftClient.CollectionManagement.CollectionCreated += Handler;

        var createCollection = new CreateCollection(nameField.text, descriptionField.text, tokenPrefixField.text, new CollectionMode(new Nft(size)));

        NftClient.CollectionManagement.CreateCollection(createCollection, new Address(address), GameSettings.PrivateKey);
    }
Example #19
0
    /// <summary>
    /// Method called every time the text in the input field changed.
    /// Sets the button to interactable if the text is a valid ethereum address.
    /// </summary>
    private void OnAddressChanged()
    {
        isInvalidAddress = !AddressUtils.IsValidEthereumAddress(addressField.Text);

        if (isInvalidAddress)
        {
            CheckInvalidAddress();
        }
        else
        {
            CheckValidAddress();
        }
    }
Example #20
0
        public async Task TransferFromFailsForNotApprovedAccount()
        {
            var key = await CreateTestAliceItem();

            using var client = CreateClient();
            client.ItemManagement.TransferFrom(new TransferFrom(new Address(Configuration.Alice.Address), new Address(Configuration.Charlie.Address), key, 0), new Address(Configuration.Bob.Address), Configuration.Bob.PrivateKey);

            await WaitBlocks(2);

            var item = client.ItemManagement.GetNftItem(key);

            Assert.Equal(AddressUtils.GetPublicKeyFromAddr(Configuration.Alice.Address).Bytes, item !.Owner.Bytes);
        }
Example #21
0
        public void Serialize(Stream stream, object value, IBinarySerializer serializer, object[] parameters)
        {
            var address = (Address)value;

            if (address == null)
            {
                return;
            }

            var key = AddressUtils.GetPublicKeyFromAddr(address).Bytes;

            serializer.Serialize(key, stream);
        }
Example #22
0
        public IActionResult PostMultipleAddresses([FromBody] IEnumerable <Address> addresses)
        {
            using (var scope = new TransactionScope())
            {
                foreach (var address in addresses)
                {
                    address.AggregateCity = AddressUtils.GetAggregateCity(address, _addressRepository.GetAggregateAddresses());
                    _addressRepository.InsertAddress(address);
                }
                scope.Complete();

                return(CreatedAtAction(nameof(Get), new { id = addresses.Select(a => a.ID) }));
            }
        }
        static void Main(string[] args)
        {
            // This is a manual test due to lack of test DOTs
            if (args.Length < 4)
            {
                Console.WriteLine("This is intended to be a manual test");
                Console.WriteLine("Usage: ");
                Console.WriteLine("<sender address> <recipient address> <amount in fDOTs> <sender private key (hex)>");
                Console.WriteLine("success");
            }
            else
            {
                var senderAddr          = args[0];
                var recipientAddr       = args[1];
                var amountStr           = args[2];
                var senderPrivateKeyStr = args[3];

                using (IApplication app = PolkaApi.GetAppication())
                {
                    // Receiving address public key
                    var pk = AddressUtils.GetPublicKeyFromAddr(recipientAddr);

                    // Compact-encode amount
                    var compactAmount = Scale.EncodeCompactInteger(BigInteger.Parse(amountStr));

                    var buf = new byte[pk.Bytes.Length + compactAmount.Bytes.Length];
                    pk.Bytes.CopyTo(buf.AsMemory());
                    compactAmount.Bytes.CopyTo(buf.AsMemory(pk.Bytes.Length));

                    app.Connect();
                    var exHash = app.SubmitExtrinsic(buf, "balances", "transfer", new Address(senderAddr), senderPrivateKeyStr);

                    Console.WriteLine($"Sent extrinsic with hash: {exHash} ");
                    Console.WriteLine("Now let's try to cancel it... ");

                    try
                    {
                        app.RemoveExtrinsic(exHash);
                    }
                    catch (ApplicationException)
                    {
                        Console.WriteLine("Yeah, looks like canceling is not yet supported");
                    }

                    app.Disconnect();
                }
            }
        }
        /// <summary>
        /// Gets the bytes for this <see cref="AbstractGameVariable"/>.
        ///
        /// Process.MainModule.BaseAddress is where the process has its memory start point.
        /// <see cref="LocalBaseAddress"/> bytes ahead of the process base address brings us to 4 bytes (for a 32-bit application), which contain a memory address.
        ///
        /// Use that memory address and add the <see cref="Offset"/> to it to get to the bytes that contain the actual value.
        /// Note that in the second read the process's base address is not needed.
        /// </summary>
        public void Scan()
        {
            try
            {
                Memory memory = Scanner.Instance.Memory;

                byte[] bytes = memory.Read(memory.ReadProcess.MainModule.BaseAddress + LocalBaseAddress, PointerSize, out _);
                int    ptr   = AddressUtils.ToDec(AddressUtils.MakeAddress(bytes));

                Bytes = memory.Read(new IntPtr(ptr) + Offset, Size, out _);
            }
            catch (Exception ex)
            {
                Logging.Log.Error($"Error scanning {typeof(T)} variable", ex);
            }
        }
Example #25
0
        public object Deserialize(Type type, Stream stream, IBinarySerializer deserializer, object[] parameters)
        {
            var key = new byte[32];

            stream.Read(key, 0, key.Length);

            var address = AddressUtils.GetAddrFromPublicKey(new PublicKey()
            {
                Bytes = key
            });

            return(new Address()
            {
                Symbols = address
            });
        }
Example #26
0
        public static Socks5Response FromRequest(Socks5Request request, IPEndPoint bindedEndPoint)
        {
            var resp = new Socks5Response
            {
                Version  = request.Version,
                Response = SocksResponse.SUCCESS,
                RSV      = request.RSV,
                Remote   = new SocksRemote()
                {
                    AddressType = bindedEndPoint.AddressFamily == AddressFamily.InterNetworkV6 ? SocksAddressType.IPV6 : SocksAddressType.IPV4,
                    Address     = AddressUtils.GetVaildLocalIpAddress(bindedEndPoint),
                    Port        = (ushort)bindedEndPoint.Port,
                }
            };

            return(resp);
        }
Example #27
0
        public async Task ApproveAddsAccountToApprovedList()
        {
            var key = await CreateTestAliceItem();

            using var client = CreateClient();
            var publicKey2        = AddressUtils.GetPublicKeyFromAddr(Configuration.Bob.Address);
            var approveListBefore = client.ItemManagement.GetApproved(key);

            if (approveListBefore != null)
            {
                Assert.DoesNotContain(approveListBefore !.ApprovedAccounts, a => a.Bytes.ToHexString().Equals(publicKey2.Bytes.ToHexString()));
            }

            client.ItemManagement.Approve(new Approve(new Address(Configuration.Bob.Address), key),
                                          new Address(Configuration.Alice.Address), Configuration.Alice.PrivateKey);

            await WaitBlocks(2);

            var approveList = client.ItemManagement.GetApproved(key);

            Assert.Contains(approveList !.ApprovedAccounts, a => a.Bytes.ToHexString().Equals(publicKey2.Bytes.ToHexString()));
        }
Example #28
0
        static void Main(string[] args)
        {
            // This is a manual test due to lack of test DOTs
            //if (args.Length < 4)
            //{
            //    Console.WriteLine("This is intended to be a manual test");
            //    Console.WriteLine("Usage: ");
            //    Console.WriteLine("<sender address> <recipient address> <amount in fDOTs> <sender private key (hex)>");
            //    Console.WriteLine("success");
            //}
            //else
            //{


            var senderAddr          = "5GuuxfuxbvaiwteUrV9U7Mj2Fz7TWK84WhLaZdMMJRvSuzr4";
            var recipientAddr       = "5HQdHxuPgQ1BpJasmm5ZzfSk5RDvYiH6YHfDJVE8jXmp4eig";
            var amountStr           = "1000000000000";
            var senderPrivateKeyStr = "0xa81056d713af1ff17b599e60d287952e89301b5208324a0529b62dc7369c745defc9c8dd67b7c59b201bc164163a8978d40010c22743db142a47f2e064480d4b";

            using (IApplication app = PolkaApi.GetAppication())
            {
                // Receiving address public key
                var pk = AddressUtils.GetPublicKeyFromAddr(recipientAddr);

                // Compact-encode amount
                var compactAmount = Scale.EncodeCompactInteger(BigInteger.Parse(amountStr));

                var buf = new byte[pk.Bytes.Length + compactAmount.Bytes.Length];
                pk.Bytes.CopyTo(buf.AsMemory());
                compactAmount.Bytes.CopyTo(buf.AsMemory(pk.Bytes.Length));

                app.Connect();
                var result = app.SubmitExtrinsic(buf, "balances", "transfer", new Address(senderAddr), senderPrivateKeyStr);
                Console.WriteLine(result);
                app.Disconnect();
            }
            //     }
        }
Example #29
0
        public override async Task Process(NftOutgoingTransaction outgoing)
        {
            var account = AddressUtils.GetAddrFromPublicKey(new PublicKey()
            {
                Bytes = outgoing.RecipientPublicKeyBytes
            });

            _logger.LogInformation("Calling Nft.Transfer({Account}, {CollectionId}, {TokenId}, {Value})", account, outgoing.CollectionId, outgoing.TokenId, outgoing.Value);
            var recipient = new PublicKey()
            {
                Bytes = outgoing.RecipientPublicKeyBytes
            };

            await this.CallSubstrate(
                _logger,
                _configuration.MatcherContractPublicKey,
                _configuration.UniqueEndpoint,
                new Address(_configuration.MarketplaceUniqueAddress),
                _configuration.MarketplacePrivateKeyBytes,
                app => new TransferCall(recipient, (uint)outgoing.CollectionId, (uint)outgoing.TokenId, outgoing.Value));

            _logger.LogInformation("Successfully called Nft.Transfer({Account}, {CollectionId}, {TokenId}, {Value})", account, outgoing.CollectionId, outgoing.TokenId, outgoing.Value);
        }
Example #30
0
        static void Main(string[] args)
        {
            // This is a manual test due to lack of test DOTs
            if (args.Length < 4)
            {
                Console.WriteLine("This is intended to be a manual test");
                Console.WriteLine("Usage: ");
                Console.WriteLine("<sender address> <recipient address> <amount in fDOTs> <sender private key (hex)>");
                Console.WriteLine("success");
            }
            else
            {
                var senderAddr          = args[0];
                var recipientAddr       = args[1];
                var amountStr           = args[2];
                var senderPrivateKeyStr = args[3];

                using (IApplication app = PolkaApi.GetAppication())
                {
                    // Receiving address public key
                    var pk = AddressUtils.GetPublicKeyFromAddr(recipientAddr);

                    // Compact-encode amount
                    var compactAmount = Scale.EncodeCompactInteger(BigInteger.Parse(amountStr));

                    var buf = new byte[pk.Bytes.Length + compactAmount.Bytes.Length];
                    pk.Bytes.CopyTo(buf.AsMemory());
                    compactAmount.Bytes.CopyTo(buf.AsMemory(pk.Bytes.Length));

                    app.Connect();
                    var result = app.SubmitExtrinsic(buf, "balances", "transfer", new Address(senderAddr), senderPrivateKeyStr);
                    Console.WriteLine(result);
                    app.Disconnect();
                }
            }
        }