Exemplo n.º 1
0
        public void ToArray_Success()
        {
            byte[] sourceArray = new byte[] { 18, 178, 255, 70, 0 };
            ByteString result = new ByteString(sourceArray);

            Assert.Equal<byte>(new byte[] { 18, 178, 255, 70, 0 }, result.ToByteArray());
        }
Exemplo n.º 2
0
        internal PopFollowingResponse(ByteString text)
        {
            if (text == null)
            throw new ArgumentNullException("text");

              this.Text = text;
        }
Exemplo n.º 3
0
        public static PopDropListing ToDropListing(ByteString[] texts)
        {
            ThrowIfTooFewTexts(texts, 2);

              return new PopDropListing(ToNumber(texts[0]),
                                ToNumber(texts[1]));
        }
Exemplo n.º 4
0
        protected override SaslExchangeStatus Exchange(ByteString serverChallenge, out ByteString clientResponse)
        {
            if (Credential == null)
            throw new SaslException("Credential property must be set");

              clientResponse = null;

              switch (step /* challenge */) {
            case 0: /* case "Username:"******"Password:": */
              if (string.IsNullOrEmpty(Credential.Password))
            return SaslExchangeStatus.Failed;

              step++;
              clientResponse = new ByteString(Credential.Password);
              return SaslExchangeStatus.Succeeded;

            default: // unexpected server challenge
              clientResponse = null;
              return SaslExchangeStatus.Failed;
              }
        }
Exemplo n.º 5
0
        /**
         * Method attaches a signature (captured) from the UI to a successfully executed transaction
         */
        public EzeResult attachSignature(string txnId, ImageType imageType, ByteString imageData, int height, int width, double tipAmount)
        {
            Console.Error.WriteLine("...attachSignature <" + txnId + ">");

            SignatureInput signatureInput = SignatureInput.CreateBuilder()
                    .SetTxnId(txnId)
                    .SetImageType(MapImageType(imageType))
                    .SetImageBytes(imageData)
                    .SetHeight(height)
                    .SetWidth(width)
                    .SetTipAmount(tipAmount)
                    .Build();

            ApiInput apiInput = ApiInput.CreateBuilder()
                    .SetMsgType(ApiInput.Types.MessageType.ATTACH_SIGNATURE)
                    .SetMsgData(signatureInput.ToByteString()).Build();

            this.send(apiInput);
            EzeResult result = null;

            while (true)
            {
                result = this.getResult(this.receive());
                if (result.getEventName() == EventName.ATTACH_SIGNATURE) break;
            }
            return result;
        }
Exemplo n.º 6
0
 /// <summary>
 /// Parses a message from the given byte string.
 /// </summary>
 /// <param name="data">The data to parse.</param>
 /// <returns>The parsed message.</returns>
 public IMessage ParseFrom(ByteString data)
 {
     Preconditions.CheckNotNull(data, "data");
     IMessage message = factory();
     message.MergeFrom(data);
     return message;
 }
Exemplo n.º 7
0
 public OutboundTransaction(ByteString recordKey, long amount, ByteString version, string target)
 {
     this.RecordKey = recordKey;
     this.Amount = amount;
     this.Version = version;
     this.Target = target;
 }
