Пример #1
0
 public override WAccount GetAccount(UInt160 publicKeyHash)
 {
     using (WalletDataContext ctx = new WalletDataContext(path))
     {
         return GetAccountInternal(ctx.Accounts.FirstOrDefault(p => p.PublicKeyHash == publicKeyHash.ToArray())?.PrivateKeyEncrypted);
     }
 }
Пример #2
0
 public WalletEntry GetEntry(UInt160 scriptHash)
 {
     byte[] redeemScript, encryptedPrivateKey;
     GetEncryptedEntry(scriptHash, out redeemScript, out encryptedPrivateKey);
     if (redeemScript == null || encryptedPrivateKey == null) return null;
     if ((redeemScript.Length - 3) % 34 != 0 || encryptedPrivateKey.Length % 96 != 0) throw new IOException();
     ProtectedMemory.Unprotect(masterKey, MemoryProtectionScope.SameProcess);
     byte[] decryptedPrivateKey;
     using (AesManaged aes = new AesManaged())
     {
         aes.Padding = PaddingMode.None;
         using (ICryptoTransform decryptor = aes.CreateDecryptor(masterKey, iv))
         {
             decryptedPrivateKey = decryptor.TransformFinalBlock(encryptedPrivateKey, 0, encryptedPrivateKey.Length);
         }
     }
     ProtectedMemory.Protect(masterKey, MemoryProtectionScope.SameProcess);
     byte[][] privateKeys = new byte[encryptedPrivateKey.Length / 96][];
     for (int i = 0; i < privateKeys.Length; i++)
     {
         privateKeys[i] = new byte[96];
         Buffer.BlockCopy(decryptedPrivateKey, i * 96, privateKeys[i], 0, 96);
     }
     WalletEntry entry = new WalletEntry(redeemScript, privateKeys);
     Array.Clear(decryptedPrivateKey, 0, decryptedPrivateKey.Length);
     for (int i = 0; i < privateKeys.Length; i++)
     {
         Array.Clear(privateKeys[i], 0, privateKeys[i].Length);
     }
     return entry;
 }
Пример #3
0
 void ISerializable.Deserialize(BinaryReader reader)
 {
     this.AssetId = reader.ReadSerializable<UInt256>();
     this.Value = reader.ReadSerializable<Fixed8>();
     if (Value <= Fixed8.Zero) throw new FormatException();
     this.ScriptHash = reader.ReadSerializable<UInt160>();
 }
Пример #4
0
 public override WAccount GetAccountByScriptHash(UInt160 scriptHash)
 {
     using (WalletDataContext ctx = new WalletDataContext(path))
     {
         byte[] publicKeyHash = ctx.Contracts.FirstOrDefault(p => p.ScriptHash == scriptHash.ToArray())?.PublicKeyHash;
         if (publicKeyHash == null) return null;
         return GetAccountInternal(ctx.Accounts.FirstOrDefault(p => p.PublicKeyHash == publicKeyHash)?.PrivateKeyEncrypted);
     }
 }
Пример #5
0
 public static MultiSigContract Create(UInt160 publicKeyHash, int m, params ECPoint[] publicKeys)
 {
     return new MultiSigContract
     {
         RedeemScript = CreateMultiSigRedeemScript(m, publicKeys),
         PublicKeyHash = publicKeyHash,
         m = m,
         publicKeys = publicKeys
     };
 }
Пример #6
0
 void ISerializable.Deserialize(BinaryReader reader)
 {
     this.Amount = reader.ReadSerializable<Fixed8>();
     if (Amount == Fixed8.Zero) throw new FormatException();
     if (Amount.GetData() % 10000 != 0) throw new FormatException();
     this.Price = reader.ReadSerializable<Fixed8>();
     if (Price <= Fixed8.Zero) throw new FormatException();
     if (Price.GetData() % 10000 != 0) throw new FormatException();
     this.Client = reader.ReadSerializable<UInt160>();
 }
Пример #7
0
 public ViewPrivateKeyDialog(Account account, UInt160 scriptHash)
 {
     InitializeComponent();
     textBox3.Text = Wallet.ToAddress(scriptHash);
     textBox4.Text = account.PublicKey.EncodePoint(true).ToHexString();
     using (account.Decrypt())
     {
         textBox1.Text = account.PrivateKey.ToHexString();
     }
     textBox2.Text = account.Export();
 }
Пример #8
0
 void ISignable.FromUnsignedArray(byte[] value)
 {
     using (MemoryStream ms = new MemoryStream(value, false))
     using (BinaryReader reader = new BinaryReader(ms))
     {
         this.AssetId = reader.ReadSerializable<UInt256>();
         this.ValueAssetId = reader.ReadSerializable<UInt256>();
         this.Agent = reader.ReadSerializable<UInt160>();
         this.Amount = reader.ReadSerializable<Fixed8>();
         this.Price = reader.ReadSerializable<Fixed8>();
         this.Client = reader.ReadSerializable<UInt160>();
         this.Inputs = reader.ReadSerializableArray<TransactionInput>();
     }
 }
Пример #9
0
 protected override void DeserializeExclusiveData(BinaryReader reader)
 {
     this.AssetType = (AssetType)reader.ReadByte();
     if (!Enum.IsDefined(typeof(AssetType), AssetType))
         throw new FormatException();
     this.Name = reader.ReadVarString();
     this.Amount = reader.ReadSerializable<Fixed8>();
     if (Amount == Fixed8.Zero || Amount < -Fixed8.Satoshi) throw new FormatException();
     if (AssetType == AssetType.Share && Amount <= Fixed8.Zero)
         throw new FormatException();
     if (AssetType == AssetType.Currency && Amount != -Fixed8.Satoshi)
         throw new FormatException();
     this.Issuer = ECPoint.DeserializeFrom(reader, ECCurve.Secp256r1);
     this.Admin = reader.ReadSerializable<UInt160>();
 }
