Example #1
0
        public async Task ClientStream_HttpClientWithTimeout_Success()
        {
            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.EventId.Name == "ErrorStartingCall" &&
                    writeContext.Exception is TaskCanceledException)
                {
                    return(true);
                }

                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.EventId.Name == "GrpcStatusError" &&
                    writeContext.Message == "Call failed with gRPC error status. Status code: 'Cancelled', Message: 'Error starting gRPC call.'.")
                {
                    return(true);
                }

                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.EventId.Name == "WriteMessageError" &&
                    writeContext.Exception is InvalidOperationException &&
                    writeContext.Exception.Message == "Can't write the message because the call is complete.")
                {
                    return(true);
                }

                if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName)
                {
                    return(true);
                }

                return(false);
            });

            // Arrange
            var data = new byte[1024 * 64]; // 64 KB

            var httpClient = Fixture.CreateClient();

            httpClient.Timeout = TimeSpan.FromSeconds(0.5);

            var channel = GrpcChannel.ForAddress(httpClient.BaseAddress, new GrpcChannelOptions
            {
                HttpClient    = httpClient,
                LoggerFactory = LoggerFactory
            });

            var client      = new StreamService.StreamServiceClient(channel);
            var dataMessage = new DataMessage
            {
                Data = ByteString.CopyFrom(data)
            };

            // Act
            var call = client.ClientStreamedData();

            var ex = await ExceptionAssert.ThrowsAsync <RpcException>(async() =>
            {
                while (true)
                {
                    await call.RequestStream.WriteAsync(dataMessage).DefaultTimeout();

                    await Task.Delay(100);
                }
            }).DefaultTimeout();

            // Assert
            Assert.AreEqual(StatusCode.Cancelled, ex.StatusCode);
            Assert.AreEqual(StatusCode.Cancelled, call.GetStatus().StatusCode);
        }
 public static Flow <Google.Protobuf.ByteString, ByteString, NotUsed> FromProtobuf()
 {
     // TODO: avoid copying
     return(Flow.Create <Google.Protobuf.ByteString>()
            .Select(x => ByteString.CopyFrom(x.ToByteArray())));
 }
Example #3
0
        /// <summary>
        ///     Generates the encrypted signature which is required for the <see cref="RequestEnvelope"/>.
        /// </summary>
        /// <param name="requests">The requests of the <see cref="RequestEnvelope"/>.</param>
        /// <returns>The encrypted <see cref="Unknown6"/> (Signature).</returns>
        internal Unknown6 GenerateSignature(RequestEnvelope requestEnvelope)
        {
            var signature = new Signature
            {
                TimestampSinceStart = (ulong)_internalStopwatch.ElapsedMilliseconds,
                Timestamp           = (ulong)TimeUtil.GetCurrentTimestampInMilliseconds(),
                SensorInfo          = new SensorInfo()
                {
                    AccelNormalizedZ  = Randomize(9.8),
                    AccelNormalizedX  = Randomize(0.02),
                    AccelNormalizedY  = Randomize(0.3),
                    TimestampSnapshot = (ulong)_internalStopwatch.ElapsedMilliseconds - 230,
                    MagnetometerX     = Randomize(012271042913198471),
                    MagnetometerY     = Randomize(-0.015570580959320068),
                    MagnetometerZ     = Randomize(0.010850906372070313),
                    AngleNormalizedX  = Randomize(17.950439453125),
                    AngleNormalizedY  = Randomize(-23.36273193359375),
                    AngleNormalizedZ  = Randomize(-48.8250732421875),
                    AccelRawX         = Randomize(-0.0120010357350111),
                    AccelRawY         = Randomize(-0.04214850440621376),
                    AccelRawZ         = Randomize(0.94571763277053833),
                    GyroscopeRawX     = Randomize(7.62939453125e-005),
                    GyroscopeRawY     = Randomize(-0.00054931640625),
                    GyroscopeRawZ     = Randomize(0.0024566650390625),
                    AccelerometerAxes = 3
                },
                DeviceInfo = new DeviceInfo()
                {
                    DeviceId              = _session.Device.DeviceId,
                    AndroidBoardName      = _session.Device.AndroidBoardName,
                    AndroidBootloader     = _session.Device.AndroidBootloader,
                    DeviceBrand           = _session.Device.DeviceBrand,
                    DeviceModel           = _session.Device.DeviceModel,
                    DeviceModelIdentifier = _session.Device.DeviceModelIdentifier,
                    DeviceModelBoot       = _session.Device.DeviceModelBoot,
                    HardwareManufacturer  = _session.Device.HardwareManufacturer,
                    HardwareModel         = _session.Device.HardwareModel,
                    FirmwareBrand         = _session.Device.FirmwareBrand,
                    FirmwareTags          = _session.Device.FirmwareTags,
                    FirmwareType          = _session.Device.FirmwareType,
                    FirmwareFingerprint   = _session.Device.FirmwareFingerprint
                },
                LocationFix =
                {
                    new LocationFix
                    {
                        Provider = "network",
                        //Unk4 = 120,
                        Latitude            = (float)_session.Player.Coordinate.Latitude,
                        Longitude           = (float)_session.Player.Coordinate.Longitude,
                        Altitude            = (float)_session.Player.Coordinate.Altitude,
                        TimestampSinceStart = (ulong)_internalStopwatch.ElapsedMilliseconds - 200,
                        Floor        = 3,
                        LocationType = 1
                    }
                }
            };

            // Compute 10
            var serializedTicket = requestEnvelope.AuthTicket != null?requestEnvelope.AuthTicket.ToByteArray() : requestEnvelope.AuthInfo.ToByteArray();

            var firstHash     = CalculateHash32(serializedTicket, 0x1B845238);
            var locationBytes = BitConverter.GetBytes(_session.Player.Coordinate.Latitude).Reverse()
                                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Longitude).Reverse())
                                .Concat(BitConverter.GetBytes(_session.Player.Coordinate.Altitude).Reverse()).ToArray();

            signature.LocationHash1 = CalculateHash32(locationBytes, firstHash);
            // Compute 20
            signature.LocationHash2 = CalculateHash32(locationBytes, 0x1B845238);
            // Compute 24
            var seed = xxHash64.CalculateHash(serializedTicket, serializedTicket.Length, 0x1B845238);

            foreach (var req in requestEnvelope.Requests)
            {
                var reqBytes = req.ToByteArray();
                signature.RequestHash.Add(xxHash64.CalculateHash(reqBytes, reqBytes.Length, seed));
            }

            //static for now
            signature.Unknown22 = ByteString.CopyFrom(0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F);

            var iv = new byte[32];

            _random.NextBytes(iv);

            var encryptedSignature = new Unknown6
            {
                RequestType = 6,
                Unknown2    = new Unknown6.Types.Unknown2
                {
                    EncryptedSignature = ByteString.CopyFrom(CryptUtil.Encrypt(signature.ToByteArray(), iv))
                }
            };

            return(encryptedSignature);
        }
Example #4
0
 private static IEnumerable <ByteString> StringToByteString(IEnumerable <ReadOnlyMemory <char> > str)
 => str.Select(s => ByteString.CopyFrom(Encoding.UTF8.GetBytes(s.ToString())));