Exemplo n.º 8
0
        protected override SaslExchangeStatus Exchange(ByteString serverChallenge, out ByteString clientResponse)
        {
            // 2. The Anonymous Mechanism
              //    The mechanism consists of a single message from the client to the
              //    server.  The client may include in this message trace information in
              //    the form of a string of [UTF-8]-encoded [Unicode] characters prepared
              //    in accordance with [StringPrep] and the "trace" stringprep profile
              //    defined in Section 3 of this document.  The trace information, which
              //    has no semantical value, should take one of two forms: an Internet
              //    email address, or an opaque string that does not contain the '@'
              //    (U+0040) character and that can be interpreted by the system
              //    administrator of the client's domain.  For privacy reasons, an
              //    Internet email address or other information identifying the user
              //    should only be used with permission from the user.
              if (Credential == null)
            throw new SaslException("Credential property must be set");

              clientResponse = null;

              if (string.IsNullOrEmpty(Credential.UserName))
            return SaslExchangeStatus.Failed;

              // XXX
              clientResponse = new ByteString(Encoding.UTF8.GetBytes(Credential.UserName));

              return SaslExchangeStatus.Succeeded;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Mutation"/> class.
        /// </summary>
        /// <param name="@namespace">The namespace in which the mutation operates.</param>
        /// <param name="records">A collection of all the records affected by the mutation.</param>
        /// <param name="metadata">The metadata associated with the mutation.</param>
        public Mutation(ByteString @namespace, IEnumerable<Record> records, ByteString metadata)
        {
            if (@namespace == null)
                throw new ArgumentNullException(nameof(@namespace));

            if (records == null)
                throw new ArgumentNullException(nameof(records));

            if (metadata == null)
                throw new ArgumentNullException(nameof(metadata));

            this.Namespace = @namespace;
            this.Records = records.ToList().AsReadOnly();
            this.Metadata = metadata;

            // Records must not be null
            if (this.Records.Any(entry => entry == null))
                throw new ArgumentNullException(nameof(records));

            // There must not be any duplicate keys
            HashSet<ByteString> keys = new HashSet<ByteString>();
            foreach (Record record in this.Records)
            {
                if (keys.Contains(record.Key))
                    throw new ArgumentNullException(nameof(records));

                keys.Add(record.Key);
            }
        }
Exemplo n.º 10
0
        public async Task<ByteString> PostTransaction(ByteString rawMutation, IReadOnlyList<SignatureEvidence> authentication)
        {
            Mutation mutation;
            try
            {
                // Verify that the mutation can be deserialized
                mutation = MessageSerializer.DeserializeMutation(rawMutation);
            }
            catch (InvalidProtocolBufferException)
            {
                throw new TransactionInvalidException("InvalidMutation");
            }

            if (!mutation.Namespace.Equals(this.ledgerId))
                throw new TransactionInvalidException("InvalidNamespace");

            if (mutation.Records.Count == 0)
                throw new TransactionInvalidException("InvalidMutation");

            if (mutation.Records.Any(record => record.Key.Value.Count > MaxKeySize))
                throw new TransactionInvalidException("InvalidMutation");

            ValidateAuthentication(authentication, MessageSerializer.ComputeHash(rawMutation.ToByteArray()));

            ParsedMutation parsedMutation = ParsedMutation.Parse(mutation);

            // All assets must have an overall zero balance

            IReadOnlyDictionary<AccountKey, AccountStatus> accounts =
                await this.store.GetAccounts(parsedMutation.AccountMutations.Select(entry => entry.AccountKey));

            var groups = parsedMutation.AccountMutations
                .GroupBy(account => account.AccountKey.Asset.FullPath)
                .Select(group => group.Sum(entry => entry.Balance - accounts[entry.AccountKey].Balance));

            if (groups.Any(group => group != 0))
                throw new TransactionInvalidException("UnbalancedTransaction");

            DateTime date = DateTime.UtcNow;

            await this.validator.Validate(parsedMutation, authentication, accounts);

            TransactionMetadata metadata = new TransactionMetadata(authentication);

            byte[] rawMetadata = SerializeMetadata(metadata);

            Transaction transaction = new Transaction(rawMutation, date, new ByteString(rawMetadata));
            byte[] serializedTransaction = MessageSerializer.SerializeTransaction(transaction);

            try
            {
                await this.store.AddTransactions(new[] { new ByteString(serializedTransaction) });
            }
            catch (ConcurrentMutationException)
            {
                throw new TransactionInvalidException("OptimisticConcurrency");
            }

            return new ByteString(MessageSerializer.ComputeHash(serializedTransaction));
        }
Exemplo n.º 11
0
        public static async Task<Record> GetRecordVersion(this ILedgerQueries queries, ByteString key, ByteString version)
        {
            if (version.Value.Count == 0)
            {
                return new Record(key, ByteString.Empty, ByteString.Empty);
            }
            else
            {
                ByteString rawTransaction = await queries.GetTransaction(version);

                if (rawTransaction == null)
                {
                    return null;
                }
                else
                {
                    Transaction transaction = MessageSerializer.DeserializeTransaction(rawTransaction);
                    Mutation mutation = MessageSerializer.DeserializeMutation(transaction.Mutation);

                    Record result = mutation.Records.FirstOrDefault(record => record.Key.Equals(key) && record.Value != null);

                    if (result == null)
                        return null;
                    else
                        return result;
                }
            }
        }
Exemplo n.º 12
0
        public void TestContains()
        {
            var str = new ByteString("ababdabdbdabcab");

              Assert.IsTrue(str.Contains(new ByteString("abc")));
              Assert.IsTrue(str.Contains(new ByteString("abd")));
              Assert.IsFalse(str.Contains(new ByteString("abe")));
        }
Exemplo n.º 13
0
 public UnknownFieldSetTest()
 {
     descriptor = TestAllTypes.Descriptor;
     allFields = TestUtil.GetAllSet();
     allFieldsData = allFields.ToByteString();
     emptyMessage = TestEmptyMessage.ParseFrom(allFieldsData);
     unknownFields = emptyMessage.UnknownFields;
 }
Exemplo n.º 14
0
 /// <summary>
 /// Merges data from the given byte string into an existing message.
 /// </summary>
 /// <param name="message">The message to merge the data into.</param>
 /// <param name="data">The data to merge, which must be protobuf-encoded binary data.</param>
 public static void MergeFrom(this IMessage message, ByteString data)
 {
     ProtoPreconditions.CheckNotNull(message, "message");
     ProtoPreconditions.CheckNotNull(data, "data");
     CodedInputStream input = data.CreateCodedInput();
     message.MergeFrom(input);
     input.CheckReadEndOfStreamTag();
 }
Exemplo n.º 15
0
        public void TestConstructFromString()
        {
            var s = new ByteString("abc");

              Assert.IsFalse(s.IsEmpty);
              Assert.AreEqual(3, s.Length);
              Assert.AreEqual(new byte[] {0x61, 0x62, 0x63}, s.ByteArray);
        }
Exemplo n.º 16
0
        public AkkaProtocolSpec()
        {
            testEnvelope = codec.ConstructMessage(localAkkaAddress, testActor, testMsg);
            testMsgPdu = codec.ConstructPayload(testEnvelope);

            testHeartbeat = new InboundPayload(codec.ConstructHeartbeat());
            testPayload = new InboundPayload(testMsgPdu);
        }
Exemplo n.º 17
0
 public string DecodeEscapedString(int end, int skip, Encoding encoding)
 {
     if(CheckValue('\"'))
     {
         var sb = new StringBuilder(end - Position);
         ByteString bs = null;
         var bytes = new byte[end - Position + 1];
         Skip();
         while(Position < end)
         {
             var c = ReadChar();
             if(c == '\\')
             {
                 var nc = CurrentChar;
                 if(nc.IsOctDigit())
                 {
                     if(bs == null)
                     {
                         var bufferSize = end - Position;
                         if(bufferSize < 1) bufferSize = 1;
                         bs = new ByteString(end - Position);
                     }
                     int len = 1;
                     int start = Position;
                     Skip();
                     while(CurrentChar.IsOctDigit())
                     {
                         Skip();
                         ++len;
                     }
                     bs.AppendByte(ByteFromOctString(String, start, len));
                 }
                 else
                 {
                     ByteString.Dump(bs, sb, encoding);
                     HandleEscapeCode(sb, nc);
                     Skip();
                 }
             }
             else if(c == '\"')
             {
                 ByteString.Dump(bs, sb, encoding);
                 break;
             }
             else
             {
                 ByteString.Dump(bs, sb, encoding);
                 sb.Append(c);
             }
         }
         Position = end + skip;
         return sb.ToString();
     }
     else
     {
         return ReadStringUpTo(end, skip);
     }
 }
Exemplo n.º 18
0
        public void Constructor_Success()
        {
            byte[] sourceArray = new byte[] { 18, 178, 255, 70, 0 };
            ByteString result = new ByteString(sourceArray);
            sourceArray[4] = 1;

            Assert.NotSame(sourceArray, result.Value);
            Assert.Equal<byte>(new byte[] { 18, 178, 255, 70, 0 }, result.Value);
        }
Exemplo n.º 19
0
        public static long ToMessageNumber(ByteString text)
        {
            var val = ToNumber(text);

              if (val == 0L)
            throw new PopMalformedTextException(string.Format("must be non-zero positive number, but was {0}", val));

              return val;
        }
Exemplo n.º 20
0
        public void Parse_Data()
        {
            ByteString data = new ByteString(Encoding.UTF8.GetBytes("/aka/name/:DATA:record:name"));
            RecordKey key = RecordKey.Parse(data);

            Assert.Equal(RecordType.Data, key.RecordType);
            Assert.Equal("/aka/name/", key.Path.FullPath);
            Assert.Equal("record:name", key.Name);
        }
Exemplo n.º 21
0
 public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
 {
     var key = recordKey.ToByteArray();
     var res = await TransactionCollection.Find(Builders<MongoDbTransaction>.Filter.AnyEq(x=>x.Records, key))
         .Project(x=>x.MutationHash)
         .SortBy(x=>x.Timestamp)
         .ToListAsync();
     return res.Select(x=>new ByteString(x)).ToList().AsReadOnly();
 }
Exemplo n.º 22
0
        public void Parse_Account()
        {
            ByteString data = new ByteString(Encoding.UTF8.GetBytes("/account/name/:ACC:/asset/name/"));
            RecordKey key = RecordKey.Parse(data);

            Assert.Equal(RecordType.Account, key.RecordType);
            Assert.Equal("/account/name/", key.Path.FullPath);
            Assert.Equal("/asset/name/", key.Name);
        }
Exemplo n.º 23
0
        public AkkaProtocolSpec()
            : base(@"akka.test.default-timeout = 1.5 s")
        {
            testEnvelope = codec.ConstructMessage(localAkkaAddress, TestActor, testMsg);
            testMsgPdu = codec.ConstructPayload(testEnvelope);

            testHeartbeat = new InboundPayload(codec.ConstructHeartbeat());
            testPayload = new InboundPayload(testMsgPdu);
        }
        public static async Task<IReadOnlyList<Record>> GetSubaccounts(this ILedgerQueries queries, string rootAccount)
        {
            ByteString prefix = new ByteString(Encoding.UTF8.GetBytes(rootAccount));
            IReadOnlyList<Record> records = await queries.GetKeyStartingFrom(prefix);

            return records
                .Where(record => !record.Value.Equals(ByteString.Empty))
                .ToList()
                .AsReadOnly();
        }
Exemplo n.º 25
0
        public static async Task<IReadOnlyList<AccountStatus>> GetAccount(this ILedgerQueries queries, string account)
        {
            ByteString prefix = new ByteString(Encoding.UTF8.GetBytes(account + ":ACC:"));
            IReadOnlyList<Record> records = await queries.GetKeyStartingFrom(prefix);

            return records
                .Select(record => AccountStatus.FromRecord(RecordKey.Parse(record.Key), record))
                .ToList()
                .AsReadOnly();
        }
Exemplo n.º 26
0
 /// <summary>
 /// Converts a <see cref="ByteString"/> structure into a Helios <see cref="NetworkData"/> structure
 /// </summary>
 /// <param name="byteString">The data to send over the network</param>
 /// <param name="address">The address that we received data from / are sending data to</param>
 /// <returns>a new <see cref="NetworkData"/> struct</returns>
 public static NetworkData ToData(ByteString byteString, Address address)
 {
     var data = new NetworkData()
     {
         Buffer = byteString.ToByteArray(),
         RemoteHost = HeliosTransport.AddressToNode(address)
     };
     data.Length = data.Buffer.Length;
     return data;
 }
Exemplo n.º 27
0
        public override void Setup()
        {
            base.Setup();
            testEnvelope = codec.ConstructMessage(localAkkaAddress, testActor, testMsg);
            testMsgPdu = codec.ConstructPayload(testEnvelope);

            testHeartbeat = new InboundPayload(codec.ConstructHeartbeat());
            testPayload = new InboundPayload(testMsgPdu);


        }
Exemplo n.º 28
0
 public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
 {
     return await ExecuteQuery<ByteString>(
         "EXEC [Openchain].[GetRecordMutations] @instance, @recordKey;",
         reader => new ByteString((byte[])reader[0]),
         new Dictionary<string, object>()
         {
             ["instance"] = this.instanceId,
             ["recordKey"] = recordKey.ToByteArray()
         });
 }
Exemplo n.º 29
0
 public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
 {
     return await ExecuteAsync(@"
             SELECT  MutationHash
             FROM    RecordMutations
             WHERE   RecordKey = @recordKey",
         reader => new ByteString((byte[])reader.GetValue(0)),
         new Dictionary<string, object>()
         {
             ["@recordKey"] = recordKey.ToByteArray()
         });
 }
Exemplo n.º 30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Record"/> class.
        /// </summary>
        /// <param name="key">The key of the record.</param>
        /// <param name="value">The value of the record.</param>
        /// <param name="version">The version of the record.</param>
        public Record(ByteString key, ByteString value, ByteString version)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));

            if (version == null)
                throw new ArgumentNullException(nameof(version));

            this.Key = key;
            this.Value = value;
            this.Version = version;
        }
 private static IEnumerable <ByteString> StringToByteString(IEnumerable <string> str)
 => str.Select(s => ByteString.CopyFrom(Encoding.UTF8.GetBytes(s)));