Пример #10
0
 private void DeserializeUnsignedInternal(BinaryReader reader, UInt256 asset_id, UInt256 value_asset_id, UInt160 agent)
 {
     AssetId = asset_id;
     ValueAssetId = value_asset_id;
     Agent = agent;
     Amount = reader.ReadSerializable<Fixed8>();
     if (Amount == Fixed8.Zero) throw new FormatException();
     if (Amount.GetData() % 10000 != 0) throw new FormatException();
     Price = reader.ReadSerializable<Fixed8>();
     if (Price <= Fixed8.Zero) throw new FormatException();
     if (Price.GetData() % 10000 != 0) throw new FormatException();
     Client = reader.ReadSerializable<UInt160>();
     Inputs = reader.ReadSerializableArray<TransactionInput>();
     if (Inputs.Distinct().Count() != Inputs.Length)
         throw new FormatException();
 }
Пример #11
0
 public override bool DeleteAccount(UInt160 publicKeyHash)
 {
     bool flag = base.DeleteAccount(publicKeyHash);
     if (flag)
     {
         using (WalletDataContext ctx = new WalletDataContext(DbPath))
         {
             Account account = ctx.Accounts.FirstOrDefault(p => p.PublicKeyHash.SequenceEqual(publicKeyHash.ToArray()));
             if (account != null)
             {
                 ctx.Accounts.Remove(account);
                 ctx.SaveChanges();
             }
         }
     }
     return flag;
 }
Пример #12
0
 protected override void DeserializeExclusiveData(BinaryReader reader)
 {
     this.AssetId = reader.ReadSerializable<UInt256>();
     this.ValueAssetId = reader.ReadSerializable<UInt256>();
     if (AssetId == ValueAssetId) throw new FormatException();
     this.Agent = reader.ReadSerializable<UInt160>();
     this.Orders = new Order[reader.ReadVarInt()];
     for (int i = 0; i < Orders.Length; i++)
     {
         Orders[i] = new Order();
         Orders[i].DeserializeInTransaction(reader, this);
     }
     ulong count = reader.ReadVarInt();
     if (count > 1) throw new FormatException();
     if (count == 0)
     {
         this.SplitOrder = null;
     }
     else
     {
         this.SplitOrder = reader.ReadSerializable<SplitOrder>();
     }
 }
 public override ContractState GetContract(UInt160 hash)
 {
     return(db.TryGet <ContractState>(ReadOptions.Default, DataEntryPrefix.ST_Contract, hash));
 }
Пример #14
0
 void ISerializable.Deserialize(BinaryReader reader)
 {
     ScriptHash = reader.ReadSerializable <UInt160>();
     Key        = reader.ReadBytesWithGrouping();
 }
Пример #15
0
        private static async Task WalletAndTransactionsTest()
        {
            // Create online wallet and import account
            var walletManager   = new WalletManager(new NeoScanRestService(NeoScanNet.MainNet), RpcClient);
            var importedAccount = walletManager.ImportAccount("WIF HERE (or use NEP2 bellow)", "Account_label");
            //var importedAccount = walletManager.ImportAccount("encryptedPrivateKey", "password", "Account_label");

            var neoService = new NeoApiService(RpcClient);

            //invoke test example using Phantasma smart contract
            var method             = "getMailboxFromAddress";                    //operation
            var contractScriptHash = "ed07cffad18f1308db51920d99a2af60ac66a7b3"; // smart contract scripthash
            var script             = NEP6.Helpers.Utils.GenerateScript(contractScriptHash, method,
                                                                       new object[] { "ARcZoZPn1ReBo4LPLvkEteyLu6S2A5cvY2".ToScriptHash().ToArray() });
            var result = await neoService.Contracts.InvokeScript.SendRequestAsync(script.ToHexString());

            var content = Encoding.UTF8.GetString(result.Stack[0].Value.ToString().HexToBytes()); //the way you read a result can vary

            //call contract example using Phantasma smart contract
            var RegisterInboxOperation = "registerMailbox"; //operation
            var user = importedAccount.Address.ToArray();
            var args = new object[] { user, "neomodules" };

            var transaction = await importedAccount.TransactionManager.CallContract("ed07cffad18f1308db51920d99a2af60ac66a7b3",
                                                                                    RegisterInboxOperation, //operation
                                                                                    args,                   // arguments
                                                                                    null,                   // array of transfer outputs you want to attach gas or neo with the contract call (optional)
                                                                                    0m,                     // network fee (optional)
                                                                                    null                    // attributes (optional)
                                                                                    );


            // list of transfer outputs
            var transferOutputWithNep5AndGas = new List <TransferOutput>
            {
                new TransferOutput
                {
                    AssetId    = UInt160.Parse("a58b56b30425d3d1f8902034996fcac4168ef71d"), //  e.g. Script Hash of ASA
                    Value      = BigDecimal.Parse("0.0001", byte.Parse("8")),               // majority of NEP5 tokens have 8 decimals
                    ScriptHash = "AddressScriptHash to sent here".ToScriptHash(),
                },
                new TransferOutput
                {
                    AssetId    = NEP6.Helpers.Utils.GasToken,                  //GAS
                    Value      = BigDecimal.Parse("0.00001", byte.Parse("8")), // GAS has 8 decimals too
                    ScriptHash = "AddressScriptHash to sent here".ToScriptHash(),
                }
            };

            var transferOutputWithOnlyGas = new List <TransferOutput>
            {
                new TransferOutput
                {
                    AssetId    = NEP6.Helpers.Utils.GasToken,                  //GAS
                    Value      = BigDecimal.Parse("0.00001", byte.Parse("8")), // GAS has 8 decimals too
                    ScriptHash = "AddressScriptHash to sent here".ToScriptHash(),
                }
            };

            // Claims unclaimed gas. Does not spent your neo to make gas claimable, you have to do it yourself!
            var claim = await importedAccount.TransactionManager.ClaimGas();

            // Transfer NEP5 and gas with fee
            var invocationTx = await importedAccount.TransactionManager.TransferNep5(null, transferOutputWithNep5AndGas, null, 0.00001m);

            // Send native assets (NEO and GAS) with fee
            var nativeTx = await importedAccount.TransactionManager.SendNativeAsset(null, transferOutputWithOnlyGas, null, 0.0001m);

            // Call contract
            var scriptHash = "a58b56b30425d3d1f8902034996fcac4168ef71d".ToScriptHash().ToArray(); // ASA e.g
            var operation  = "your operation here";
            var arguments  = new object[] { "arg1", "arg2", "etc" };

            // Estimate Gas consumed from contract call
            var estimateContractGasCall =
                await importedAccount.TransactionManager.EstimateGasContractInvocation(scriptHash, operation, arguments);

            // Confirm a transaction
            var confirmedTransaction =
                await importedAccount.TransactionManager.WaitForTxConfirmation(invocationTx.Hash.ToString(), 10000, 10);
        }