Example #5
0
 private static ByteString StringToByteString(string str) => ByteString.CopyFrom(Encoding.UTF8.GetBytes(str));
 private static Payload CreateZerosPayload(int size)
 {
     return(new Payload {
         Body = ByteString.CopyFrom(new byte[size])
     });
 }
        public static async Task ExecuteDeviceApprove(IAuthentication auth, IList <string> messages)
        {
            var keysRq = new EnterpriseDataCommand
            {
                include = new[] { "devices_request_for_admin_approval" }
            };
            var rs = await auth.ExecuteAuthCommand <EnterpriseDataCommand, EnterpriseDataResponse>(keysRq);

            if ((rs.DeviceRequestForApproval?.Count ?? 0) == 0)
            {
                return;
            }

            var userDataKeys = new Dictionary <long, byte[]>();

            foreach (var drq in rs.DeviceRequestForApproval)
            {
                if (!userDataKeys.ContainsKey(drq.EnterpriseUserId))
                {
                    userDataKeys[drq.EnterpriseUserId] = null;
                }
            }

            var dataKeyRq = new UserDataKeyRequest();

            dataKeyRq.EnterpriseUserId.AddRange(userDataKeys.Keys);
            var dataKeyRs = await auth.ExecuteAuthRest <UserDataKeyRequest, EnterpriseUserDataKeys>("enterprise/get_enterprise_user_data_key", dataKeyRq);

            foreach (var key in dataKeyRs.Keys)
            {
                if (key.UserEncryptedDataKey.IsEmpty)
                {
                    continue;
                }
                if (key.KeyTypeId != 2)
                {
                    continue;
                }
                try
                {
                    var userDataKey = CryptoUtils.DecryptEc(key.UserEncryptedDataKey.ToByteArray(), _enterprisePrivateKey);
                    userDataKeys[key.EnterpriseUserId] = userDataKey;
                }
                catch (Exception e)
                {
                    messages.Add($"Data key decrypt error: {e.Message}");
                }
            }

            var approveDevicesRq = new ApproveUserDevicesRequest();

            foreach (var drq in rs.DeviceRequestForApproval)
            {
                if (!userDataKeys.ContainsKey(drq.EnterpriseUserId) || userDataKeys[drq.EnterpriseUserId] == null)
                {
                    continue;
                }

                var dataKey         = userDataKeys[drq.EnterpriseUserId];
                var devicePublicKey = CryptoUtils.LoadPublicEcKey(drq.DevicePublicKey.Base64UrlDecode());
                var encDataKey      = CryptoUtils.EncryptEc(dataKey, devicePublicKey);
                var approveRq       = new ApproveUserDeviceRequest
                {
                    EnterpriseUserId       = drq.EnterpriseUserId,
                    EncryptedDeviceToken   = ByteString.CopyFrom(drq.EncryptedDeviceToken.Base64UrlDecode()),
                    EncryptedDeviceDataKey = ByteString.CopyFrom(encDataKey),
                    DenyApproval           = false,
                };
                approveDevicesRq.DeviceRequests.Add(approveRq);
            }

            if (approveDevicesRq.DeviceRequests.Count == 0)
            {
                return;
            }

            var approveRs = await auth.ExecuteAuthRest <ApproveUserDevicesRequest, ApproveUserDevicesResponse>("enterprise/approve_user_devices", approveDevicesRq);

            foreach (var deviceRs in approveRs.DeviceResponses)
            {
                var message = $"Approve device for {deviceRs.EnterpriseUserId} {(deviceRs.Failed ? "failed" : "succeeded")}";
                Debug.WriteLine(message);
                messages.Add(message);
            }
        }
Example #8
0
 public void SetAccountStateRoot(byte[] root)
 {
     this.block.BlockHeader.RawData.AccountStateRoot = ByteString.CopyFrom(root);
 }
Example #9
0
 public void SetWitness(string witness)
 {
     this.block.BlockHeader.RawData.WitnessAddress = ByteString.CopyFrom(witness.ToBytes());
 }