Exemplo n.º 32
0
 public static object Deserialize(string typeName, ByteString bytes, int serializerId) => Serializers[serializerId].Deserialize(bytes, typeName);
Exemplo n.º 33
0
        private static object ConvertValue(ProtoBuf.Share.DataEntry.Types.Type dataEntryType, ByteString value)
        {
            NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

            switch (dataEntryType)
            {
            case ProtoBuf.Share.DataEntry.Types.Type.ThirdPartyAttribute:
                return(ThirdPartyAttributeConverter.ParseThirdPartyAttribute(value.ToByteArray()));

            default:
                logger.Warn($"Unsupported data entry '{dataEntryType.ToString()}', skipping...");
                return(null);
            }
        }
Exemplo n.º 34
0
 public static objectCoords ParseFrom(ByteString data)
 {
     return(CreateBuilder().MergeFrom(data).BuildParsed());
 }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            base.ConfigureServices(context);

            var dictionary = new Dictionary <long, Hash>
            {
                { 1, Hash.FromString("1") },
                { 2, Hash.FromString("2") },
                { 3, Hash.FromString("3") }
            };

            Configure <GrpcCrossChainConfigOption>(option =>
            {
                option.ListeningPort         = 5001;
                option.ParentChainServerIp   = "127.0.0.1";
                option.ParentChainServerPort = 5000;
            });

            Configure <CrossChainConfigOptions>(option =>
            {
                option.ParentChainId = ChainHelper.ConvertChainIdToBase58(ChainHelper.GetChainId(1));
            });

            context.Services.AddTransient(provider =>
            {
                var kernelTestHelper      = context.Services.GetRequiredServiceLazy <KernelTestHelper>();
                var mockBlockChainService = new Mock <IBlockchainService>();
                mockBlockChainService.Setup(m => m.GetChainAsync()).Returns(() =>
                {
                    var chain = new Chain {
                        LastIrreversibleBlockHeight = 10
                    };
                    return(Task.FromResult(chain));
                });
                mockBlockChainService.Setup(m =>
                                            m.GetBlockHashByHeightAsync(It.IsAny <Chain>(), It.IsAny <long>(), It.IsAny <Hash>()))
                .Returns <Chain, long, Hash>((chain, height, hash) =>
                {
                    if (height > 0 && height <= 3)
                    {
                        return(Task.FromResult(dictionary[height]));
                    }
                    return(Task.FromResult <Hash>(null));
                });
                mockBlockChainService.Setup(m => m.GetBlockByHashAsync(It.IsAny <Hash>())).Returns <Hash>(hash =>
                {
                    foreach (var kv in dictionary)
                    {
                        if (kv.Value.Equals(hash))
                        {
                            var block = kernelTestHelper.Value.GenerateBlock(kv.Key - 1, dictionary[kv.Key - 1]);
                            return(Task.FromResult(block));
                        }
                    }

                    return(Task.FromResult <Block>(null));
                });
                return(mockBlockChainService.Object);
            });

            context.Services.AddTransient(provider =>
            {
                var mockBlockExtraDataService = new Mock <IBlockExtraDataService>();
                mockBlockExtraDataService
                .Setup(m => m.GetExtraDataFromBlockHeader(It.IsAny <string>(), It.IsAny <BlockHeader>())).Returns(
                    () =>
                {
                    var crossExtraData = new CrossChainExtraData
                    {
                        TransactionStatusMerkleTreeRoot = Hash.FromString("SideChainBlockHeadersRoot"),
                    };
                    return(ByteString.CopyFrom(crossExtraData.ToByteArray()));
                });
                return(mockBlockExtraDataService.Object);
            });

            context.Services.AddTransient(provider =>
            {
                var mockCrossChainIndexingDataService = new Mock <ICrossChainIndexingDataService>();
                mockCrossChainIndexingDataService
                .Setup(m => m.GetIndexedCrossChainBlockDataAsync(It.IsAny <Hash>(), It.IsAny <long>()))
                .Returns(() =>
                {
                    var crossChainBlockData = new CrossChainBlockData
                    {
                        SideChainBlockData =
                        {
                            new SideChainBlockData
                            {
                                ChainId = 123, Height = 1,
                                TransactionStatusMerkleTreeRoot = Hash.FromString("fakeTransactionMerkleTree")
                            }
                        }
                    };
                    return(Task.FromResult(crossChainBlockData));
                });
                mockCrossChainIndexingDataService
                .Setup(m => m.GetIndexedSideChainBlockDataAsync(It.IsAny <Hash>(), It.IsAny <long>())).Returns(
                    () =>
                {
                    var indexedSideChainBlockData = new IndexedSideChainBlockData
                    {
                        SideChainBlockData =
                        {
                            new SideChainBlockData
                            {
                                ChainId = 123, Height = 1,
                                TransactionStatusMerkleTreeRoot = Hash.FromString("fakeTransactionMerkleTree")
                            }
                        }
                    };
                    return(Task.FromResult(indexedSideChainBlockData));
                });
                return(mockCrossChainIndexingDataService.Object);
            });

            context.Services.AddTransient(provider =>
            {
                var mockCrossChainClientProvider = new Mock <ICrossChainClientProvider>();
                mockCrossChainClientProvider.Setup(m => m.CreateCrossChainClient(It.IsAny <CrossChainClientDto>()))
                .Returns(() =>
                {
                    var mockCrossChainClient = new Mock <ICrossChainClient>();
                    mockCrossChainClient.Setup(m => m.RequestChainInitializationDataAsync(It.IsAny <int>())).Returns(() =>
                    {
                        var chainInitialization = new ChainInitializationData
                        {
                            CreationHeightOnParentChain = 1
                        };
                        return(Task.FromResult(chainInitialization));
                    });
                    mockCrossChainClient.Setup(m => m.RequestCrossChainDataAsync(It.IsAny <long>(), It.IsAny <Func <IBlockCacheEntity, bool> >())).Returns(() =>
                    {
                        var chainInitialization = new ChainInitializationData
                        {
                            CreationHeightOnParentChain = 1
                        };
                        return(Task.FromResult(chainInitialization));
                    });
                    return(mockCrossChainClient.Object);
                });
                return(mockCrossChainClientProvider.Object);
            });

            context.Services.AddSingleton <CrossChainPlugin>();
        }
 private static IEnumerable <ByteString> StringToByteString(IEnumerable <ReadOnlyMemory <char> > str)
 => str.Select(s => ByteString.CopyFrom(Encoding.UTF8.GetBytes(s.ToString())));