Пример #16
0
 public abstract Contract GetContract(UInt160 scriptHash);
Пример #17
0
 public override bool DeleteContract(UInt160 scriptHash)
 {
     bool flag = base.DeleteContract(scriptHash);
     if (flag)
     {
         using (WalletDataContext ctx = new WalletDataContext(DbPath))
         {
             Contract contract = ctx.Contracts.FirstOrDefault(p => p.ScriptHash.SequenceEqual(scriptHash.ToArray()));
             if (contract != null)
             {
                 ctx.Contracts.Remove(contract);
                 ctx.SaveChanges();
             }
         }
     }
     return flag;
 }
Пример #18
0
        /// <summary>
        /// 获取需要校验的脚本Hash值
        /// </summary>
        /// <returns>返回需要校验的脚本Hash值</returns>
        public override UInt160[] GetScriptHashesForVerifying()
        {
            UInt160 issuer = Contract.CreateSignatureRedeemScript(Issuer).ToScriptHash();

            return(base.GetScriptHashesForVerifying().Union(new[] { issuer }).OrderBy(p => p).ToArray());
        }
Пример #19
0
 public abstract WalletEntry FindEntry(UInt160 scriptHash);
Пример #20
0
        private bool OnSendCommand(string[] args)
        {
            if (args.Length < 4 || args.Length > 5)
            {
                Console.WriteLine("error");
                return(true);
            }
            if (Program.Wallet == null)
            {
                Console.WriteLine("You have to open the wallet first.");
                return(true);
            }
            string password = ReadPassword("password");

            if (password.Length == 0)
            {
                Console.WriteLine("cancelled");
                return(true);
            }
            if (!Program.Wallet.VerifyPassword(password))
            {
                Console.WriteLine("Incorrect password");
                return(true);
            }
            UIntBase assetId;

            switch (args[1].ToLower())
            {
            case "neo":
            case "ans":
                assetId = Blockchain.GoverningToken.Hash;
                break;

            case "gas":
            case "anc":
                assetId = Blockchain.UtilityToken.Hash;
                break;

            default:
                assetId = UIntBase.Parse(args[1]);
                break;
            }
            UInt160     scriptHash = Wallet.ToScriptHash(args[2]);
            bool        isSendAll  = string.Equals(args[3], "all", StringComparison.OrdinalIgnoreCase);
            Transaction tx;

            if (isSendAll)
            {
                Coin[] coins = Program.Wallet.FindUnspentCoins().Where(p => p.Output.AssetId.Equals(assetId)).ToArray();
                tx = new ContractTransaction
                {
                    Attributes = new TransactionAttribute[0],
                    Inputs     = coins.Select(p => p.Reference).ToArray(),
                    Outputs    = new[]
                    {
                        new TransactionOutput
                        {
                            AssetId    = (UInt256)assetId,
                            Value      = coins.Sum(p => p.Output.Value),
                            ScriptHash = scriptHash
                        }
                    }
                };
            }
            else
            {
                AssetDescriptor descriptor = new AssetDescriptor(assetId);
                if (!BigDecimal.TryParse(args[3], descriptor.Decimals, out BigDecimal amount))
                {
                    Console.WriteLine("Incorrect Amount Format");
                    return(true);
                }
                Fixed8 fee = args.Length >= 5 ? Fixed8.Parse(args[4]) : Fixed8.Zero;
                tx = Program.Wallet.MakeTransaction(null, new[]
                {
                    new TransferOutput
                    {
                        AssetId    = assetId,
                        Value      = amount,
                        ScriptHash = scriptHash
                    }
                }, fee: fee);
                if (tx == null)
                {
                    Console.WriteLine("Insufficient funds");
                    return(true);
                }
            }
            ContractParametersContext context = new ContractParametersContext(tx);

            Program.Wallet.Sign(context);
            if (context.Completed)
            {
                tx.Scripts = context.GetScripts();
                Program.Wallet.ApplyTransaction(tx);
                LocalNode.Relay(tx);
                Console.WriteLine($"TXID: {tx.Hash}");
            }
            else
            {
                Console.WriteLine("SignatureContext:");
                Console.WriteLine(context.ToString());
            }
            return(true);
        }
Пример #21
0
 protected WalletAccount(UInt160 scriptHash)
 {
     this.ScriptHash = scriptHash;
 }