Example #10
0
        public RequestEnvelope SetRequestEnvelopeUnknown6(RequestEnvelope requestEnvelope)
        {
            if (_sessionHash == null)
            {
                _sessionHash = new byte[32];
                _random.NextBytes(_sessionHash);
            }

            byte[] authSeed = requestEnvelope.AuthTicket != null?
                              requestEnvelope.AuthTicket.ToByteArray() :
                                  requestEnvelope.AuthInfo.ToByteArray();


            var normAccel = new Vector(_deviceInfo.Sensors.AccelRawX, _deviceInfo.Sensors.AccelRawY, _deviceInfo.Sensors.AccelRawZ);

            normAccel.NormalizeVector(1.0f);//1.0f on iOS, 9.81 on Android?

            var sig = new Signature
            {
                LocationHash1 =
                    Utils.GenerateLocation1(authSeed, requestEnvelope.Latitude, requestEnvelope.Longitude,
                                            requestEnvelope.Accuracy),
                LocationHash2 =
                    Utils.GenerateLocation2(requestEnvelope.Latitude, requestEnvelope.Longitude,
                                            requestEnvelope.Accuracy),
                SessionHash         = ByteString.CopyFrom(_sessionHash),
                Unknown25           = 7363665268261373700L,
                Timestamp           = (ulong)DateTime.UtcNow.ToUnixTime(),
                TimestampSinceStart = (ulong)_deviceInfo.TimeSnapshot,
                SensorInfo          = new Signature.Types.SensorInfo
                {
                    AccelNormalizedX  = normAccel.X,
                    AccelNormalizedY  = normAccel.Y,
                    AccelNormalizedZ  = normAccel.Z,
                    AccelRawX         = -_deviceInfo.Sensors.AccelRawX,
                    AccelRawY         = -_deviceInfo.Sensors.AccelRawY,
                    AccelRawZ         = -_deviceInfo.Sensors.AccelRawZ,
                    MagnetometerX     = _deviceInfo.Sensors.MagnetometerX,
                    MagnetometerY     = _deviceInfo.Sensors.MagnetometerY,
                    MagnetometerZ     = _deviceInfo.Sensors.MagnetometerZ,
                    GyroscopeRawX     = _deviceInfo.Sensors.GyroscopeRawX,
                    GyroscopeRawY     = _deviceInfo.Sensors.GyroscopeRawY,
                    GyroscopeRawZ     = _deviceInfo.Sensors.GyroscopeRawZ,
                    AngleNormalizedX  = _deviceInfo.Sensors.AngleNormalizedX,
                    AngleNormalizedY  = _deviceInfo.Sensors.AngleNormalizedY,
                    AngleNormalizedZ  = _deviceInfo.Sensors.AngleNormalizedZ,
                    AccelerometerAxes = _deviceInfo.Sensors.AccelerometerAxes,
                    TimestampSnapshot = (ulong)(_deviceInfo.Sensors.TimeSnapshot - _random.Next(150, 260))
                },
                DeviceInfo = new Signature.Types.DeviceInfo
                {
                    DeviceId              = _deviceInfo.DeviceID,
                    AndroidBoardName      = _deviceInfo.AndroidBoardName,
                    AndroidBootloader     = _deviceInfo.AndroidBootloader,
                    DeviceBrand           = _deviceInfo.DeviceBrand,
                    DeviceModel           = _deviceInfo.DeviceModel,
                    DeviceModelBoot       = _deviceInfo.DeviceModelBoot,
                    DeviceModelIdentifier = _deviceInfo.DeviceModelIdentifier,
                    FirmwareFingerprint   = _deviceInfo.FirmwareFingerprint,
                    FirmwareTags          = _deviceInfo.FirmwareTags,
                    HardwareManufacturer  = _deviceInfo.HardwareManufacturer,
                    HardwareModel         = _deviceInfo.HardwareModel,
                    FirmwareBrand         = _deviceInfo.FirmwareBrand,
                    FirmwareType          = _deviceInfo.FirmwareType
                },

                ActivityStatus = _deviceInfo.ActivityStatus != null ? new Signature.Types.ActivityStatus()
                {
                    Walking    = _deviceInfo.ActivityStatus.Walking,
                    Automotive = _deviceInfo.ActivityStatus.Automotive,
                    Cycling    = _deviceInfo.ActivityStatus.Cycling,
                    Running    = _deviceInfo.ActivityStatus.Running,
                    Stationary = _deviceInfo.ActivityStatus.Stationary,
                    Tilting    = _deviceInfo.ActivityStatus.Tilting,
                }
                : null
            };


            if (_deviceInfo.GpsSattelitesInfo.Length > 0)
            {
                sig.GpsInfo = new Signature.Types.AndroidGpsInfo();
                //sig.GpsInfo.TimeToFix //currently not filled

                _deviceInfo.GpsSattelitesInfo.ToList().ForEach(sat =>
                {
                    sig.GpsInfo.Azimuth.Add(sat.Azimuth);
                    sig.GpsInfo.Elevation.Add(sat.Elevation);
                    sig.GpsInfo.HasAlmanac.Add(sat.Almanac);
                    sig.GpsInfo.HasEphemeris.Add(sat.Emphasis);
                    sig.GpsInfo.SatellitesPrn.Add(sat.SattelitesPrn);
                    sig.GpsInfo.Snr.Add(sat.Snr);
                    sig.GpsInfo.UsedInFix.Add(sat.UsedInFix);
                });
            }

            _deviceInfo.LocationFixes.ToList().ForEach(loc => sig.LocationFix.Add(new Signature.Types.LocationFix
            {
                Floor              = loc.Floor,
                Longitude          = loc.Longitude,
                Latitude           = loc.Latitude,
                Altitude           = loc.Altitude,
                LocationType       = loc.LocationType,
                Provider           = loc.Provider,
                ProviderStatus     = loc.ProviderStatus,
                HorizontalAccuracy = loc.HorizontalAccuracy,
                VerticalAccuracy   = loc.VerticalAccuracy,
                Course             = loc.Course,
                Speed              = loc.Speed,
                TimestampSnapshot  = loc.TimeSnapshot
            }));

            foreach (var request in requestEnvelope.Requests)
            {
                sig.RequestHash.Add(
                    Utils.GenerateRequestHash(authSeed, request.ToByteArray())
                    );
            }

            requestEnvelope.Unknown6 = new Unknown6
            {
                RequestType = 6,
                Unknown2    = new Unknown6.Types.Unknown2
                {
                    EncryptedSignature = ByteString.CopyFrom(Crypt.Encrypt(sig.ToByteArray()))
                }
            };

            return(requestEnvelope);
        }
Example #11
0
 public void SetMerkleTree()
 {
     this.block.BlockHeader.RawData.TxTrieRoot = ByteString.CopyFrom(CalcMerkleRoot().Hash);
 }
Example #12
0
        public static Hero NewInstance()
        {
            return(new Hero
            {
                Id = ByteString.CopyFrom(Id.ToByteArray()),
                Name = "Sara",
                Races = { Race.Human },
                Gender = Gender.Female,
                MaxAttack = 7600,
                MaxHp = 1840,
                MaxLevel = 80,
                BaseDoubleAttackRate = 6,
                BaseTripleAttackRate = 4.5,
                Element = Element.Light,
                WeaponProficiencies = { EquipmentType.Melee },
                AvailablePerkIds =
                {
                    ExtendedMasteryPerks.AttackBoost,
                    ExtendedMasteryPerks.DefenseBoost,
                    ExtendedMasteryPerks.DefenseBoost,
                    ExtendedMasteryPerks.HpBoost,
                    ExtendedMasteryPerks.DarkDamageReduction,
                    ExtendedMasteryPerks.AttackBoost,
                    ExtendedMasteryPerks.DefenseBoost,
                    ExtendedMasteryPerks.HpBoost,
                    ExtendedMasteryPerks.DoubleAttackRateBoost,
                    ExtendedMasteryPerks.CriticalHitRateBoost,
                    ExtendedMasteryPerks.HpBoost,
                    ExtendedMasteryPerks.SkillDamageCapBoost,
                    ExtendedMasteryPerks.DarkDamageReduction,
                    ExtendedMasteryPerks.HostilityBoost,
                    ExtendedMasteryPerks.SupportSkill,
                },
                PassiveAbilities =
                {
                    new PassiveAbility
                    {
                        Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill,
                        Name = "Passive ability 1",
                        Description = "Passive ability 1 description",
                    },
                    new PassiveAbility
                    {
                        Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill,
                        Name = "Passive ability 2",
                        Description = "Passive ability 2 description",
                    },
                },
                UpgradedPassiveAbilities =
                {
                    new PassiveAbilityUpgrade
                    {
                        Ability = new PassiveAbility
                        {
                            Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill,
                            Name = "Upgraded passive ability 2",
                            Description = "Upgraded passive ability 2 description",
                        },
                        RequiredLevel = 85,
                        RequiredRank = 5,
                        UpgradedPassiveAbilityIndex = 2,
                    },
                    new PassiveAbilityUpgrade
                    {
                        Ability = new PassiveAbility
                        {
                            Type = PassiveAbility.Types.PassiveAbilityType.SupportSkill,
                            Name = "Passive ability 3",
                            Description = "Passive ability 3 description",
                        },
                        RequiredLevel = 95,
                        RequiredRank = 5,
                        UpgradedPassiveAbilityIndex = 3,
                    },
                },
                ModelMetadata =
                {
                    new ModelMetadata
                    {
                        JsAssetPath = "npc/48b77e14-05d4-497f-ad1f-6673296cf486/model/0/npc_3040236000_02.js",
                        ConstructorName = "mc_npc_3040236000_02",
                        ImageAssets =
                        {
                            new ImageAsset
                            {
                                Name = "npc_3040236000_02",
                                Path = "npc/48b77e14-05d4-497f-ad1f-6673296cf486/model/0/npc_3040236000_02.png",
                            },
                        },
                    },
                },
                OnHitEffectModelMetadata =
                {
                    new ModelMetadata
                    {
                        JsAssetPath = "npc/48b77e14-05d4-497f-ad1f-6673296cf486/model/0/phit_3040236000.js",
                        ConstructorName = "mc_phit_3040236000_effect",
                        ImageAssets =
                        {
                            new ImageAsset
                            {
                                Name = "phit_3040236000",
                                Path = "npc/48b77e14-05d4-497f-ad1f-6673296cf486/model/0/phit_3040236000.png",
                            },
                        },
                    },
                },
                SpecialAbility = new SpecialAbility
                {
                    Name = string.Empty,
                    HitCount = { 13 },

                    ModelMetadata =
                    {
                        new ModelMetadata
                        {
                            JsAssetPath = "npc/48b77e14-05d4-497f-ad1f-6673296cf486/model/0/nsp_3040236000_02_s2.js",
                            ConstructorName = "mc_nsp_3040236000_02_s2_special",
                            ImageAssets =
                            {
                                new ImageAsset
                                {
                                    Name = "nsp_3040236000_02_s2",
                                    Path = "npc/48b77e14-05d4-497f-ad1f-6673296cf486/model/0/nsp_3040236000_02_s2.png",
                                },
                            },
                        },
                    },
                    Effects =
                    {
                    },
                    ProcessEffects = (sara, raidActions) =>
                    {
                        if (sara.GetDebuffs().All(e => e.IsUsedInternally))
                        {
                            sara.Hero.GetAbilities()[1].Cast(sara, raidActions);
                        }
                        else
                        {
                            sara.ApplyStatusEffect(new StatusEffectSnapshot
                            {
                                Id = StatusEffectLibrary.RemoveAllDebuffs,
                            });
                        }
                    },
                },
                Abilities =
                {
                    Affectio(cooldown: 7),
                    Tonitrua(cooldown: 7),
                    Afflatus(cooldown: 6),
                },
                UpgradedAbilities =
                {
                    new AbilityUpgrade
                    {
                        RequiredLevel = 55,
                        Ability = Affectio(cooldown: 6),
                        UpgradedAbilityIndex = 0,
                    },
                    new AbilityUpgrade
                    {
                        RequiredLevel = 75,
                        Ability = Tonitrua(cooldown: 6),
                        UpgradedAbilityIndex = 1,
                    },
                },
                OnActionStart = (sara, raidActions) => ProcessPassiveEffects(sara),
                OnTurnEnd = (sara, raidActions) =>
                {
                    foreach (var enemy in sara.Raid.Enemies)
                    {
                        if (enemy.NumSpecialAttacksUsedThisTurn >= 1)
                        {
                            sara.Hero.GetAbilities()[1].Cast(sara, raidActions);
                            break;
                        }
                    }
                },
                OnSetup = (sara, allies, loadout) =>
                {
                    sara.ApplyStatusEffect(
                        new StatusEffectSnapshot
                    {
                        Id = "passive",
                        Strength = -25,
                        Modifier = ModifierLibrary.ChargeBarSpedUp,
                        BaseAccuracy = double.MaxValue,
                        IsUsedInternally = true,
                        IsPassiveEffect = true,
                        TurnDuration = int.MaxValue,
                    });
                },
                OnEnteringFrontline = (sara, raidActions) => ProcessPassiveEffects(sara),
            });
        }