Exemplo n.º 37
0
 public static Quaternion ParseFrom(ByteString data, ExtensionRegistry extensionRegistry)
 {
     return(CreateBuilder().MergeFrom(data, extensionRegistry).BuildParsed());
 }
Exemplo n.º 38
0
 public override void OnPush()
 {
     _buffer += Grab(_stage.Inlet);
     Rechunk();
 }
Exemplo n.º 39
0
 public static ServerNotifyResult ParseFrom(ByteString data)
 {
     return(ServerNotifyResult.CreateBuilder().MergeFrom(data).BuildParsed());
 }
Exemplo n.º 40
0
 public static ServerNotifyResult ParseFrom(
     ByteString data,
     ExtensionRegistry extensionRegistry)
 {
     return(ServerNotifyResult.CreateBuilder().MergeFrom(data, extensionRegistry).BuildParsed());
 }
Exemplo n.º 41
0
 /// <exception cref="Com.Google.Protobuf.InvalidProtocolBufferException"/>
 public static ConcatVectorTableProto.ConcatVectorTable ParseFrom(ByteString data, ExtensionRegistryLite extensionRegistry)
 {
     return(Parser.ParseFrom(data, extensionRegistry));
 }
Exemplo n.º 42
0
 /// <exception cref="Com.Google.Protobuf.InvalidProtocolBufferException"/>
 public static ConcatVectorTableProto.ConcatVectorTable ParseFrom(ByteString data)
 {
     return(Parser.ParseFrom(data));
 }
Exemplo n.º 43
0
 private void SendMessage(Message message)
 {
     ack = false;
     SendData(ByteString.FromBytes(message.ToArray()));
 }