Пример #22
0
        private bool OnExportKeyCommand(string[] args)
        {
            if (Program.Wallet == null)
            {
                Console.WriteLine("You have to open the wallet first.");
                return(true);
            }
            if (args.Length < 2 || args.Length > 4)
            {
                Console.WriteLine("error");
                return(true);
            }
            UInt160 scriptHash = null;
            string  path       = null;

            if (args.Length == 3)
            {
                try
                {
                    scriptHash = Wallet.ToScriptHash(args[2]);
                }
                catch (FormatException)
                {
                    path = args[2];
                }
            }
            else if (args.Length == 4)
            {
                scriptHash = Wallet.ToScriptHash(args[2]);
                path       = args[3];
            }
            string password = ReadPassword("password");

            if (password.Length == 0)
            {
                Console.WriteLine("cancelled");
                return(true);
            }
            if (!Program.Wallet.VerifyPassword(password))
            {
                Console.WriteLine("Incorrect password");
                return(true);
            }
            IEnumerable <KeyPair> keys;

            if (scriptHash == null)
            {
                keys = Program.Wallet.GetAccounts().Where(p => p.HasKey).Select(p => p.GetKey());
            }
            else
            {
                keys = new[] { Program.Wallet.GetAccount(scriptHash).GetKey() }
            };
            if (path == null)
            {
                foreach (KeyPair key in keys)
                {
                    Console.WriteLine(key.Export());
                }
            }
            else
            {
                File.WriteAllLines(path, keys.Select(p => p.Export()));
            }
            return(true);
        }
Пример #23
0
 public byte[] GetParameter(UInt160 scriptHash, int index)
 {
     return(parameters[GetIndex(scriptHash)][index]);
 }
Пример #24
0
        private void setupAssetStateWithValues(AssetState assetState, out UInt256 assetId, out AssetType assetType, out string name, out Fixed8 amount, out Fixed8 available, out byte precision, out Fixed8 fee, out UInt160 feeAddress, out ECPoint owner, out UInt160 admin, out UInt160 issuer, out uint expiration, out bool isFrozen)
        {
            assetId              = new UInt256(TestUtils.GetByteArray(32, 0x20));
            assetState.AssetId   = assetId;
            assetType            = AssetType.Token;
            assetState.AssetType = assetType;

            name            = "bhp";
            assetState.Name = name;

            amount            = new Fixed8(42);
            assetState.Amount = amount;

            available            = new Fixed8(43);
            assetState.Available = available;

            precision            = 0x42;
            assetState.Precision = precision;

            fee            = new Fixed8(44);
            assetState.Fee = fee;

            feeAddress            = new UInt160(TestUtils.GetByteArray(20, 0x21));
            assetState.FeeAddress = feeAddress;

            owner            = ECPoint.DecodePoint(TestUtils.GetByteArray(1, 0x00), ECCurve.Secp256);
            assetState.Owner = owner;

            admin            = new UInt160(TestUtils.GetByteArray(20, 0x22));
            assetState.Admin = admin;

            issuer            = new UInt160(TestUtils.GetByteArray(20, 0x23));
            assetState.Issuer = issuer;

            expiration            = 42u;
            assetState.Expiration = expiration;

            isFrozen            = true;
            assetState.IsFrozen = isFrozen;
        }
Пример #25
0
 void ISerializable.Deserialize(BinaryReader reader)
 {
     this.AssetId = reader.ReadSerializable<UInt256>();
     this.Value = reader.ReadSerializable<Fixed8>();
     this.ScriptHash = reader.ReadSerializable<UInt160>();
 }
 public void Deserialize(BinaryReader reader)
 {
     PublicKeyHash = reader.ReadSerializable <UInt160>();
     ParameterList = reader.ReadVarBytes().Select(p => (ContractParameterType)p).ToArray();
     Script        = reader.ReadVarBytes();
 }
Пример #27
0
        protected override void GetEncryptedEntry(UInt160 scriptHash, out byte[] redeemScript, out byte[] encryptedPrivateKey)
        {
            using (WalletDataContext ctx = new WalletDataContext(connectionString))
            {
                //Account account = ctx.Accounts.FirstOrDefault(p => p.ScriptHash == scriptHash.ToArray());
                //It throws a NotSupportedException:
                //LINQ to Entities does not recognize the method 'Byte[] ToArray()' method, and this method cannot be translated into a store expression.
                //I don't know why.
                //So,
                byte[] temp = scriptHash.ToArray();
                Account account = ctx.Accounts.FirstOrDefault(p => p.ScriptHash == temp);
                //It works!

                if (account == null)
                {
                    redeemScript = null;
                    encryptedPrivateKey = null;
                    return;
                }
                redeemScript = account.RedeemScript;
                encryptedPrivateKey = account.PrivateKeyEncrypted;
            }
        }