Example #13
0
 public static ECDSAPublicKey ToPublicKey(this byte[] buffer)
 {
     return(new ECDSAPublicKey {
         Buffer = ByteString.CopyFrom(Crypto.DecodePublicKey(buffer, true))
     });
 }
Example #14
0
 public void ClearCache()
 {
     CacheNotify.Publish(new AscCacheItem {
         Id = ByteString.CopyFrom(Guid.NewGuid().ToByteArray())
     }, CacheNotifyAction.Any);
 }
Example #15
0
        public void Execute()
        {
            var s          = CurrentTransactionContext.Trace.StartTime = TimestampHelper.GetUtcNow().ToDateTime();
            var methodName = CurrentTransactionContext.Transaction.MethodName;

            try
            {
                if (!_callHandlers.TryGetValue(methodName, out var handler))
                {
                    throw new RuntimeException(
                              $"Failed to find handler for {methodName}. We have {_callHandlers.Count} handlers: " +
                              string.Join(", ", _callHandlers.Keys.OrderBy(k => k))
                              );
                }

                try
                {
                    var tx     = CurrentTransactionContext.Transaction;
                    var retVal = handler.Execute(tx.Params.ToByteArray());
                    if (retVal != null)
                    {
                        CurrentTransactionContext.Trace.ReturnValue = ByteString.CopyFrom(retVal);
                        // TODO: Clean up ReadableReturnValue
                        CurrentTransactionContext.Trace.ReadableReturnValue = handler.ReturnBytesToString(retVal);
                    }

                    CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.Executed;
                }
                catch (TargetInvocationException ex)
                {
                    CurrentTransactionContext.Trace.Error          += ex;
                    CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.ContractError;
                }
                catch (AssertionException ex)
                {
                    CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.ContractError;
                    CurrentTransactionContext.Trace.Error          += "\n" + ex;
                }
                catch (Exception ex)
                {
                    // TODO: Simplify exception
                    CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.ContractError;
                    CurrentTransactionContext.Trace.Error          += "\n" + ex;
                }

                if (!handler.IsView())
                {
                    var changes = _smartContractProxy.GetChanges();

                    var address = _hostSmartContractBridgeContext.Self.ToStorageKey();
                    foreach (var(key, value) in changes.Writes)
                    {
                        if (!key.StartsWith(address))
                        {
                            throw new InvalidOperationException("a contract cannot access other contracts data");
                        }
                    }

                    foreach (var(key, value) in changes.Reads)
                    {
                        if (!key.StartsWith(address))
                        {
                            throw new InvalidOperationException("a contract cannot access other contracts data");
                        }
                    }

                    if (!CurrentTransactionContext.Trace.IsSuccessful())
                    {
                        changes.Writes.Clear();
                    }

                    CurrentTransactionContext.Trace.StateSet = changes;
                }
                else
                {
                    CurrentTransactionContext.Trace.StateSet = new TransactionExecutingStateSet();
                }
            }
            catch (Exception ex)
            {
                CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.SystemError;
                CurrentTransactionContext.Trace.Error          += ex + "\n";
            }
            finally
            {
                // TODO: Not needed
                Cleanup();
            }

            var e = CurrentTransactionContext.Trace.EndTime = TimestampHelper.GetUtcNow().ToDateTime();

            CurrentTransactionContext.Trace.Elapsed = (e - s).Ticks;
        }