Exemplo n.º 44
0
        private static ByteStringContext.ExternalScope CreateCounterKeySlice(DocumentsOperationContext context, ByteString buffer, Slice documentIdPrefix, Slice counterName, out Slice counterKeySlice)
        {
            var scope = Slice.External(context.Allocator, buffer.Ptr, buffer.Length, out counterKeySlice);

            documentIdPrefix.CopyTo(buffer.Ptr);
            counterName.CopyTo(buffer.Ptr + documentIdPrefix.Size);
            return(scope);
        }
Exemplo n.º 45
0
 public static Quaternion ParseFrom(ByteString data)
 {
     return(CreateBuilder().MergeFrom(data).BuildParsed());
 }
Exemplo n.º 46
0
 private static Flow <ByteString, string, NotUsed> SimpleLines(string delimiter, int maximumBytes, bool allowTruncation = true)
 {
     return(Framing.Delimiter(ByteString.FromString(delimiter), maximumBytes, allowTruncation)
            .Select(x => x.ToString(Encoding.UTF8)).Named("LineFraming"));
 }
Exemplo n.º 47
0
        public async Task ClientStream_HttpClientWithTimeout_Success()
        {
            SetExpectedErrorsFilter(writeContext =>
            {
                if (writeContext.LoggerName == "Grpc.Net.Client.Internal.GrpcCall" &&
                    writeContext.Exception is TaskCanceledException)
                {
                    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);
            });

            using var httpEventListener = new HttpEventSourceListener(LoggerFactory);

            var tcs = new TaskCompletionSource <object?>(TaskCreationOptions.RunContinuationsAsynchronously);

            async Task <DataComplete> ClientStreamedData(IAsyncStreamReader <DataMessage> requestStream, ServerCallContext context)
            {
                Logger.LogInformation("Server started");
                context.CancellationToken.Register(() =>
                {
                    Logger.LogInformation("Server completed TCS");
                    tcs.SetResult(null);
                });

                var total = 0L;

                await foreach (var message in requestStream.ReadAllAsync())
                {
                    total += message.Data.Length;

                    if (message.ServerDelayMilliseconds > 0)
                    {
                        await Task.Delay(message.ServerDelayMilliseconds);
                    }
                }

                return(new DataComplete
                {
                    Size = total
                });
            }

            // Arrange
            var data = CreateTestData(1024); // 1 KB

            var method = Fixture.DynamicGrpc.AddClientStreamingMethod <DataMessage, DataComplete>(ClientStreamedData, "ClientStreamedDataTimeout");

            var httpClient = Fixture.CreateClient();

            httpClient.Timeout = TimeSpan.FromSeconds(0.5);

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

            var client = TestClientFactory.Create(channel, method);

            var dataMessage = new DataMessage
            {
                Data = ByteString.CopyFrom(data)
            };

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

            Logger.LogInformation("Client writing message");
            await call.RequestStream.WriteAsync(dataMessage).DefaultTimeout();

            Logger.LogInformation("Client waiting for TCS to complete");
            await tcs.Task.DefaultTimeout();

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

            // Assert
            Assert.AreEqual(StatusCode.Cancelled, ex.StatusCode);
            Assert.AreEqual(StatusCode.Cancelled, call.GetStatus().StatusCode);

            AssertHasLog(LogLevel.Information, "GrpcStatusError", "Call failed with gRPC error status. Status code: 'Cancelled', Message: ''.");

            await TestHelpers.AssertIsTrueRetryAsync(
                () => HasLog(LogLevel.Error, "ErrorExecutingServiceMethod", "Error when executing service method 'ClientStreamedDataTimeout'."),
                "Wait for server error so it doesn't impact other tests.").DefaultTimeout();
        }
Exemplo n.º 48
0
 public static RustProto.Blueprint ParseFrom(ByteString data, ExtensionRegistry extensionRegistry)
 {
     return(CreateBuilder().MergeFrom(data, extensionRegistry).BuildParsed());
 }
Exemplo n.º 49
0
 public static RustProto.Blueprint ParseFrom(ByteString data)
 {
     return(CreateBuilder().MergeFrom(data).BuildParsed());
 }
Exemplo n.º 50
0
        public void Convert_ByteArray_To_ByteString_Should_Fail()
        {
            var testBytes = new byte[500];

            testBytes.ToByteString().Should().Equal(ByteString.CopyFrom(testBytes));
        }
 private static ByteString StringToByteString(ReadOnlyMemory <char> str) => ByteString.CopyFrom(Encoding.UTF8.GetBytes(str.ToString()));
Exemplo n.º 52
0
        public async ETVoid DispatchAsync(Session session, ushort opcode, object message)
        {
            // 根据消息接口判断是不是Actor消息,不同的接口做不同的处理
            switch (message)
            {
            case IFrameMessage iFrameMessage:                     // 如果是帧消息,构造成OneFrameMessage发给对应的unit
            {
                long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId;
                ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId);

                // 这里设置了帧消息的id,防止客户端伪造
                iFrameMessage.Id = unitId;

                OneFrameMessage oneFrameMessage = new OneFrameMessage
                {
                    Op       = opcode,
                    AMessage = ByteString.CopyFrom(session.Network.MessagePacker.SerializeTo(iFrameMessage))
                };
                //actorLocationSender.Send(oneFrameMessage);
                Game.Scene.GetComponent <ServerFrameComponent>().Add(oneFrameMessage);
                return;
            }

            case IActorLocationRequest actorLocationRequest:                     // gate session收到actor rpc消息,先向actor 发送rpc请求,再将请求结果返回客户端
            {
                long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId;
                ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId);

                int       rpcId      = actorLocationRequest.RpcId;              // 这里要保存客户端的rpcId
                long      instanceId = session.InstanceId;
                IResponse response   = await actorLocationSender.Call(actorLocationRequest);

                response.RpcId = rpcId;

                // session可能已经断开了,所以这里需要判断
                if (session.InstanceId == instanceId)
                {
                    session.Reply(response);
                }

                break;
            }

            case IActorLocationMessage actorLocationMessage:
            {
                long unitId = session.GetComponent <SessionPlayerComponent>().Player.UnitId;
                ActorLocationSender actorLocationSender = Game.Scene.GetComponent <ActorLocationSenderComponent>().Get(unitId);
                actorLocationSender.Send(actorLocationMessage);
                break;
            }

            case IActorRequest actorRequest:                      // 分发IActorRequest消息,目前没有用到,需要的自己添加
            {
                break;
            }

            case IActorMessage actorMessage:                      // 分发IActorMessage消息,目前没有用到,需要的自己添加
            {
                break;
            }

            default:
            {
                // 非Actor消息
                Game.Scene.GetComponent <MessageDispatcherComponent>().Handle(session, new MessageInfo(opcode, message));
                break;
            }
            }
        }
