public async Task <ActionResult> Get(string currency, string address) { try { var codec = new Codec(); var goldCurrencyStateBytes = await this.BlockChainService.GetState(GoldCurrencyState.Address.ToByteArray()); var goldCurrency = new GoldCurrencyState( (Dictionary)codec.Decode(goldCurrencyStateBytes)).Currency; var bytes = await this.BlockChainService.GetBalance( this.ParseHex(address), codec.Encode(goldCurrency.Serialize())); var state = codec.Decode(bytes); return(this.Content( JsonSerializer.Serialize(state, new JsonSerializerOptions { Converters = { new BencodexValueConverter(), }, }), "application/json")); } catch (Exception) { return(new StatusCodeResult(500)); } }
public void TransferAsset( [Argument("SENDER", Description = "An address of sender.")] string sender, [Argument("RECIPIENT", Description = "An address of recipient.")] string recipient, [Argument("AMOUNT", Description = "An amount of gold to transfer.")] int goldAmount, [Argument("GENESIS-BLOCK", Description = "A genesis block containing InitializeStates.")] string genesisBlock ) { byte[] genesisBytes = File.ReadAllBytes(genesisBlock); var genesisDict = (Bencodex.Types.Dictionary)_codec.Decode(genesisBytes); IReadOnlyList <Transaction <NCAction> > genesisTxs = BlockMarshaler.UnmarshalBlockTransactions <NCAction>(genesisDict); var initStates = (InitializeStates)genesisTxs.Single().Actions.Single().InnerAction; Currency currency = new GoldCurrencyState(initStates.GoldCurrency).Currency; var action = new TransferAsset( new Address(sender), new Address(recipient), currency * goldAmount ); var bencoded = new List( (Text)nameof(TransferAsset), action.PlainValue ); byte[] raw = _codec.Encode(bencoded); Console.Write(ByteUtil.Hex(raw)); }
public void ActivateAccount(bool invalid, int expectedCode) { var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; var privateKey = new PrivateKey(); (ActivationKey activationKey, PendingActivationState _) = ActivationKey.Create(privateKey, nonce); string invitationCode = invalid ? "invalid_code" : activationKey.Encode(); var filePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName()); var resultCode = _command.ActivateAccount(invitationCode, ByteUtil.Hex(nonce), filePath); Assert.Equal(expectedCode, resultCode); if (resultCode == 0) { var rawAction = Convert.FromBase64String(File.ReadAllText(filePath)); var decoded = (List)_codec.Decode(rawAction); string type = (Text)decoded[0]; Assert.Equal(nameof(Nekoyume.Action.ActivateAccount), type); Dictionary plainValue = (Dictionary)decoded[1]; var action = new ActivateAccount(); action.LoadPlainValue(plainValue); Assert.Equal(activationKey.PrivateKey.Sign(nonce), action.Signature); Assert.Equal(activationKey.PendingAddress, action.PendingAddress); } else { Assert.Contains("hexWithSlash seems invalid. [invalid_code]", _console.Error.ToString()); } }
public void SpecTestSuite(Spec spec) { _output.WriteLine("YAML: {0}", spec.SemanticsPath); _output.WriteLine("Data: {0}", spec.EncodingPath); Codec codec = new Codec(); IValue decoded = codec.Decode(spec.Encoding); _output.WriteLine("Value: {0}", decoded.Inspect(false)); Assert.Equal(spec.Semantics, decoded); Assert.Equal(spec.Encoding.LongLength, decoded.EncodingLength); Assert.Equal(spec.Semantics.EncodingLength, decoded.EncodingLength); Assert.Equal(spec.Semantics.Fingerprint, decoded.Fingerprint); byte[] encoded = codec.Encode(spec.Semantics); AssertEqual(spec.Encoding, encoded); var random = new Random(); var toOffload = new ConcurrentDictionary <Fingerprint, bool>(); var offloaded = new ConcurrentDictionary <Fingerprint, IValue>(); var offloadOptions = new OffloadOptions( iv => toOffload.TryGetValue(iv.Fingerprint, out bool v) ? v : toOffload[iv.Fingerprint] = random.Next() % 2 == 0, (iv, loader) => offloaded[iv.Fingerprint] = iv.GetValue(loader) ); byte[] encodingWithOffload = codec.Encode(spec.Semantics, offloadOptions); _output.WriteLine( "Encoding with offload ({0}): {1}", encodingWithOffload.LongLength, _utf8.GetString(encodingWithOffload) ); _output.WriteLine( "Encoding with offload (hex): {0}", BitConverter.ToString(encodingWithOffload) ); _output.WriteLine("Offloaded values:"); foreach (KeyValuePair <Fingerprint, IValue> pair in offloaded) { _output.WriteLine("- {0}", pair.Key); } IValue partiallyDecoded = codec.Decode( encodingWithOffload, fp => offloaded[fp] ); Assert.Equal(spec.Semantics.Fingerprint, partiallyDecoded.Fingerprint); Assert.Equal(spec.Semantics, partiallyDecoded); Assert.Equal(spec.Semantics.Inspect(true), partiallyDecoded.Inspect(true)); }
public override TxExecution GetTxExecution(BlockHash blockHash, TxId txid) { UPath path = TxExecutionPath(blockHash, txid); if (_txExecutions.FileExists(path)) { IValue decoded; using (Stream f = _txExecutions.OpenFile( path, System.IO.FileMode.Open, FileAccess.Read)) { try { decoded = Codec.Decode(f); } catch (DecodingException e) { const string msg = "Uncaught exception during " + nameof(GetTxExecution) + ": {Exception}"; _logger.Error(e, msg, e); return(null); } } return(DeserializeTxExecution(blockHash, txid, decoded, _logger)); } return(null); }
public void SpecTestSuite(Spec spec) { Codec codec = new Codec(); IValue decoded = codec.Decode(spec.Encoding); Assert.Equal(spec.Semantics, decoded); }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("imgcomp target_png_file [threshold(0-255)]"); return; } try { int threshold = 128; if (args.Length == 2) { threshold = System.Convert.ToInt32(threshold); } Codec codec = new Codec(); string path = args[0]; var data = codec.Encode(path, 128); File.WriteAllBytes(path + ".bin", data); (var width, var height, var colD, var maskD) = codec.Decode(data); SaveBmp565(path + ".bmp", width, height, colD); SaveBmp565(path + ".m.bmp", width, height, maskD); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
protected override ITextureRef ResolveById(ulong id) { if (Pointers.ContainsKey(id)) { id = Pointers[id]; } if (Files.ContainsKey(id)) { //Non far3 file if (FilesCache.ContainsKey(id)) { return(FilesCache[id]); } var path = this.ContentManager.GetPath(Files[id]); using (var stream = File.OpenRead(path)) { FilesCache.Add(id, Codec.Decode(stream)); return(FilesCache[id]); } } var result = base.ResolveById(id); /* * if (result.ReplacePath == null) * { * if (File.Exists(ReplacementImportDir + id.ToString("x16") + "_[NS-L3][x2.000000].png")) * { * result.ReplacePath = ReplacementImportDir + id.ToString("x16") + "_[NS-L3][x2.000000].png"; * } * } */ return(result); }
public async Task <Stream> Process(Stream request, Context context) { object result; try { var(fullname, args) = await Codec.Decode(request, context as ServiceContext).ConfigureAwait(false); var resultTask = invokeManager.Handler(fullname, args, context); if (Timeout > TimeSpan.Zero) { using (CancellationTokenSource source = new CancellationTokenSource()) { #if NET40 var timer = TaskEx.Delay(Timeout, source.Token); var task = await TaskEx.WhenAny(resultTask, timer).ConfigureAwait(false); #else var timer = Task.Delay(Timeout, source.Token); var task = await Task.WhenAny(resultTask, timer).ConfigureAwait(false); #endif source.Cancel(); if (task == timer) { throw new TimeoutException(); } } } result = await resultTask.ConfigureAwait(false); } catch (Exception e) { result = e.InnerException ?? e; } return(Codec.Encode(result, context as ServiceContext)); }
public void LoadData() { using var f = File.OpenRead(DataFile); using var reader = new BinaryReader(f); Bytes = reader.ReadBytes((int)f.Length); Stream = new MemoryStream(Bytes); Value = Codec.Decode(Bytes); }
public Neighbors(byte[][] dataFrames) { var codec = new Codec(); int foundCount = BitConverter.ToInt32(dataFrames[0], 0); Found = dataFrames.Skip(1).Take(foundCount) .Select(ba => new BoundPeer((Bencodex.Types.Dictionary)codec.Decode(ba))) .ToImmutableList(); }
public void SerializingAndDeserializng_Message_ShouldBeEqual() { var codec = new Codec(); var obj = TestHelper.CreateMessage(); var data = codec.Encode(obj); codec.Decode(data).Should().Be(obj); }
private TxFailure(SerializationInfo info, StreamingContext context) : base(info, context) { ExceptionName = info.GetString(nameof(ExceptionName)) ?? string.Empty; ExceptionMetadata = info.GetValue <byte[]?>(nameof(ExceptionMetadata)) is { } bytes ? Codec.Decode(bytes) : null; }
public void SerializingAndDeserializng_MessageWithEmptyMembers_ShouldBeEqual() { var codec = new Codec(); var obj = new Message(new Dictionary <string, string>(), new List <byte>().ToArray()); var data = codec.Encode(obj); codec.Decode(data).Should().Be(obj); }
public UnaryResult <byte[]> GetBalance(byte[] addressBytes, byte[] currencyBytes) { var address = new Address(addressBytes); var serializedCurrency = (Bencodex.Types.Dictionary)_codec.Decode(currencyBytes); Currency currency = CurrencyExtensions.Deserialize(serializedCurrency); BigInteger balance = _blockChain.GetBalance(address, currency); byte[] encoded = _codec.Encode((Bencodex.Types.Integer)balance); return(UnaryResult(encoded)); }
/// <inheritdoc cref="BaseStore.GetTxExecution(BlockHash, TxId)"/> public override TxExecution GetTxExecution(BlockHash blockHash, TxId txid) { byte[] key = TxExecutionKey(blockHash, txid); if (_txExecutionDb.Get(key) is { } bytes) { return(DeserializeTxExecution(blockHash, txid, Codec.Decode(bytes), _logger)); } return(null); }
public static void Tick(float DeltaTime) { if (ConnectedStateCode_ == (int)ConnectedCode.Failed && OnServerConnectFailed != null) { Interlocked.Exchange(ref ConnectedStateCode_, (int)ConnectedCode.None); OnServerConnectFailed(Ip, Port); } else if (ConnectedStateCode_ == (int)ConnectedCode.Succeeded && OnServerConnectSucceeded != null) { Interlocked.Exchange(ref ConnectedStateCode_, (int)ConnectedCode.None); OnServerConnectSucceeded(Ip, Port); } while (true) { try { NetMsgBuffer Buffer = null; lock (RecvQueueLock_) { if (RecvQueue_.Count == 0) { break; } Buffer = RecvQueue_.Dequeue(); } var Msg = Codec.Decode(Buffer.Data); if (Msg != null) { DispatchMsg(Msg); } } catch { break; } } if (LastSendTime_ >= SendInterval && SendQueue_.Count > 0) { var Data = SendQueue_.Dequeue().Data; /*IAsyncResult result = */ TcpClient_.GetStream().BeginWrite(Data, 0, (int)Data.Length, Ar => { ((TcpClient)Ar.AsyncState).GetStream().EndWrite(Ar); }, TcpClient_); LastSendTime_ = 0.0f; } else { LastSendTime_ += DeltaTime; } }
internal Block <NullAction> GetGenesisBlock(IBlockPolicy <NullAction> policy) { var uri = new Uri(GenesisBlockPath); using (var client = new WebClient()) { var serialized = client.DownloadData(uri); var dict = (Bencodex.Types.Dictionary)Codec.Decode(serialized); return(BlockMarshaler.UnmarshalBlock <NullAction>(policy.GetHashAlgorithm, dict)); } }
private IValue Decompress(byte[] bytes) { using var buffer = new MemoryStream(); using var compressed = new MemoryStream(bytes); using (var deflate = new DeflateStream(compressed, CompressionMode.Decompress)) { deflate.CopyTo(buffer); } buffer.Seek(0, SeekOrigin.Begin); return(_codec.Decode(buffer)); }
/// <summary> /// Gets <see cref="BlockHeader"/> instance from serialized <paramref name="bytes"/>. /// </summary> /// <param name="bytes">Serialized <see cref="BlockHeader"/>.</param> /// <returns>Deserialized <see cref="BlockHeader"/>.</returns> /// <exception cref="DecodingException">Thrown when decoded value is not /// <see cref="Bencodex.Types.Dictionary"/> type.</exception> public static BlockHeader Deserialize(byte[] bytes) { IValue value = Codec.Decode(bytes); if (!(value is Bencodex.Types.Dictionary dict)) { throw new DecodingException( $"Expected {typeof(Bencodex.Types.Dictionary)} but " + $"{value.GetType()}"); } return(new BlockHeader(dict)); }
/// <summary> /// 对协议的编解码测试 /// </summary> private void TestCodec() { LoginReqMsg msg = new LoginReqMsg("123", "pwd"); ByteBuffer buff = new ByteBuffer(Codec.Encode(msg)); LoginReqMsg login = (LoginReqMsg)Codec.Decode(buff); Debug.Log(login.GetCommand()); Debug.Log(login.id); Debug.Log(login.pwd); }
public async Task <Stream> Process(Stream request, Context context) { object result; try { var(fullname, args) = await Codec.Decode(request, context as ServiceContext).ConfigureAwait(false); result = await invokeManager.Handler(fullname, args, context).ConfigureAwait(false); } catch (Exception e) { result = e.InnerException ?? e; } return(Codec.Encode(result, context as ServiceContext)); }
/// <inheritdoc cref="BaseStore.GetBlockDigest(BlockHash)"/> public override BlockDigest?GetBlockDigest(BlockHash blockHash) { if (_blockCache.TryGetValue(blockHash, out BlockDigest cachedDigest)) { return(cachedDigest); } UPath path = BlockPath(blockHash); if (!_blocks.FileExists(path)) { return(null); } BlockDigest blockDigest; try { IValue value = Codec.Decode(_blocks.ReadAllBytes(path)); if (!(value is Bencodex.Types.Dictionary dict)) { throw new DecodingException( $"Expected {typeof(Bencodex.Types.Dictionary)} but " + $"{value.GetType()}"); } blockDigest = new BlockDigest(dict); } catch (FileNotFoundException) { return(null); } _blockCache.AddOrUpdate(blockHash, blockDigest); return(blockDigest); }
public async Task <ContentResult> Get(string address) { var bytes = await this.BlockChainService.GetState(this.ParseHex(address)); var codec = new Codec(); var state = codec.Decode(bytes); return(this.Content( JsonSerializer.Serialize(state, new JsonSerializerOptions { Converters = { new BencodexValueConverter(), }, }), "application/json")); }
public object Deserialize(Stream serializationStream) { IValue value = _codec.Decode(serializationStream); if (!(value is Dictionary)) { throw new SerializationException( "expected a dictionary" ); } var bo = (Dictionary)value; var type = typeof(T); var constructorInfo = type.GetConstructor( BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance, null, new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null); var serializationInfo = new SerializationInfo( typeof(T), new BencodexFormatterConverter() ); foreach (var kv in bo) { var key = FromBencodexKey(kv.Key); serializationInfo.AddValue(key, FromBencodexValue(kv.Value)); } if (constructorInfo == null) { throw new SerializationException( $"Can't found proper constructor in {type} " + "to deserialize it." ); } return(constructorInfo.Invoke( new object[] { serializationInfo, Context, } )); }
/// <summary> /// Decodes a message from a buffer and advance the buffer read cursor. /// </summary> /// <param name="buffer">The buffer.</param> /// <returns></returns> public static Message Decode(ByteBuffer buffer) { Message message = new Message(); while (buffer.Length > 0) { var described = (RestrictedDescribed)Codec.Decode(buffer); if (described.Descriptor.Code == Codec.Header.Code) { message.Header = (Header)described; } else if (described.Descriptor.Code == Codec.DeliveryAnnotations.Code) { message.DeliveryAnnotations = (DeliveryAnnotations)described; } else if (described.Descriptor.Code == Codec.MessageAnnotations.Code) { message.MessageAnnotations = (MessageAnnotations)described; } else if (described.Descriptor.Code == Codec.Properties.Code) { message.Properties = (Properties)described; } else if (described.Descriptor.Code == Codec.ApplicationProperties.Code) { message.ApplicationProperties = (ApplicationProperties)described; } else if (described.Descriptor.Code == Codec.AmqpValue.Code || described.Descriptor.Code == Codec.Data.Code || described.Descriptor.Code == Codec.AmqpSequence.Code) { message.BodySection = described; } else if (described.Descriptor.Code == Codec.Footer.Code) { message.Footer = (Footer)described; } else { throw new AmqpException(ErrorCode.FramingError, Fx.Format(SRAmqp.AmqpUnknownDescriptor, described.Descriptor)); } } return(message); }
private TxSuccess(SerializationInfo info, StreamingContext context) : base(info, context) { var updatedStates = (Dictionary)Codec.Decode(info.GetValue <byte[]>(nameof(UpdatedStates))); UpdatedStates = updatedStates.ToImmutableDictionary( kv => new Address((Binary)kv.Key), kv => kv.Value is List l && l.Any() ? l[0] : null ); FungibleAssetsDelta = DecodeFungibleAssetGroups( info.GetValue <byte[]>(nameof(FungibleAssetsDelta)) ); UpdatedFungibleAssets = DecodeFungibleAssetGroups( info.GetValue <byte[]>(nameof(UpdatedFungibleAssets)) ); }
protected override ITextureRef ResolveById(ulong id) { if (Files.ContainsKey(id)) { //Non far3 file if (FilesCache.ContainsKey(id)) { return(FilesCache[id]); } var path = this.ContentManager.GetPath(Files[id]); using (var stream = File.OpenRead(path)) { FilesCache.Add(id, Codec.Decode(stream)); return(FilesCache[id]); } } return(base.ResolveById(id)); }
public UnaryResult <byte[]> GetBalance(byte[] addressBytes, byte[] currencyBytes) { var address = new Address(addressBytes); var serializedCurrency = (Bencodex.Types.Dictionary)_codec.Decode(currencyBytes); Currency currency = CurrencyExtensions.Deserialize(serializedCurrency); FungibleAssetValue balance = _blockChain.GetBalance(address, currency); byte[] encoded = _codec.Encode( new Bencodex.Types.List( new IValue[] { balance.Currency.Serialize(), (Integer)balance.RawValue, } ) ); return(UnaryResult(encoded)); }
public Dictionary <string, IValue> Load(string jsonFilePath) { if (jsonFilePath is null) { throw new ArgumentNullException(nameof(jsonFilePath)); } if (!_fileSystem.File.Exists(jsonFilePath)) { throw new FileNotFoundException(); } string rawJsonString = _fileSystem.File.ReadAllText(jsonFilePath); Dictionary <string, byte[]> json = JsonSerializer.Deserialize <Dictionary <string, byte[]> >(rawJsonString); var codec = new Codec(); return(json.ToDictionary(pair => pair.Key, pair => codec.Decode(pair.Value))); }