Example #16
0
        /// <summary>
        /// Adds the media files.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>A map with key as image name, and value as image bytes.</returns>
        private Dictionary <string, string> AddMediaFiles(GoogleAdsClient client, long customerId)
        {
            // Get the MediaFileService.
            MediaFileServiceClient mediaFileService =
                client.GetService(Services.V4.MediaFileService);

            // Creates a bytes array from the logo image data.
            byte[] logoImageData = MediaUtilities.GetAssetDataFromUrl(
                "https://goo.gl/mtt54n", client.Config);

            // Creates the logo image.
            MediaFile mediaFileLogo = new MediaFile()
            {
                Type  = MediaType.Image,
                Image = new MediaImage()
                {
                    Data = ByteString.CopyFrom(logoImageData)
                },
                MimeType = MimeType.ImagePng
            };

            // Creates the operation for the logo image.
            MediaFileOperation mediaFileLogoOperation = new MediaFileOperation()
            {
                Create = mediaFileLogo
            };

            // Creates a bytes array from the marketing image data.
            byte[] marketingImageData = MediaUtilities.GetAssetDataFromUrl(
                "https://goo.gl/3b9Wfh", client.Config);

            // Creates the marketing image.
            MediaFile mediaFileMarketing = new MediaFile()
            {
                Type  = MediaType.Image,
                Image = new MediaImage()
                {
                    Data = ByteString.CopyFrom(marketingImageData)
                },
                MimeType = MimeType.ImageJpeg
            };

            // Creates the operation for the marketing image.
            MediaFileOperation mediaFileMarketingOperation = new MediaFileOperation()
            {
                Create = mediaFileMarketing
            };

            // Adds the media files.
            MutateMediaFilesResponse response =
                mediaFileService.MutateMediaFiles(customerId.ToString(),
                                                  new[] { mediaFileLogoOperation, mediaFileMarketingOperation });

            // Display the results.
            foreach (MutateMediaFileResult result in response.Results)
            {
                Console.WriteLine($"Created media file with resource name " +
                                  $"'{result.ResourceName}'.");
            }

            return(new Dictionary <string, string>()
            {
                { "logoResourceName", response.Results[0].ResourceName },
                { "marketingImageResourceName", response.Results[1].ResourceName },
            });
        }
Example #17
0
 private static ByteString ByteStringOfSize(int size)
 {
     return(ByteString.CopyFrom(new byte[size]));
 }
        private async Task <Block> FillBlockAfterExecutionAsync(BlockHeader blockHeader, List <Transaction> transactions,
                                                                ReturnSetCollection returnSetCollection)
        {
            Logger.LogTrace("Start block field filling after execution.");
            var bloom         = new Bloom();
            var blockStateSet = new BlockStateSet
            {
                BlockHeight  = blockHeader.Height,
                PreviousHash = blockHeader.PreviousBlockHash
            };

            foreach (var returnSet in returnSetCollection.Executed)
            {
                foreach (var change in returnSet.StateChanges)
                {
                    blockStateSet.Changes[change.Key] = change.Value;
                    blockStateSet.Deletes.Remove(change.Key);
                }

                foreach (var delete in returnSet.StateDeletes)
                {
                    blockStateSet.Deletes.AddIfNotContains(delete.Key);
                    blockStateSet.Changes.Remove(delete.Key);
                }

                if (returnSet.Status == TransactionResultStatus.Mined)
                {
                    bloom.Combine(new[] { new Bloom(returnSet.Bloom.ToByteArray()) });
                }
            }

            blockHeader.Bloom = ByteString.CopyFrom(bloom.Data);
            blockHeader.MerkleTreeRootOfWorldState = CalculateWorldStateMerkleTreeRoot(blockStateSet);

            var allExecutedTransactionIds = transactions.Select(x => x.GetHash()).ToList();
            var orderedReturnSets         = returnSetCollection.ToList().AsParallel()
                                            .OrderBy(d => allExecutedTransactionIds.IndexOf(d.TransactionId)).ToList();

            blockHeader.MerkleTreeRootOfTransactionStatus =
                CalculateTransactionStatusMerkleTreeRoot(orderedReturnSets);

            blockHeader.MerkleTreeRootOfTransactions = CalculateTransactionMerkleTreeRoot(allExecutedTransactionIds);

            var blockHash = blockHeader.GetHashWithoutCache();
            var blockBody = new BlockBody();

            blockBody.TransactionIds.AddRange(allExecutedTransactionIds);

            var block = new Block
            {
                Header = blockHeader,
                Body   = blockBody
            };

            blockStateSet.BlockHash = blockHash;
            Logger.LogTrace("Set block state set.");

            await _blockchainStateService.SetBlockStateSetAsync(blockStateSet);

            Logger.LogTrace("Finish block field filling after execution.");
            return(block);
        }
        private async Task CancelInParallel(int tasks, bool waitForHeaders, int interations)
        {
            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.LoggerName == TestConstants.ServerCallHandlerTestName)
                {
                    // Kestrel cancellation error message
                    if (writeContext.Exception is IOException &&
                        writeContext.Exception.Message == "The client reset the request stream.")
                    {
                        return(true);
                    }

                    // Cancellation when service is receiving message
                    if (writeContext.Exception is InvalidOperationException &&
                        writeContext.Exception.Message == "Can't read messages after the request is complete.")
                    {
                        return(true);
                    }

                    // Cancellation when service is writing message
                    if (writeContext.Exception is InvalidOperationException &&
                        writeContext.Exception.Message == "Can't write the message because the request is complete.")
                    {
                        return(true);
                    }

                    // Cancellation before service writes message
                    if (writeContext.Exception is TaskCanceledException &&
                        writeContext.Exception.Message == "A task was canceled.")
                    {
                        return(true);
                    }

                    // Request is canceled while writing message
                    if (writeContext.Exception is OperationCanceledException)
                    {
                        return(true);
                    }
                }

                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall")
                {
                    // Cancellation when call hasn't returned headers
                    if (writeContext.EventId.Name == "ErrorStartingCall" &&
                        writeContext.Exception is TaskCanceledException)
                    {
                        return(true);
                    }
                }

                return(false);
            });

            // Arrange
            var data = new byte[1024 * 64];

            var client = new StreamService.StreamServiceClient(Channel);

            await TestHelpers.RunParallel(tasks, async taskIndex =>
            {
                try
                {
                    for (var i = 0; i < interations; i++)
                    {
                        Logger.LogInformation($"Staring {taskIndex}-{i}");

                        var cts     = new CancellationTokenSource();
                        var headers = new Metadata();
                        if (waitForHeaders)
                        {
                            headers.Add("flush-headers", bool.TrueString);
                        }
                        using var call = client.EchoAllData(cancellationToken: cts.Token, headers: headers);

                        if (waitForHeaders)
                        {
                            await call.ResponseHeadersAsync.DefaultTimeout();
                        }

                        await call.RequestStream.WriteAsync(new DataMessage
                        {
                            Data = ByteString.CopyFrom(data)
                        }).DefaultTimeout();

                        cts.Cancel();
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Cancellation error");
                    throw;
                }
            });

            // Wait a short amount of time so that any server cancellation error
            // finishes being thrown before the next test starts.
            await Task.Delay(50);
        }
Example #20
0
 public static ByteString ToByteString(this ITinkarId id)
 {
     //# Tested
     return(ByteString.CopyFrom(id.Uuid.ToByteArray()));
 }
Example #21
0
 private static ByteString StringToByteString(ReadOnlyMemory <char> str) => ByteString.CopyFrom(Encoding.UTF8.GetBytes(str.ToString()));