Exemplo n.º 53
0
        public async Task Create_ProposalFailed_Test()
        {
            var organizationAddress = await CreateOrganizationAsync();

            var blockTime           = BlockTimeProvider.GetBlockTime();
            var createProposalInput = new CreateProposalInput
            {
                ToAddress           = SampleAddress.AddressList[0],
                Params              = ByteString.CopyFromUtf8("Test"),
                ExpiredTime         = blockTime.AddDays(1),
                OrganizationAddress = organizationAddress
            };
            //"Invalid proposal."
            //ContractMethodName is null or white space
            {
                var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendWithExceptionAsync(createProposalInput);

                transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed);
                transactionResult.TransactionResult.Error.Contains("Invalid proposal.").ShouldBeTrue();
            }
            //ToAddress is null
            {
                createProposalInput.ContractMethodName = "Test";
                createProposalInput.ToAddress          = null;

                var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendWithExceptionAsync(createProposalInput);

                transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed);
                transactionResult.TransactionResult.Error.Contains("Invalid proposal.").ShouldBeTrue();
            }
            //ExpiredTime is null
            {
                createProposalInput.ExpiredTime = null;
                createProposalInput.ToAddress   = SampleAddress.AddressList[0];

                var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendWithExceptionAsync(createProposalInput);

                transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed);
                transactionResult.TransactionResult.Error.Contains("Invalid proposal.").ShouldBeTrue();
            }
            //"Expired proposal."
            {
                createProposalInput.ExpiredTime = blockTime.AddMilliseconds(5);
                Thread.Sleep(10);

                var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendWithExceptionAsync(createProposalInput);

                transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed);
            }
            //"No registered organization."
            {
                createProposalInput.ExpiredTime         = BlockTimeProvider.GetBlockTime().AddDays(1);
                createProposalInput.OrganizationAddress = SampleAddress.AddressList[1];

                var transactionResult = await ParliamentAuthContractStub.CreateProposal.SendWithExceptionAsync(createProposalInput);

                transactionResult.TransactionResult.Status.ShouldBe(TransactionResultStatus.Failed);
                transactionResult.TransactionResult.Error.Contains("No registered organization.").ShouldBeTrue();
            }
            //"Proposal with same input."
            {
                createProposalInput.OrganizationAddress = organizationAddress;
                var transactionResult1 = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput);

                transactionResult1.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined);

                var transactionResult2 = await ParliamentAuthContractStub.CreateProposal.SendAsync(createProposalInput);

                transactionResult2.TransactionResult.Status.ShouldBe(TransactionResultStatus.Mined);
            }
        }
        public async Task Candidates_NotEnough_Test()
        {
            await InitializeCandidates(EconomicContractsTestConstants.InitialCoreDataCenterCount);

            var firstRound = await AEDPoSContractStub.GetCurrentRoundInformation.CallAsync(new Empty());

            var randomHashes = Enumerable.Range(0, EconomicContractsTestConstants.InitialCoreDataCenterCount)
                               .Select(_ => HashHelper.ComputeFrom("hash3")).ToList();
            var triggers = Enumerable.Range(0, EconomicContractsTestConstants.InitialCoreDataCenterCount).Select(i =>
                                                                                                                 new AElfConsensusTriggerInformation
            {
                Pubkey  = ByteString.CopyFrom(InitialCoreDataCenterKeyPairs[i].PublicKey),
                InValue = randomHashes[i]
            }).ToDictionary(t => t.Pubkey.ToHex(), t => t);

            var voter = GetElectionContractTester(VoterKeyPairs[0]);

            foreach (var candidateKeyPair in ValidationDataCenterKeyPairs.Take(EconomicContractsTestConstants
                                                                               .InitialCoreDataCenterCount))
            {
                await voter.Vote.SendAsync(new VoteMinerInput
                {
                    CandidatePubkey = candidateKeyPair.PublicKey.ToHex(),
                    Amount          = 100 + new Random().Next(1, 200),
                    EndTimestamp    = TimestampHelper.GetUtcNow().AddDays(100)
                });
            }

            foreach (var minerInRound in firstRound.RealTimeMinersInformation.Values.OrderBy(m => m.Order))
            {
                var currentKeyPair =
                    InitialCoreDataCenterKeyPairs.First(p => p.PublicKey.ToHex() == minerInRound.Pubkey);

                KeyPairProvider.SetKeyPair(currentKeyPair);

                BlockTimeProvider.SetBlockTime(minerInRound.ExpectedMiningTime);

                var tester            = GetAEDPoSContractStub(currentKeyPair);
                var headerInformation =
                    (await AEDPoSContractStub.GetConsensusExtraData.CallAsync(triggers[minerInRound.Pubkey]
                                                                              .ToBytesValue())).ToConsensusHeaderInformation();

                // Update consensus information.
                var toUpdate = headerInformation.Round.ExtractInformationToUpdateConsensus(minerInRound.Pubkey);
                await tester.UpdateValue.SendAsync(toUpdate);
            }

            var changeTermTime = BlockchainStartTimestamp.ToDateTime()
                                 .AddMinutes(AEDPoSContractTestConstants.PeriodSeconds + 1);

            BlockTimeProvider.SetBlockTime(changeTermTime.ToTimestamp());

            var nextTermInformation = (await AEDPoSContractStub.GetConsensusExtraData.CallAsync(
                                           new AElfConsensusTriggerInformation
            {
                Behaviour = AElfConsensusBehaviour.NextTerm,
                Pubkey = ByteString.CopyFrom(BootMinerKeyPair.PublicKey)
            }.ToBytesValue())).ToConsensusHeaderInformation();

            await AEDPoSContractStub.NextTerm.SendAsync(nextTermInformation.Round);

            // First candidate cheat others with in value.
            var oneCandidate             = GetAEDPoSContractStub(ValidationDataCenterKeyPairs[0]);
            var anotherCandidate         = GetAEDPoSContractStub(ValidationDataCenterKeyPairs[1]);
            var randomHash               = HashHelper.ComputeFrom("hash5");
            var informationOfSecondRound = (await AEDPoSContractStub.GetConsensusExtraData.CallAsync(
                                                new AElfConsensusTriggerInformation
            {
                Behaviour = AElfConsensusBehaviour.UpdateValue,
                PreviousInValue = Hash.Empty,
                InValue = randomHash,
                Pubkey = ByteString.CopyFrom(ValidationDataCenterKeyPairs[0].PublicKey)
            }.ToBytesValue())).ToConsensusHeaderInformation();
            var updateResult = await oneCandidate.UpdateValue.SendAsync(
                informationOfSecondRound.Round.ExtractInformationToUpdateConsensus(ValidationDataCenterKeyPairs[0]
                                                                                   .PublicKey.ToHex()));

            var thirdRoundStartTime = changeTermTime.AddMinutes(AEDPoSContractTestConstants.PeriodSeconds + 2);

            BlockTimeProvider.SetBlockTime(thirdRoundStartTime.ToTimestamp());
            var thirdRound = (await AEDPoSContractStub.GetConsensusExtraData.CallAsync(
                                  new AElfConsensusTriggerInformation
            {
                Behaviour = AElfConsensusBehaviour.NextRound,
                Pubkey = ByteString.CopyFrom(ValidationDataCenterKeyPairs[0].PublicKey)
            }.ToBytesValue())).ToConsensusHeaderInformation().Round;

            await oneCandidate.NextRound.SendAsync(thirdRound);

            var cheatInformation = (await AEDPoSContractStub.GetConsensusExtraData.CallAsync(
                                        new AElfConsensusTriggerInformation
            {
                Behaviour = AElfConsensusBehaviour.UpdateValue,
                PreviousInValue = HashHelper.ComputeFrom(randomHash), // Not same as before.
                InValue = HashHelper.ComputeFrom("InValue"),          // Don't care this value in current test case.
                Pubkey = ByteString.CopyFrom(ValidationDataCenterKeyPairs[0].PublicKey)
            }.ToBytesValue())).ToConsensusHeaderInformation();
            await oneCandidate.UpdateValue.SendAsync(
                cheatInformation.Round.ExtractInformationToUpdateConsensus(ValidationDataCenterKeyPairs[0].PublicKey
                                                                           .ToHex()));
        }
