public async Task <ByteString> Init(IContractContext context)
        {
            var cars = new List <Car>
            {
                new Car("Toyota", "Prius", "blue", "Tomoko"),
                new Car("Ford", "Mustang", "red", "Brad"),
                new Car("Hyundai", "Tucson", "green", "Jin Soo"),
                new Car("Volkswagen", "Passat", "yellow", "Max"),
                new Car("Tesla", "S", "black", "Michael"),
                new Car("Peugeot", "205", "purpe", "Michel"),
                new Car("Chery", "522L", "white", "Aarav"),
                new Car("Fiat", "Punto", "violet", "Pari"),
                new Car("Tata", "Nano", "indigo", "Valeria"),
                new Car("Holden", "Barina", "brown", "Shotaro")
            };

            for (var index = 0; index < cars.Count; index++)
            {
                var car = cars[index];
                if (await context.Stub.PutStateJson($"CAR{index}", car))
                {
                    _logger.LogInformation("Added car", car.ToString());
                }
                else
                {
                    _logger.LogError($"Error writing car {car} onto the ledger");
                }
            }

            return(ByteString.Empty);
        }
        public async Task <ByteString> CreateCar(IContractContext context, string carNumber, string make, string model, string color, string owner)
        {
            var car = new Car(make, model, color, owner);

            await context.Stub.PutState(carNumber, JsonConvert.SerializeObject(car));

            return(ByteString.Empty);
        }
        public async Task <ByteString> ChangeCarOwner(IContractContext context, string carNumber, string owner)
        {
            var car = await context.Stub.GetStateJson <Car>(carNumber);

            car.Owner = owner;

            await context.Stub.PutStateJson(carNumber, car);

            return(ByteString.Empty);
        }
        public async Task <ByteString> Query(IContractContext context, string account)
        {
            var accountValueBytes = await context.Stub.GetState(account);

            if (accountValueBytes == null)
            {
                throw new Exception($"Failed to get state of asset holder {account}");
            }

            _logger.LogInformation($"Query Response: name={account}, value={accountValueBytes.ToStringUtf8()}");
            return(accountValueBytes);
        }
        public async Task <ByteString> QueryCar(IContractContext context, string carNumber)
        {
            var carBytes = await context.Stub.GetState(carNumber);

            if (carBytes == null || carBytes.Length <= 0)
            {
                throw new Exception($"Car {carNumber} does not exist.");
            }

            _logger.LogInformation(carBytes.ToStringUtf8());

            return(carBytes);
        }
        public async Task <ByteString> QueryAllCars(IContractContext context)
        {
            var startKey = "CAR0";
            var endKey   = "CAR999";

            var iterator = await context.Stub.GetStateByRange(startKey, endKey);

            var result = new List <CarQueryResult>();

            while (true)
            {
                var iterationResult = await iterator.Next();

                if (iterationResult.Value != null && iterationResult.Value.Value.Length > 0)
                {
                    var queryResult = new CarQueryResult
                    {
                        Key = iterationResult.Value.Key
                    };

                    try
                    {
                        queryResult.Record =
                            JsonConvert.DeserializeObject <Car>(iterationResult.Value.Value.ToStringUtf8());
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex,
                                         $"An error occured while trying to deserialize {iterationResult.Value.Value.ToStringUtf8()}");
                    }

                    result.Add(queryResult);
                }

                if (iterationResult.Done)
                {
                    _logger.LogInformation("End of data");
                    await iterator.Close();

                    _logger.LogInformation("Result", result);
                    return(JsonConvert.SerializeObject(result).ToByteString());
                }
            }
        }
        public async Task <ByteString> Transfer(
            IContractContext context,
            string firstAccount,
            string secondAccount,
            string amountString
            )
        {
            if (string.IsNullOrEmpty(firstAccount) || string.IsNullOrEmpty(secondAccount))
            {
                throw new Exception("Asset holding must not be empty");
            }

            var aValue = await context.Stub.TryGetState <int>(firstAccount);

            if (!aValue.HasValue)
            {
                throw new Exception("Failed to get state of asset holder A");
            }

            var bValue = await context.Stub.TryGetState <int>(secondAccount);

            if (!bValue.HasValue)
            {
                throw new Exception("Failed to get state of asset holder B");
            }

            if (!int.TryParse(amountString, out var amount))
            {
                throw new Exception("Expecting integer value for amount to be transferred");
            }

            aValue -= amount;
            bValue += amount;

            _logger.LogInformation($"aValue = {aValue}, bValue = {bValue}");

            await context.Stub.PutState(firstAccount, aValue);

            await context.Stub.PutState(secondAccount, bValue);

            return(ByteString.Empty);
        }
        public async Task <ByteString> Init(
            IContractContext context,
            string firstAccount,
            string firstAccountValue,
            string secondAccount,
            string secondAccountValue
            )
        {
            _logger.LogInformation("=================== Example Init ===================");

            if (!int.TryParse(firstAccountValue, out var aValue) ||
                !int.TryParse(secondAccountValue, out var bValue))
            {
                throw new Exception("Expecting integer value for asset holding");
            }

            await context.Stub.PutState(firstAccount, aValue);

            await context.Stub.PutState(secondAccount, bValue);

            return(ByteString.Empty);
        }
 /// <summary>
 /// Возвращает условие безопасной выборки данных указанного типа
 /// </summary>
 /// <param name="type">Тип данных, для которых возвращается условие выборки</param>
 /// <param name="context">Контекст безопасности, в котором определяется условие</param>
 /// <returns>Условие, ограничивающее выборку данных типа <b>type</b></returns>
 public abstract IList<string> GetObjectCriteria(Type type, IContractContext context);
 /// <summary>
 /// Возвращает новую типизированную систему безопасности операций с данными с указанным контекстом безопасности
 /// </summary>
 /// <param name="context">Контекст безопасности</param>
 public abstract ISelectDataSecurity CreateContractSecurity(IContractContext context);
 /// <summary>
 /// Возвращает флаг разрешения на операцию со свойством или полем объекта
 /// </summary>
 /// <param name="contractObject">Объект данных, над которым должна быть выполнена операция</param>
 /// <param name="operation">Операция, разрешение на которую запрашивается</param>
 /// <param name="memberName">Свойство или поле объекта, над которым должна быть выполнена операция</param>
 /// <param name="context">Контекст безопасности операций с данными</param>
 /// <returns>True - если операция над объектом разрешена, иначе false</returns>
 /// <remarks>Базовые операции над объектом описаны в классе <see cref="T:SecurityOperations"/></remarks>
 public abstract bool IsGranted(IContractObject contractObject, string operation, string memberName, IContractContext context);