Example #22
0
        static PBField ToPBField(this Object item)
        {
            PBField f = new PBField();

            switch (item)
            {
            case String value:
                f.StringValue = value;
                break;

            case Boolean value:
                f.BoolValue = value;
                break;

            case Int32 value:
                f.IntValue = value;
                break;

            case Single value:
                f.FloatValue = value;
                break;

            case Byte[] value:
                f.BytesValue = ByteString.CopyFrom(value);
                break;

            case ConceptDTO value:
                f.ConceptValue = value.ToPBConcept();
                break;

            case DateTime value:
                f.TimeValue = Timestamp.FromDateTime(value);
                break;

            case List <IPublicId> value:
            {
                PBPublicIdList l = new PBPublicIdList();
                l.PublicIds.AddRange(value.ToPBPublicIds());
                f.PublicIdListValue = l;
            }
            break;

            case HashSet <IPublicId> value:
            {
                PBPublicIdList l = new PBPublicIdList();
                l.PublicIds.AddRange(value.ToPBPublicIds());
                f.PublicIdListValue = l;
            }
            break;

            case DiTreeDTO value:
                f.DiTreeValue = value.ToPBDiTree();
                break;

            case DiGraphDTO value:
                f.DiGraphValue = value.ToPBDiGraph();
                break;

            case GraphDTO value:
                f.GraphValue = value.ToPBGraph();
                break;

            case VertexDTO value:
                f.VertexValue = value.ToPBVertex();
                break;

            default:
                throw new NotImplementedException();
            }
            return(f);
        }
Example #23
0
 private static IEnumerable <ByteString> StringToByteString(IEnumerable <string> str)
 => str.Select(s => ByteString.CopyFrom(Encoding.UTF8.GetBytes(s)));
Example #24
0
 public Cmp(ByteSequence key, Op compareOp, CmpTarget <T> target)
 {
     this.key    = ByteString.CopyFrom(key.GetBytes());
     this.op     = compareOp;
     this.target = target;
 }
Example #25
0
        void SendBatchedMessageHelper()
        {
            var message = new UnityOutputProto
            {
                RlOutput = m_CurrentUnityRlOutput,
            };
            var tempUnityRlInitializationOutput = GetTempUnityRlInitializationOutput();

            if (tempUnityRlInitializationOutput != null)
            {
                message.RlInitializationOutput = tempUnityRlInitializationOutput;
            }

            byte[] messageAggregated = SideChannelManager.GetSideChannelMessage();
            message.RlOutput.SideChannel = ByteString.CopyFrom(messageAggregated);

            var input = Exchange(message);

            UpdateSentActionSpec(tempUnityRlInitializationOutput);

            foreach (var k in m_CurrentUnityRlOutput.AgentInfos.Keys)
            {
                m_CurrentUnityRlOutput.AgentInfos[k].Value.Clear();
            }

            var rlInput = input?.RlInput;

            if (rlInput?.AgentActions == null)
            {
                return;
            }

            UpdateEnvironmentWithInput(rlInput);

            foreach (var brainName in rlInput.AgentActions.Keys)
            {
                if (!m_OrderedAgentsRequestingDecisions[brainName].Any())
                {
                    continue;
                }

                if (!rlInput.AgentActions[brainName].Value.Any())
                {
                    continue;
                }

                var agentActions = rlInput.AgentActions[brainName].ToAgentActionList();
                var numAgents    = m_OrderedAgentsRequestingDecisions[brainName].Count;
                for (var i = 0; i < numAgents; i++)
                {
                    var agentAction = agentActions[i];
                    var agentId     = m_OrderedAgentsRequestingDecisions[brainName][i];
                    if (m_LastActionsReceived[brainName].ContainsKey(agentId))
                    {
                        m_LastActionsReceived[brainName][agentId] = agentAction;
                    }
                }
            }
            foreach (var brainName in m_OrderedAgentsRequestingDecisions.Keys)
            {
                m_OrderedAgentsRequestingDecisions[brainName].Clear();
            }
        }