Пример #28
0
        private JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getbestblockhash":
            {
                return(GetBestBlockHash());
            }

            case "getblock":
            {
                JObject key     = _params[0];
                bool    verbose = _params.Count >= 2 && _params[1].AsBoolean();
                return(GetBlock(key, verbose));
            }

            case "getblockcount":
            {
                return(GetBlockCount());
            }

            case "getblockhash":
            {
                uint height = uint.Parse(_params[0].AsString());
                return(GetBlockHash(height));
            }

            case "getblockheader":
            {
                JObject key     = _params[0];
                bool    verbose = _params.Count >= 2 && _params[1].AsBoolean();
                return(GetBlockHeader(key, verbose));
            }

            case "getblocksysfee":
            {
                uint height = uint.Parse(_params[0].AsString());
                return(GetBlockSysFee(height));
            }

            case "getconnectioncount":
            {
                return(GetConnectionCount());
            }

            case "getcontractstate":
            {
                UInt160 script_hash = UInt160.Parse(_params[0].AsString());
                return(GetContractState(script_hash));
            }

            case "getpeers":
            {
                return(GetPeers());
            }

            case "getrawmempool":
            {
                bool shouldGetUnverified = _params.Count >= 1 && _params[0].AsBoolean();
                return(GetRawMemPool(shouldGetUnverified));
            }

            case "getrawtransaction":
            {
                UInt256 hash    = UInt256.Parse(_params[0].AsString());
                bool    verbose = _params.Count >= 2 && _params[1].AsBoolean();
                return(GetRawTransaction(hash, verbose));
            }

            case "getstorage":
            {
                UInt160 script_hash = UInt160.Parse(_params[0].AsString());
                byte[]  key         = _params[1].AsString().HexToBytes();
                return(GetStorage(script_hash, key));
            }

            case "gettransactionheight":
            {
                UInt256 hash = UInt256.Parse(_params[0].AsString());
                return(GetTransactionHeight(hash));
            }

            case "getvalidators":
            {
                return(GetValidators());
            }

            case "getversion":
            {
                return(GetVersion());
            }

            case "invokefunction":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                string              operation   = _params[1].AsString();
                ContractParameter[] args        = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                return(InvokeFunction(script_hash, operation, args));
            }

            case "invokescript":
            {
                byte[] script = _params[0].AsString().HexToBytes();
                return(InvokeScript(script));
            }

            case "listplugins":
            {
                return(ListPlugins());
            }

            case "sendrawtransaction":
            {
                Transaction tx = _params[0].AsString().HexToBytes().AsSerializable <Transaction>();
                return(SendRawTransaction(tx));
            }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(SubmitBlock(block));
            }

            case "validateaddress":
            {
                string address = _params[0].AsString();
                return(ValidateAddress(address));
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Пример #29
0
        public JObject FindStates(JArray _params)
        {
            var root_hash = UInt256.Parse(_params[0].AsString());

            if (!Settings.Default.FullState && StateStore.Singleton.CurrentLocalRootHash != root_hash)
            {
                throw new RpcException(-100, "Old state not supported");
            }
            var script_hash = UInt160.Parse(_params[1].AsString());
            var prefix      = Convert.FromBase64String(_params[2].AsString());

            byte[] key = Array.Empty <byte>();
            if (3 < _params.Count)
            {
                key = Convert.FromBase64String(_params[3].AsString());
            }
            int count = Settings.Default.MaxFindResultItems;

            if (4 < _params.Count)
            {
                count = int.Parse(_params[4].AsString());
            }
            if (Settings.Default.MaxFindResultItems < count)
            {
                count = Settings.Default.MaxFindResultItems;
            }
            using var store = StateStore.Singleton.GetStoreSnapshot();
            var trie     = new Trie(store, root_hash);
            var contract = GetHistoricalContractState(trie, script_hash);

            if (contract is null)
            {
                throw new RpcException(-100, "Unknown contract");
            }
            StorageKey pkey = new()
            {
                Id  = contract.Id,
                Key = prefix,
            };
            StorageKey fkey = new()
            {
                Id  = pkey.Id,
                Key = key,
            };
            JObject json = new();
            JArray  jarr = new();
            int     i    = 0;

            foreach (var(ikey, ivalue) in trie.Find(pkey.ToArray(), 0 < key.Length ? fkey.ToArray() : null))
            {
                if (count < i)
                {
                    break;
                }
                if (i < count)
                {
                    JObject j = new();
                    j["key"]   = Convert.ToBase64String(ikey.Span);
                    j["value"] = Convert.ToBase64String(ivalue.Span);
                    jarr.Add(j);
                }
                i++;
            }
            ;
            if (0 < jarr.Count)
            {
                json["firstProof"] = GetProof(trie, contract.Id, Convert.FromBase64String(jarr.First()["key"].AsString()));
            }
            if (1 < jarr.Count)
            {
                json["lastProof"] = GetProof(trie, contract.Id, Convert.FromBase64String(jarr.Last()["key"].AsString()));
            }
            json["truncated"] = count < i;
            json["results"]   = jarr;
            return(json);
        }
Пример #30
0
        private void button3_Click(object sender, EventArgs e)
        {
            string            s         = textBox2.Text;
            ContractParameter parameter = new ContractParameter();

            if (string.Equals(s, "true", StringComparison.OrdinalIgnoreCase))
            {
                parameter.Type  = ContractParameterType.Boolean;
                parameter.Value = true;
            }
            else if (string.Equals(s, "false", StringComparison.OrdinalIgnoreCase))
            {
                parameter.Type  = ContractParameterType.Boolean;
                parameter.Value = false;
            }
            else if (long.TryParse(s, out long num))
            {
                parameter.Type  = ContractParameterType.Integer;
                parameter.Value = num;
            }
            else if (s.StartsWith("0x"))
            {
                if (UInt160.TryParse(s, out UInt160 i160))
                {
                    parameter.Type  = ContractParameterType.Hash160;
                    parameter.Value = i160;
                }
                else if (UInt256.TryParse(s, out UInt256 i256))
                {
                    parameter.Type  = ContractParameterType.Hash256;
                    parameter.Value = i256;
                }
                else if (BigInteger.TryParse(s.Substring(2), NumberStyles.AllowHexSpecifier, null, out BigInteger bi))
                {
                    parameter.Type  = ContractParameterType.Integer;
                    parameter.Value = bi;
                }
                else
                {
                    parameter.Type  = ContractParameterType.String;
                    parameter.Value = s;
                }
            }
            else if (ECPoint.TryParse(s, ECCurve.Secp256r1, out ECPoint point))
            {
                parameter.Type  = ContractParameterType.PublicKey;
                parameter.Value = point;
            }
            else
            {
                try
                {
                    parameter.Value = s.HexToBytes();
                    parameter.Type  = ContractParameterType.ByteArray;
                }
                catch (FormatException)
                {
                    parameter.Type  = ContractParameterType.String;
                    parameter.Value = s;
                }
            }
            parameters.Add(parameter);
            listView1.Items.Add(new ListViewItem(new[]
            {
                new ListViewItem.ListViewSubItem
                {
                    Name = "index",
                    Text = $"[{listView1.Items.Count}]"
                },
                new ListViewItem.ListViewSubItem
                {
                    Name = "type",
                    Text = parameter.Type.ToString()
                },
                new ListViewItem.ListViewSubItem
                {
                    Name = "value",
                    Text = parameter.ToString()
                }
            }, -1)
            {
                Tag = parameter
            });
        }
Пример #31
0
 protected override void DeleteAccount(UInt160 publicKeyHash)
 {
     using (WalletDataContext ctx = new WalletDataContext(connectionString))
     {
         DbAccount account = ctx.Accounts.FirstOrDefault(p => p.PublicKeyHash == publicKeyHash.ToArray());
         if (account != null)
         {
             ctx.Contracts.RemoveRange(ctx.Contracts.Where(p => p.PublicKeyHash == publicKeyHash.ToArray()));
             ctx.Accounts.Remove(account);
             ctx.SaveChanges();
         }
     }
 }
Пример #32
0
 public abstract bool Contains(UInt160 scriptHash);
Пример #33
0
 protected abstract void GetEncryptedEntry(UInt160 scriptHash, out byte[] redeemScript, out byte[] encryptedPrivateKey);
Пример #34
0
 public abstract bool DeleteAccount(UInt160 scriptHash);
Пример #35
0
 protected override void OnTransferred(ApplicationEngine engine, UInt160 from, NameState token)
 {
     token.Admin = null;
 }
Пример #36
0
 public abstract WalletAccount GetAccount(UInt160 scriptHash);
Пример #37
0
        public void TestSerializeAndDeserializeConsensusContext()
        {
            var consensusContext = new ConsensusContext(null, null)
            {
                Block = new Block
                {
                    PrevHash      = Blockchain.GenesisBlock.Hash,
                    Index         = 1,
                    Timestamp     = 4244941711,
                    NextConsensus = UInt160.Parse("5555AAAA5555AAAA5555AAAA5555AAAA5555AAAA"),
                    ConsensusData = new ConsensusData
                    {
                        PrimaryIndex = 6
                    }
                },
                ViewNumber = 2,
                Validators = new ECPoint[7]
                {
                    ECPoint.Parse("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70", Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d", Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e", Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554", Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093", Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", Cryptography.ECC.ECCurve.Secp256r1),
                    ECPoint.Parse("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a", Cryptography.ECC.ECCurve.Secp256r1)
                },
                MyIndex = -1
            };
            var testTx1 = TestUtils.CreateRandomHashTransaction();
            var testTx2 = TestUtils.CreateRandomHashTransaction();

            int txCountToInlcude = 256;

            consensusContext.TransactionHashes = new UInt256[txCountToInlcude];

            Transaction[] txs = new Transaction[txCountToInlcude];
            for (int i = 0; i < txCountToInlcude; i++)
            {
                txs[i] = TestUtils.CreateRandomHashTransaction();
                consensusContext.TransactionHashes[i] = txs[i].Hash;
            }
            // consensusContext.TransactionHashes = new UInt256[2] {testTx1.Hash, testTx2.Hash};
            consensusContext.Transactions = txs.ToDictionary(p => p.Hash);

            consensusContext.PreparationPayloads = new ConsensusPayload[consensusContext.Validators.Length];
            var prepareRequestMessage = new PrepareRequest
            {
                TransactionHashes = consensusContext.TransactionHashes,
                Timestamp         = 23
            };

            consensusContext.PreparationPayloads[6] = MakeSignedPayload(consensusContext, prepareRequestMessage, 6, new[] { (byte)'3', (byte)'!' });
            consensusContext.PreparationPayloads[0] = MakeSignedPayload(consensusContext, new PrepareResponse {
                PreparationHash = consensusContext.PreparationPayloads[6].Hash
            }, 0, new[] { (byte)'t', (byte)'e' });
            consensusContext.PreparationPayloads[1] = MakeSignedPayload(consensusContext, new PrepareResponse {
                PreparationHash = consensusContext.PreparationPayloads[6].Hash
            }, 1, new[] { (byte)'s', (byte)'t' });
            consensusContext.PreparationPayloads[2] = null;
            consensusContext.PreparationPayloads[3] = MakeSignedPayload(consensusContext, new PrepareResponse {
                PreparationHash = consensusContext.PreparationPayloads[6].Hash
            }, 3, new[] { (byte)'1', (byte)'2' });
            consensusContext.PreparationPayloads[4] = null;
            consensusContext.PreparationPayloads[5] = null;

            consensusContext.CommitPayloads = new ConsensusPayload[consensusContext.Validators.Length];
            using (SHA256 sha256 = SHA256.Create())
            {
                consensusContext.CommitPayloads[3] = MakeSignedPayload(consensusContext, new Commit {
                    Signature = sha256.ComputeHash(testTx1.Hash.ToArray())
                }, 3, new[] { (byte)'3', (byte)'4' });
                consensusContext.CommitPayloads[6] = MakeSignedPayload(consensusContext, new Commit {
                    Signature = sha256.ComputeHash(testTx2.Hash.ToArray())
                }, 3, new[] { (byte)'6', (byte)'7' });
            }

            consensusContext.Block.Timestamp = TimeProvider.Current.UtcNow.ToTimestampMS();

            consensusContext.ChangeViewPayloads    = new ConsensusPayload[consensusContext.Validators.Length];
            consensusContext.ChangeViewPayloads[0] = MakeSignedPayload(consensusContext, new ChangeView {
                ViewNumber = 1, Timestamp = 6
            }, 0, new[] { (byte)'A' });
            consensusContext.ChangeViewPayloads[1] = MakeSignedPayload(consensusContext, new ChangeView {
                ViewNumber = 1, Timestamp = 5
            }, 1, new[] { (byte)'B' });
            consensusContext.ChangeViewPayloads[2] = null;
            consensusContext.ChangeViewPayloads[3] = MakeSignedPayload(consensusContext, new ChangeView {
                ViewNumber = 1, Timestamp = uint.MaxValue
            }, 3, new[] { (byte)'C' });
            consensusContext.ChangeViewPayloads[4] = null;
            consensusContext.ChangeViewPayloads[5] = null;
            consensusContext.ChangeViewPayloads[6] = MakeSignedPayload(consensusContext, new ChangeView {
                ViewNumber = 1, Timestamp = 1
            }, 6, new[] { (byte)'D' });

            consensusContext.LastChangeViewPayloads = new ConsensusPayload[consensusContext.Validators.Length];

            var copiedContext = TestUtils.CopyMsgBySerialization(consensusContext, new ConsensusContext(null, null));

            copiedContext.Block.PrevHash.Should().Be(consensusContext.Block.PrevHash);
            copiedContext.Block.Index.Should().Be(consensusContext.Block.Index);
            copiedContext.ViewNumber.Should().Be(consensusContext.ViewNumber);
            copiedContext.Validators.ShouldAllBeEquivalentTo(consensusContext.Validators);
            copiedContext.MyIndex.Should().Be(consensusContext.MyIndex);
            copiedContext.Block.ConsensusData.PrimaryIndex.Should().Be(consensusContext.Block.ConsensusData.PrimaryIndex);
            copiedContext.Block.Timestamp.Should().Be(consensusContext.Block.Timestamp);
            copiedContext.Block.NextConsensus.Should().Be(consensusContext.Block.NextConsensus);
            copiedContext.TransactionHashes.ShouldAllBeEquivalentTo(consensusContext.TransactionHashes);
            copiedContext.Transactions.ShouldAllBeEquivalentTo(consensusContext.Transactions);
            copiedContext.Transactions.Values.ShouldAllBeEquivalentTo(consensusContext.Transactions.Values);
            copiedContext.PreparationPayloads.ShouldAllBeEquivalentTo(consensusContext.PreparationPayloads);
            copiedContext.CommitPayloads.ShouldAllBeEquivalentTo(consensusContext.CommitPayloads);
            copiedContext.ChangeViewPayloads.ShouldAllBeEquivalentTo(consensusContext.ChangeViewPayloads);
        }
Пример #38
0
 public static object Call(UInt160 scriptHash, string method, object[] arguments)
 {
     return(Contract.Call(scriptHash, method, arguments));
 }
 public override AccountState GetAccountState(UInt160 script_hash)
 {
     return(db.TryGet <AccountState>(ReadOptions.Default, DataEntryPrefix.ST_Account, script_hash));
 }
Пример #40
0
        private protected async ContractTask <bool> Transfer(ApplicationEngine engine, UInt160 to, byte[] tokenId, StackItem data)
        {
            if (to is null)
            {
                throw new ArgumentNullException(nameof(to));
            }
            StorageKey key_token = CreateStorageKey(Prefix_Token).Add(GetKey(tokenId));
            TokenState token     = engine.Snapshot.TryGet(key_token)?.GetInteroperable <TokenState>();
            UInt160    from      = token.Owner;

            if (!from.Equals(engine.CallingScriptHash) && !engine.CheckWitnessInternal(from))
            {
                return(false);
            }
            if (!from.Equals(to))
            {
                token = engine.Snapshot.GetAndChange(key_token).GetInteroperable <TokenState>();
                StorageKey      key_from = CreateStorageKey(Prefix_Account).Add(from);
                NFTAccountState account  = engine.Snapshot.GetAndChange(key_from).GetInteroperable <NFTAccountState>();
                account.Remove(tokenId);
                if (account.Balance.IsZero)
                {
                    engine.Snapshot.Delete(key_from);
                }
                token.Owner = to;
                StorageKey key_to = CreateStorageKey(Prefix_Account).Add(to);
                account = engine.Snapshot.GetAndChange(key_to, () => new StorageItem(new NFTAccountState())).GetInteroperable <NFTAccountState>();
                account.Add(tokenId);
                OnTransferred(engine, from, token);
            }
            await PostTransfer(engine, from, to, tokenId, data);

            return(true);
        }
Пример #41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WalletAccount"/> class.
 /// </summary>
 /// <param name="scriptHash">The hash of the account.</param>
 /// <param name="settings">The <see cref="Neo.ProtocolSettings"/> to be used by the wallet.</param>
 protected WalletAccount(UInt160 scriptHash, ProtocolSettings settings)
 {
     this.ProtocolSettings = settings;
     this.ScriptHash       = scriptHash;
 }
Пример #42
0
 /// <summary>
 /// Called when a token is transferred.
 /// </summary>
 /// <param name="engine">The <see cref="ApplicationEngine"/> that is executing the contract.</param>
 /// <param name="from">The account where the token is transferred from.</param>
 /// <param name="token">The token that is transferred.</param>
 protected virtual void OnTransferred(ApplicationEngine engine, UInt160 from, TokenState token)
 {
 }
Пример #43
0
 protected override void DeleteEntry(UInt160 scriptHash)
 {
     using (WalletDataContext ctx = new WalletDataContext(connectionString))
     {
         Account account = ctx.Accounts.FirstOrDefault(p => p.ScriptHash == scriptHash.ToArray());
         if (account != null)
         {
             ctx.Accounts.Remove(account);
             ctx.SaveChanges();
         }
     }
 }
Пример #44
0
 protected abstract void DeleteAccount(UInt160 publicKeyHash);
Пример #45
0
 protected override void SaveEncryptedEntry(UInt160 scriptHash, byte[] redeemScript, byte[] encryptedPrivateKey)
 {
     using (WalletDataContext ctx = new WalletDataContext(connectionString))
     {
         byte[] scriptHashBytes = scriptHash.ToArray();
         Account account = ctx.Accounts.FirstOrDefault(p => p.ScriptHash == scriptHashBytes);
         if (account == null)
         {
             account = ctx.Accounts.Add(new Account
             {
                 ScriptHash = scriptHash.ToArray(),
                 RedeemScript = redeemScript,
                 PrivateKeyEncrypted = encryptedPrivateKey
             });
         }
         else
         {
             account.RedeemScript = redeemScript;
             account.PrivateKeyEncrypted = encryptedPrivateKey;
         }
         ctx.SaveChanges();
     }
 }
Пример #46
0
 public abstract Account GetAccount(UInt160 publicKeyHash);
Пример #47
0
        private async ContractTask PostTransfer(ApplicationEngine engine, UInt160 from, UInt160 to, byte[] tokenId, StackItem data)
        {
            engine.SendNotification(Hash, "Transfer",
                                    new Array {
                from?.ToArray() ?? StackItem.Null, to?.ToArray() ?? StackItem.Null, 1, tokenId
            });

            if (to is not null && ContractManagement.GetContract(engine.Snapshot, to) is not null)
            {
                await engine.CallFromNativeContract(Hash, to, "onNEP11Payment", from?.ToArray() ?? StackItem.Null, 1, tokenId, data);
            }
        }
Пример #48
0
 public Task <Contract> GetContract(UInt160 hash)
 {
     throw new NotImplementedException();
 }
Пример #49
0
 public static string ToAddress(UInt160 scriptHash)
 {
     byte[] data = new byte[] { CoinVersion }.Concat(scriptHash.ToArray()).ToArray();
     return Base58.Encode(data.Concat(data.Sha256().Sha256().Take(4)).ToArray());
 }
Пример #50
0
 public void DeleteEntry(UInt160 scriptHash)
 {
     accounts.Remove(scriptHash);
 }
Пример #51
0
 public abstract Account GetAccountByScriptHash(UInt160 scriptHash);
Пример #52
0
 protected abstract void DeleteEntry(UInt160 scriptHash);
Пример #53
0
 public override Contract GetContract(UInt160 scriptHash)
 {
     using (WalletDataContext ctx = new WalletDataContext(connectionString))
     {
         byte[] redeemScript = ctx.Contracts.FirstOrDefault(p => p.ScriptHash == scriptHash.ToArray())?.RedeemScript;
         if (redeemScript == null) return null;
         return new Contract(redeemScript);
     }
 }
Пример #54
0
 protected StorageKey CreateAccountKey(UInt160 account)
 {
     return(CreateStorageKey(Prefix_Account, account));
 }
Пример #55
0
 public abstract AccountState GetAccountState(UInt160 script_hash);
Пример #56
0
 public abstract ContractState GetContract(UInt160 hash);
Пример #57
0
        protected virtual bool Transfer(ApplicationEngine engine, UInt160 from, UInt160 to, BigInteger amount)
        {
            if (amount.Sign < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(amount));
            }
            if (!from.Equals(engine.CallingScriptHash) && !InteropService.CheckWitness(engine, from))
            {
                return(false);
            }
            ContractState contract_to = engine.Snapshot.Contracts.TryGet(to);

            if (contract_to?.Payable == false)
            {
                return(false);
            }
            StorageKey  key_from     = CreateAccountKey(from);
            StorageItem storage_from = engine.Snapshot.Storages.TryGet(key_from);

            if (amount.IsZero)
            {
                if (storage_from != null)
                {
                    TState state_from = new TState();
                    state_from.FromByteArray(storage_from.Value);
                    OnBalanceChanging(engine, from, state_from, amount);
                }
            }
            else
            {
                if (storage_from is null)
                {
                    return(false);
                }
                TState state_from = new TState();
                state_from.FromByteArray(storage_from.Value);
                if (state_from.Balance < amount)
                {
                    return(false);
                }
                if (from.Equals(to))
                {
                    OnBalanceChanging(engine, from, state_from, BigInteger.Zero);
                }
                else
                {
                    OnBalanceChanging(engine, from, state_from, -amount);
                    if (state_from.Balance == amount)
                    {
                        engine.Snapshot.Storages.Delete(key_from);
                    }
                    else
                    {
                        state_from.Balance -= amount;
                        storage_from        = engine.Snapshot.Storages.GetAndChange(key_from);
                        storage_from.Value  = state_from.ToByteArray();
                    }
                    StorageKey  key_to     = CreateAccountKey(to);
                    StorageItem storage_to = engine.Snapshot.Storages.GetAndChange(key_to, () => new StorageItem
                    {
                        Value = new TState().ToByteArray()
                    });
                    TState state_to = new TState();
                    state_to.FromByteArray(storage_to.Value);
                    OnBalanceChanging(engine, to, state_to, amount);
                    state_to.Balance += amount;
                    storage_to.Value  = state_to.ToByteArray();
                }
            }
            engine.SendNotification(Hash, new StackItem[] { "Transfer", from.ToArray(), to.ToArray(), amount });
            return(true);
        }
Пример #58
0
 protected abstract void SaveEncryptedEntry(UInt160 scriptHash, byte[] redeemScript, byte[] encryptedPrivateKey);
Пример #59
0
 public override WalletEntry FindEntry(UInt160 scriptHash)
 {
     if (!accounts.Contains(scriptHash)) return null;
     return accounts[scriptHash];
 }
Пример #60
0
 protected virtual void OnBalanceChanging(ApplicationEngine engine, UInt160 account, TState state, BigInteger amount)
 {
 }