Exemplo n.º 55
0
        public async Task <Object.Object> GetObject(CancellationToken context, GetObjectParams param, CallOptions options = null)
        {
            var object_client  = new ObjectService.ObjectServiceClient(channel);
            var object_address = param.Address;
            var opts           = DefaultCallOptions.ApplyCustomOptions(options);
            var req            = new GetRequest
            {
                Body = new GetRequest.Types.Body
                {
                    Raw     = param.Raw,
                    Address = object_address,
                }
            };
            var meta = opts.GetRequestMetaHeader();

            AttachObjectSessionToken(opts, meta, object_address, ObjectSessionContext.Types.Verb.Get);
            req.MetaHeader = meta;
            req.SignRequest(key);

            var stream  = object_client.Get(req, cancellationToken: context).ResponseStream;
            var obj     = new Object.Object();
            var payload = new byte[] { };
            int offset  = 0;

            while (await stream.MoveNext())
            {
                var resp = stream.Current;
                if (!resp.VerifyResponse())
                {
                    throw new InvalidOperationException("invalid object get response");
                }
                switch (resp.Body.ObjectPartCase)
                {
                case GetResponse.Types.Body.ObjectPartOneofCase.Init:
                {
                    obj.ObjectId  = resp.Body.Init.ObjectId;
                    obj.Signature = resp.Body.Init.Signature;
                    obj.Header    = resp.Body.Init.Header;
                    payload       = new byte[obj.Header.PayloadLength];
                    break;
                }

                case GetResponse.Types.Body.ObjectPartOneofCase.Chunk:
                {
                    resp.Body.Chunk.CopyTo(payload, offset);
                    offset += resp.Body.Chunk.Length;
                    break;
                }

                case GetResponse.Types.Body.ObjectPartOneofCase.SplitInfo:
                {
                    throw new SplitInfoException(resp.Body.SplitInfo);
                }

                default:
                    throw new FormatException("malformed object get reponse");
                }
            }
            obj.Payload = ByteString.CopyFrom(payload);
            return(obj);
        }
 private static ByteString StringToByteString(string str) => ByteString.CopyFrom(Encoding.UTF8.GetBytes(str));
Exemplo n.º 57
0
        public void Convert_ByteArray_To_ByteString_Should_Succeed(int arraySize)
        {
            var testBytes = ByteUtil.GenerateRandomByteArray(arraySize);

            testBytes.ToByteString().Should().Equal(ByteString.CopyFrom(testBytes));
        }
Exemplo n.º 58
0
        private static void WriteRawBlob(DocumentsOperationContext context, List <string> dbIds, List <CounterDetail> counters, ByteString newVal, ManualBlittableJsonDocumentBuilder <UnmanagedWriteBuffer> builder)
        {
            foreach (var counterDetail in counters)
            {
                var dbId = ExtractDbId(context, counterDetail.CounterKey);

                int dbIdIndex;
                for (dbIdIndex = 0; dbIdIndex < dbIds.Count; dbIdIndex++)
                {
                    if (dbIds[dbIdIndex] == dbId)
                    {
                        break;
                    }
                }

                var counterEtag = context.DocumentDatabase.DocumentsStorage.GenerateNextEtag();

                var newEntry = (CountersStorage.CounterValues *)newVal.Ptr + dbIdIndex;
                newEntry->Value = counterDetail.TotalValue;
                newEntry->Etag  = counterEtag;
            }

            builder.WriteRawBlob(newVal.Ptr, newVal.Length);
        }