Example #26
0
        public static Hero NewInstance()
        {
            return(new Hero
            {
                Id = ByteString.CopyFrom(Id.ToByteArray()),
                Name = "Jessica",
                Races = { Race.Human },
                Gender = Gender.Female,
                MaxAttack = 5900,
                MaxHp = 1860,
                MaxLevel = 80,
                BaseDoubleAttackRate = 6,
                BaseTripleAttackRate = 4.5,
                Element = Element.Earth,
                WeaponProficiencies = { EquipmentType.Gun },
                AvailablePerkIds =
                {
                    ExtendedMasteryPerks.AttackBoost,
                    ExtendedMasteryPerks.DefenseBoost,
                    ExtendedMasteryPerks.HpBoost,
                    ExtendedMasteryPerks.DoubleAttackRateBoost,
                    ExtendedMasteryPerks.DebuffResistanceBoost,
                    ExtendedMasteryPerks.AttackBoost,
                    ExtendedMasteryPerks.DefenseBoost,
                    ExtendedMasteryPerks.HpBoost,
                    ExtendedMasteryPerks.DoubleAttackRateBoost,
                    ExtendedMasteryPerks.CriticalHitRateBoost,
                    ExtendedMasteryPerks.AttackBoost,
                    ExtendedMasteryPerks.CriticalHitRateBoost,
                    ExtendedMasteryPerks.CriticalHitRateBoost,
                    ExtendedMasteryPerks.DebuffSuccessRateBoost,
                    ExtendedMasteryPerks.SupportSkill,
                },
                PassiveAbilities =
                {
                    new PassiveAbility
                    {
                        Name = "Unforgettable Summer",
                        Description =
                            "When an ally is below 25% HP: Deal guaranteed triple attacks and 50% boost to healing specs.",
                    },
                    new PassiveAbility
                    {
                        Name = "Vacation Gear",
                        Description =
                            "Upon using charge attack: Extend Status Godsend Trigger's duration by 2 turns. Raise Status Fire Support lvl by 1.",
                    },
                },
                ModelMetadata =
                {
                    new ModelMetadata
                    {
                        JsAssetPath = "npc/5f1f772e-6f69-497f-bd5c-a1a7a575fbad/model/0/npc_3040227000_02.js",
                        ConstructorName = "mc_npc_3040227000_02",
                        ImageAssets =
                        {
                            new ImageAsset
                            {
                                Name = "npc_3040227000_02",
                                Path = "npc/5f1f772e-6f69-497f-bd5c-a1a7a575fbad/model/0/npc_3040227000_02.png",
                            },
                        },
                    },
                },
                OnHitEffectModelMetadata =
                {
                    new ModelMetadata
                    {
                        JsAssetPath = "npc/5f1f772e-6f69-497f-bd5c-a1a7a575fbad/model/0/phit_3040227000.js",
                        ConstructorName = "mc_phit_3040227000_effect",
                        ImageAssets =
                        {
                            new ImageAsset
                            {
                                Name = "phit_3040227000",
                                Path = "npc/5f1f772e-6f69-497f-bd5c-a1a7a575fbad/model/0/phit_3040227000.png",
                            },
                        },
                    },
                },
                SpecialAbility = new SpecialAbility
                {
                    Name = string.Empty,
                    HitCount = { 1 },
                    ModelMetadata =
                    {
                        new ModelMetadata
                        {
                            JsAssetPath = "npc/5f1f772e-6f69-497f-bd5c-a1a7a575fbad/model/0/nsp_3040227000_02_s2.js",
                            ConstructorName = "mc_nsp_3040227000_02_s2_special",
                            ImageAssets =
                            {
                                new ImageAsset
                                {
                                    Name = "nsp_3040227000_02_s2_a",
                                    Path = "npc/5f1f772e-6f69-497f-bd5c-a1a7a575fbad/model/0/nsp_3040227000_02_s2_a.png",
                                },
                                new ImageAsset
                                {
                                    Name = "nsp_3040227000_02_s2_b",
                                    Path = "npc/5f1f772e-6f69-497f-bd5c-a1a7a575fbad/model/0/nsp_3040227000_02_s2_b.png",
                                },
                            },
                        },
                    },
                    Effects =
                    {
                        new AbilityEffect
                        {
                            Type = AbilityEffect.Types.AbilityEffectType.ApplyStatusEffect,
                            ExtraData = new ApplyStatusEffect
                            {
                                Id = StatusEffectLibrary.Blind,
                                Strength = 25,
                                BaseAccuracy = 90,
                                DurationInSeconds = 180,
                            }.ToByteString(),
                        },
                        new AbilityEffect
                        {
                            Type = AbilityEffect.Types.AbilityEffectType.ApplyStatusEffect,
                            ExtraData = new ApplyStatusEffect
                            {
                                Id = StatusEffectLibrary.RemoveDebuff,
                                EffectTargettingType = EffectTargettingType.OnAllPartyMembers,
                            }.ToByteString(),
                        },
                    },
                    ProcessEffects = (jessica, raidActions) =>
                    {
                        var godsendTrigger = jessica.GetStatusEffect(GodsendTriggerId);
                        if (godsendTrigger != null)
                        {
                            godsendTrigger.TurnDuration += 2;
                        }

                        jessica.ApplyOrOverrideStatusEffectStacks(FireSupportId, initialStackCount: 1, increment: 1, maxStackCount: 2, raidActions: raidActions, isUndispellable: true);
                    },
                },
                Abilities =
                {
                    Pflegeschuss(cooldown: 8),
                    Feuerwerk(cooldown: 7),
                    Aussenseiter(cooldown: 7),
                },
                UpgradedAbilities =
                {
                    new AbilityUpgrade
                    {
                        RequiredLevel = 55,
                        Ability = Pflegeschuss(cooldown: 7),
                        UpgradedAbilityIndex = 0,
                    },
                    new AbilityUpgrade
                    {
                        RequiredLevel = 75,
                        Ability = Feuerwerk(cooldown: 6),
                        UpgradedAbilityIndex = 1,
                    },
                },
                OnTurnEnd = (jessica, raidActions) =>
                {
                    if (jessica.GetStatusEffect(GodsendTriggerId) != null)
                    {
                        TryProcessUnforgettableSummerHealingBoost(jessica);
                        GodsendTrigger().Cast(jessica, raidActions);
                    }
                },
                OnAttackStart = (jessica, isAboutToPerformSpecialAttack, raidActions) =>
                {
                    if (isAboutToPerformSpecialAttack && jessica.Raid.Allies.Any(e => e.HpPercentage < 25))
                    {
                        jessica.ApplyStatusEffect(
                            new StatusEffectSnapshot
                        {
                            Id = "jessica/passive_ta_up",
                            Modifier = ModifierLibrary.FlatTripleAttackRateBoost,
                            IsUsedInternally = true,
                            Strength = double.PositiveInfinity,
                        });
                    }

                    return true;
                },
                OnAbilityStart = (jessica, raidActions) =>
                {
                    TryProcessUnforgettableSummerHealingBoost(jessica);
                },
            });
        }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var services = context.Services;

            var ecKeyPair = CryptoHelpers.GenerateKeyPair();

            var dposTriggerInformation = new DPoSTriggerInformation()
            {
                PublicKey         = ByteString.CopyFrom(ecKeyPair.PublicKey),
                InitialTermNumber = 1,
                Behaviour         = DPoSBehaviour.NextTerm
            };

            services.AddTransient(o =>
            {
                var mockService = new Mock <IConsensusInformationGenerationService>();
                mockService.Setup(m => m.GetTriggerInformation(TriggerType.ConsensusTransactions)).Returns(
                    dposTriggerInformation);
                mockService.Setup(m => m.GetTriggerInformation(TriggerType.BlockHeaderExtraData)).Returns(
                    dposTriggerInformation);
                mockService.Setup(m => m.GetTriggerInformation(TriggerType.ConsensusCommand)).Returns(
                    new CommandInput {
                    PublicKey = ByteString.CopyFrom(ecKeyPair.PublicKey)
                });
                mockService.Setup(m => m.ParseConsensusTriggerInformation(It.IsAny <byte[]>())).Returns(
                    dposTriggerInformation);
                mockService.Setup(m => m.ExecuteContractAsync <ConsensusCommand>(It.IsAny <IChainContext>(),
                                                                                 It.IsAny <string>(), It.IsAny <IMessage>(), It.IsAny <DateTime>()))
                .Returns(Task.FromResult(new ConsensusCommand
                {
                    NextBlockMiningLeftMilliseconds = 4000,
                    ExpectedMiningTime = DateTime.UtcNow.Add(TimeSpan.FromSeconds(4)).ToTimestamp()
                }));
                mockService.Setup(m => m.ExecuteContractAsync <ValidationResult>(It.IsAny <IChainContext>(),
                                                                                 It.IsAny <string>(), It.IsAny <IMessage>(), It.IsAny <DateTime>()))
                .Returns(Task.FromResult(new ValidationResult
                {
                    Success = true
                }));
                mockService.Setup(m => m.ExecuteContractAsync <TransactionList>(It.IsAny <IChainContext>(),
                                                                                It.IsAny <string>(), It.IsAny <IMessage>(), It.IsAny <DateTime>()))
                .Returns(Task.FromResult(new TransactionList
                {
                    Transactions =
                    {
                        new Transaction {
                            MethodName = ConsensusConsts.GenerateConsensusTransactions, Params = ByteString.CopyFromUtf8("test1")
                        },
                        new Transaction {
                            MethodName = ConsensusConsts.GenerateConsensusTransactions, Params = ByteString.CopyFromUtf8("test2")
                        },
                        new Transaction {
                            MethodName = ConsensusConsts.GenerateConsensusTransactions, Params = ByteString.CopyFromUtf8("test3")
                        }
                    }
                }));
                return(mockService.Object);
            });

            services.AddTransient(o =>
            {
                var mockService = new Mock <IAccountService>();
                mockService.Setup(a => a.SignAsync(It.IsAny <byte[]>())).Returns <byte[]>(data =>
                                                                                          Task.FromResult(CryptoHelpers.SignWithPrivateKey(ecKeyPair.PrivateKey, data)));

                mockService.Setup(a => a.VerifySignatureAsync(It.IsAny <byte[]>(), It.IsAny <byte[]>(), It.IsAny <byte[]>()
                                                              )).Returns <byte[], byte[], byte[]>((signature, data, publicKey) =>
                {
                    var recoverResult = CryptoHelpers.RecoverPublicKey(signature, data, out var recoverPublicKey);
                    return(Task.FromResult(recoverResult && publicKey.BytesEqual(recoverPublicKey)));
                });

                mockService.Setup(a => a.GetPublicKeyAsync()).ReturnsAsync(ecKeyPair.PublicKey);

                return(mockService.Object);
            });

            services.AddTransient(o =>
            {
                var mockService = new Mock <IConsensusScheduler>();

                return(mockService.Object);
            });
            services.AddTransient(o =>
            {
                var mockService = new Mock <IBlockchainService>();
                mockService.Setup(m => m.GetChainAsync()).Returns(
                    Task.FromResult(new Chain()
                {
                    BestChainHash   = Hash.Empty,
                    BestChainHeight = 100
                }));

                return(mockService.Object);
            });
            services.AddTransient <ConsensusControlInformation>();
            services.AddTransient(o =>
            {
                var mockService = new Mock <ISmartContractAddressService>();
                mockService.Setup(m => m.GetAddressByContractName(It.IsAny <Hash>())).Returns(
                    Address.Generate());
                return(mockService.Object);
            });

            services.AddTransient <IConsensusService, ConsensusService>();
            services.AddTransient <ISystemTransactionGenerator, ConsensusTransactionGenerator>();
        }
Example #28
0
 public static ByteString FromHexString(string hexString)
 {
     return(ByteString.CopyFrom(ByteArrayHelper.HexStringToByteArray(hexString)));
 }
        public override async Task <Tfplugin5.ApplyResourceChange.Types.Response> ApplyResourceChange(
            Tfplugin5.ApplyResourceChange.Types.Request request, ServerCallContext context)
        {
            _log.LogDebug(">>>{method}>>>", nameof(ApplyResourceChange));
            _log.LogTrace($"->input[{nameof(request)}] = {{@request}}", request);
            _log.LogTrace($"->input[{nameof(context)}] = {{@context}}", context);

            try
            {
                var response = new Tfplugin5.ApplyResourceChange.Types.Response();

                var plugin  = SchemaHelper.GetPluginDetails(PluginAssembly);
                var resType = plugin.Resources.Where(x =>
                                                     request.TypeName == x.GetCustomAttribute <TFResourceAttribute>()?.Name).First();
                var invokeType = typeof(IHasApplyResourceChange <>).MakeGenericType(resType);
                if (invokeType.IsAssignableFrom(plugin.Provider))
                {
                    var invokeInputType  = typeof(ApplyResourceChangeInput <>).MakeGenericType(resType);
                    var invokeResultType = typeof(ApplyResourceChangeResult <>).MakeGenericType(resType);

                    // Construct and populate the input type instance from the request
                    var invokeInput = Activator.CreateInstance(invokeInputType);

                    var config         = DynamicValue.Unmarshal(resType, request.Config);
                    var priorState     = DynamicValue.Unmarshal(resType, request.PriorState);
                    var plannedPrivate = request.PlannedPrivate.ToByteArray();
                    var plannedState   = DynamicValue.Unmarshal(resType, request.PlannedState);

                    var changeType = ResourceChangeType.Unknown;
                    if (priorState != null)
                    {
                        if (config == null)
                        {
                            changeType = ResourceChangeType.Delete;
                        }
                        else
                        {
                            changeType = ResourceChangeType.Update;
                        }
                    }
                    else
                    if (config != null)
                    {
                        changeType = ResourceChangeType.Create;
                    }
                    else
                    {
                        _log.LogWarning("Planning NULL -> NULL : You Should Never See This!");
                    }

                    _log.LogDebug("Applying " + changeType.ToString().ToUpper());

                    invokeInputType.GetProperty(nameof(PlanResourceChangeInput <object> .ChangeType))
                    .SetValue(invokeInput, changeType);
                    invokeInputType.GetProperty(nameof(request.Config))
                    .SetValue(invokeInput, config);
                    invokeInputType.GetProperty(nameof(request.PriorState))
                    .SetValue(invokeInput, priorState);
                    invokeInputType.GetProperty(nameof(request.PlannedPrivate))
                    .SetValue(invokeInput, plannedPrivate);
                    invokeInputType.GetProperty(nameof(request.PlannedState))
                    .SetValue(invokeInput, plannedState);

                    // Invoke the functional method
                    var invokeMethod = invokeType.GetMethod(nameof(IHasApplyResourceChange <object> .ApplyChange));
                    var invokeResult = invokeMethod.Invoke(_ProviderInstance, new[] { invokeInput });
                    if (invokeResult == null)
                    {
                        throw new Exception("invocation result returned null");
                    }
                    if (!invokeResultType.IsAssignableFrom(invokeResult.GetType()))
                    {
                        throw new Exception("invocation result not of expected type or subclass");
                    }

                    // Deconstruct the result to response type
                    var diagnostics = ((TFDiagnostics)invokeResultType
                                       .GetProperty(nameof(response.Diagnostics)).GetValue(invokeResult));
                    var newPrivate = invokeResultType
                                     .GetProperty(nameof(response.Private)).GetValue(invokeResult);
                    var newState = invokeResultType
                                   .GetProperty(nameof(response.NewState)).GetValue(invokeResult);

                    if (diagnostics.Count() > 0)
                    {
                        response.Diagnostics.Add(diagnostics.All());
                    }
                    if (newPrivate != null)
                    {
                        response.Private = ByteString.CopyFrom((byte[])newPrivate);
                    }
                    if (newState != null)
                    {
                        response.NewState = DynamicValue.Marshal(resType, newState);
                    }
                }

                _log.LogTrace("<-result = {@response}", response);
                return(await Task.FromResult(response));
            }
            catch (Exception ex)
            {
                _log.LogError(ex, "<!exception = ");
                throw;
            }
        }
Example #30
0
        internal static TypedData ToTypedData(this object value)
        {
            if (value is TypedData self)
            {
                return(self);
            }

            TypedData typedData = new TypedData();

            if (value == null)
            {
                return(typedData);
            }

            // Save the original value.
            // We will use the original value when converting to JSON, so members added by ETS can be captured in the serialization.
            var originalValue = value;

            if (value is PSObject psObj && psObj.BaseObject != null)
            {
                value = psObj.BaseObject;
            }

            switch (value)
            {
            case double d:
                typedData.Double = d;
                break;

            case long l:
                typedData.Int = l;
                break;

            case int i:
                typedData.Int = i;
                break;

            case byte[] arr:
                typedData.Bytes = ByteString.CopyFrom(arr);
                break;

            case Stream s:
                typedData.Stream = ByteString.FromStream(s);
                break;

            case HttpResponseContext http:
                typedData.Http = http.ToRpcHttp();
                break;

            case string str:
                if (IsValidJson(str))
                {
                    typedData.Json = str;
                }
                else
                {
                    typedData.String = str;
                }
                break;

            default:
                typedData.Json = ConvertToJson(originalValue);
                break;
            }
            return(typedData);
        }