Exemplo n.º 59
0
        private Unknown6 GenerateSignature(IEnumerable <IMessage> requests)
        {
            var ticketBytes = _authTicket.ToByteArray(); //Added
            var sig         = new Signature()
            {
                LocationHash1 = Utils.GenerateLocation1(ticketBytes, _latitude, _longitude, _altitude),
                LocationHash2 = Utils.GenerateLocation2(_latitude, _longitude, _altitude),
                SensorInfo    = new Signature.Types.SensorInfo()
                {
                    AccelNormalizedZ  = GenRandom(9.8),
                    AccelNormalizedX  = GenRandom(0.02),
                    AccelNormalizedY  = GenRandom(0.3),
                    TimestampSnapshot = (ulong)_internalWatch.ElapsedMilliseconds - 230,
                    MagnetometerX     = GenRandom(0.12271042913198471),
                    MagnetometerY     = GenRandom(-0.015570580959320068),
                    MagnetometerZ     = GenRandom(0.010850906372070313),
                    AngleNormalizedX  = GenRandom(17.950439453125),
                    AngleNormalizedY  = GenRandom(-23.36273193359375),
                    AngleNormalizedZ  = GenRandom(-48.8250732421875),
                    AccelRawX         = GenRandom(-0.0120010357350111),
                    AccelRawY         = GenRandom(-0.04214850440621376),
                    AccelRawZ         = GenRandom(0.94571763277053833),
                    GyroscopeRawX     = GenRandom(7.62939453125e-005),
                    GyroscopeRawY     = GenRandom(-0.00054931640625),
                    GyroscopeRawZ     = GenRandom(0.0024566650390625),
                    AccelerometerAxes = 3
                },
                DeviceInfo = new Signature.Types.DeviceInfo()
                {
                    DeviceId              = Client.DeviceId,
                    AndroidBoardName      = Client.AndroidBoardName,
                    AndroidBootloader     = Client.AndroidBootloader,
                    DeviceBrand           = Client.DeviceBrand,
                    DeviceModel           = Client.DeviceModel,
                    DeviceModelIdentifier = Client.DeviceModelIdentifier,
                    DeviceModelBoot       = Client.DeviceModelBoot,
                    HardwareManufacturer  = Client.HardwareManufacturer,
                    HardwareModel         = Client.HardwareModel,
                    FirmwareBrand         = Client.FirmwareBrand,
                    FirmwareTags          = Client.FirmwareTags,
                    FirmwareType          = Client.FirmwareType,
                    FirmwareFingerprint   = Client.FirmwareFingerprint
                }
            };

            sig.LocationFix.Add(new Signature.Types.LocationFix()
            {
                Provider = "network",

                //Unk4 = 120,
                Latitude            = (float)_latitude,
                Longitude           = (float)_longitude,
                Altitude            = (float)_altitude,
                TimestampSinceStart = (ulong)_internalWatch.ElapsedMilliseconds - 200,
                Floor        = 3,
                LocationType = 1
            });

            //Compute 10
            var x         = new System.Data.HashFunction.xxHash(32, 0x1B845238);
            var firstHash = BitConverter.ToUInt32(x.ComputeHash(_authTicket.ToByteArray()), 0);

            x = new System.Data.HashFunction.xxHash(32, firstHash);
            var locationBytes = BitConverter.GetBytes(_latitude).Reverse()
                                .Concat(BitConverter.GetBytes(_longitude).Reverse())
                                .Concat(BitConverter.GetBytes(_altitude).Reverse()).ToArray();

            sig.LocationHash1 = BitConverter.ToUInt32(x.ComputeHash(locationBytes), 0);

            //Compute 20
            x = new System.Data.HashFunction.xxHash(32, 0x1B845238);
            sig.LocationHash2 = BitConverter.ToUInt32(x.ComputeHash(locationBytes), 0);

            //Compute 24
            x = new System.Data.HashFunction.xxHash(64, 0x1B845238);
            var seed = BitConverter.ToUInt64(x.ComputeHash(_authTicket.ToByteArray()), 0);

            x = new System.Data.HashFunction.xxHash(64, seed);

            foreach (var req in requests)
            {
                sig.RequestHash.Add(BitConverter.ToUInt64(x.ComputeHash(req.ToByteArray()), 0));
            }

            Unknown6 val = new Unknown6();

            val.RequestType       = 6;
            val.Unknown2          = new Unknown6.Types.Unknown2();
            val.Unknown2.Unknown1 = ByteString.CopyFrom(Encrypt(sig.ToByteArray()));

            foreach (var request in requests)
            {
                sig.RequestHash.Add(BitConverter.ToUInt64(x.ComputeHash(request.ToByteArray()), 0));
            }

            sig.Unk22 = ByteString.CopyFrom(new byte[16] {
                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
            });
            sig.Unk25 = BitConverter.ToUInt32(new System.Data.HashFunction.xxHash(64, 0x88533787).ComputeHash(System.Text.Encoding.ASCII.GetBytes("\"0f15301fe1d0e824738ef5d93355e56a6fb910d4\"")), 0);

            return(val);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var db         = DatastoreDb.Create(Project);
            var keyFactory = db.CreateKeyFactory(Kind);

            _gKey = string.IsNullOrEmpty(Key) ? keyFactory.CreateIncompleteKey() : keyFactory.CreateKey(Key);

            var entity = new Entity();

            entity.Key = _gKey;
            foreach (var k in Properties.Keys)
            {
                var val = new Value();

                switch (Properties[k])
                {// I'm surprised there's no built in method in Value to handle this scenario
                case NullValue c:
                {
                    val.NullValue = c;
                    break;
                }

                case bool c:
                {
                    val.BooleanValue = c;
                    break;
                }

                case int c:
                {
                    val.IntegerValue = (long)c;
                    break;
                }

                case long c:
                {
                    val.IntegerValue = c;
                    break;
                }

                case float c:
                {
                    val.DoubleValue = (double)c;
                    break;
                }

                case double c:
                {
                    val.DoubleValue = c;
                    break;
                }

                case Timestamp c:
                {
                    val.TimestampValue = c;
                    break;
                }

                case DateTime c:
                {
                    val.TimestampValue = c.ToTimestamp();
                    break;
                }

                case Cloud.Datastore.V1.Key c:
                {
                    val.KeyValue = c;
                    break;
                }

                case string c:
                {
                    val.StringValue = c;
                    break;
                }

                case byte[] c:
                {
                    if (c.Length > 1000000)
                    {
                        var e  = new ArgumentException("Max byte count exceeded");
                        var er = new ErrorRecord(e, "ByteCountLimitExceeded", ErrorCategory.InvalidData, Properties);
                        ThrowTerminatingError(er);
                    }

                    val.BlobValue = ByteString.CopyFrom(c);
                    break;
                }

                case LatLng c:
                {
                    val.GeoPointValue = c;
                    break;
                }

                case Entity c:
                {
                    val.EntityValue = c;
                    break;
                }

                case ArrayValue c:
                {
                    val.ArrayValue = c;
                    break;
                }

                default:
                {
                    // It's either this or throw - not sure of best approach
                    WriteWarning($"Unexpected type in properties dictionary: {Properties[k].GetType().FullName}");
                    val.StringValue = Properties[k].ToString();
                    break;
                }
                }

                entity.Properties.Add(k.ToString(), val);
            }

            WriteObject(entity);
        }