public int ActivateAccount( [Argument("INVITATION-CODE", Description = "An invitation code.")] string invitationCode, [Argument("NONCE", Description = "A hex-encoded nonce for activation.")] string nonceEncoded, [Argument("PATH", Description = "A file path of base64 encoded action.")] string filePath ) { try { ActivationKey activationKey = ActivationKey.Decode(invitationCode); byte[] nonce = ByteUtil.ParseHex(nonceEncoded); Nekoyume.Action.ActivateAccount action = activationKey.CreateActivateAccount(nonce); var encoded = new List( new[] { (Text)nameof(Nekoyume.Action.ActivateAccount), action.PlainValue } ); byte[] raw = Codec.Encode(encoded); File.WriteAllText(filePath, Convert.ToBase64String(raw)); return(0); } catch (Exception e) { _console.Error.WriteLine(e); return(-1); } }
/// <inheritdoc/> public override void SetBlockStates( HashDigest <SHA256> blockHash, IImmutableDictionary <string, IValue> states) { var serialized = new Bencodex.Types.Dictionary( states.ToImmutableDictionary( kv => (IKey)(Text)kv.Key, kv => kv.Value ) ); UPath path = StatePath(blockHash); UPath dirPath = path.GetDirectory(); CreateDirectoryRecursively(_states, dirPath); var codec = new Codec(); using Stream file = _states.CreateFile(path); if (_compress) { using var deflate = new DeflateStream(file, CompressionLevel.Fastest, true); codec.Encode(serialized, deflate); } else { codec.Encode(serialized, file); } _statesCache.AddOrUpdate(blockHash, states); }
public UnaryResult <byte[]> GetState(byte[] addressBytes) { var address = new Address(addressBytes); IValue state = _blockChain.GetState(address, _delayedRenderer?.Tip?.Hash); // FIXME: Null과 null 구분해서 반환해야 할 듯 byte[] encoded = _codec.Encode(state ?? new Null()); return(UnaryResult(encoded)); }
/// <inheritdoc cref="BaseStore.PutTxExecution(Libplanet.Tx.TxSuccess)"/> public override void PutTxExecution(TxSuccess txSuccess) { UPath path = TxExecutionPath(txSuccess); UPath dirPath = path.GetDirectory(); CreateDirectoryRecursively(_txExecutions, dirPath); using Stream f = _txExecutions.OpenFile(path, System.IO.FileMode.OpenOrCreate, FileAccess.Write); Codec.Encode(SerializeTxExecution(txSuccess), f); }
public void Encode() { Codec codec = new Codec(); AssertEqual( new byte[] { 0x74 }, // "t" codec.Encode(_t) ); AssertEqual( new byte[] { 0x66 }, // "f" codec.Encode(_f) ); }
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 void Binary() { // FIXME: Move to BinaryTest. var empty = default(Binary); var hello = new Binary(new byte[] { 0x68, 0x65, 0x6c, 0x6c, 0x6f }); AssertEqual( new byte[] { 0x30, 0x3a }, // "0:" _codec.Encode(empty) ); AssertEqual( new byte[] { 0x35, 0x3a, 0x68, 0x65, 0x6c, 0x6c, 0x6f }, _codec.Encode(hello) // "5:hello" ); }
// implementation method to actually save data protected virtual void SetData() { using (MemoryStream stream = new MemoryStream()) { codec.Encode(stream, EditedFile); CurrentPackedFile.Data = stream.ToArray(); } }
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)); }
/// <inheritdoc/> public NetMQMessage Encode( Message message, PrivateKey privateKey, Peer peer, DateTimeOffset timestamp, AppProtocolVersion version) { var netMqMessage = new NetMQMessage(); // Write body (by concrete class) foreach (byte[] frame in message.DataFrames) { netMqMessage.Append(frame); } // Write headers. (inverse order, version-type-peer-timestamp) netMqMessage.Push(timestamp.Ticks); netMqMessage.Push(_codec.Encode(peer.ToBencodex())); netMqMessage.Push((int)message.Type); netMqMessage.Push(version.Token); // Make and insert signature byte[] signature = privateKey.Sign(netMqMessage.ToByteArray()); List <NetMQFrame> frames = netMqMessage.ToList(); frames.Insert((int)Message.MessageFrame.Sign, new NetMQFrame(signature)); netMqMessage = new NetMQMessage(frames); if (message.Identity is { } to) { netMqMessage.Push(to); } return(netMqMessage); }
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 Export( [Argument( Name = "KV-STORE", Description = KVStoreArgumentDescription)] string kvStoreUri, [Argument( Name = "STATE-ROOT-HASH", Description = "The state root hash to compare.")] string stateRootHashHex, [FromService] IConfigurationService <ToolConfiguration> configurationService) { ToolConfiguration toolConfiguration = configurationService.Load(); kvStoreUri = ConvertKVStoreUri(kvStoreUri, toolConfiguration); IKeyValueStore keyValueStore = LoadKVStoreFromURI(kvStoreUri); var trie = new MerkleTrie( keyValueStore, HashDigest <SHA256> .FromString(stateRootHashHex)); var codec = new Codec(); ImmutableDictionary <string, byte[]> decoratedStates = trie.ListAllStates() .ToImmutableDictionary( pair => Encoding.UTF8.GetString(pair.Key.ToArray()), pair => codec.Encode(pair.Value)); Console.WriteLine(JsonSerializer.Serialize(decoratedStates)); }
public void sendMessage(int type, int area, int command, string message) { // Debug.Print("发送消息啊"); if (IsConnected == false) { //reSendQueue.Enqueue(sm);//加入重新发送列表 return; } SocketModel sm = new SocketModel(type, area, command, message); byte[] removeZero = Codec.Encode(sm); try { if (removeZero != null) { // Debug.Print("发送一条消息啊啊啊啊啊啊啊"); foreach (var item in removeZero) { // Debug.Print(item.ToString()); } socket.Send(removeZero); } } catch { IsConnected = false; //reSendQueue.Enqueue(sm);//加入重新发送列表 } }
static MerkleTrie() { _codec = new Codec(); var bxNull = _codec.Encode(Null.Value); EmptyRootHash = HashDigest <SHA256> .DeriveFrom(bxNull); }
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 ) { Block <NCAction> genesis = Block <NCAction> .Deserialize(File.ReadAllBytes(genesisBlock)); var initStates = (InitializeStates)genesis.Transactions.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( new IValue[] { (Text)nameof(TransferAsset), action.PlainValue } ); byte[] raw = _codec.Encode(bencoded); Console.Write(ByteUtil.Hex(raw)); }
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); } }
public byte[] Serialize() { var codec = new Codec(); byte[] serialized = codec.Encode(ToBencodex()); _bytesLength = serialized.Length; return(serialized); }
private static string DumpBencodexToFile(IValue value, string name) { string path = Path.Join(Path.GetTempPath(), $"{name}.dat"); using FileStream stream = File.OpenWrite(path); _codec.Encode(value, stream); return(path); }
public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue("serialized", Codec.Encode(Serialize())); }
public void TestTransparent() { UInt16[] color = { 0, 0, 0, 0, 0 }; UInt16[] mask = { 0, 0, 0, 0, 0 }; Codec codec = new Codec(); byte[] data = codec.Encode(1, 5, color, mask); Assert.AreEqual(new byte[] { 1, 0, 5, 0, 4 }, data); }
public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(ExceptionName), ExceptionName); info.AddValue( nameof(ExceptionMetadata), ExceptionMetadata is { } m?Codec.Encode(m) : 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 void Encode() { Codec codec = new Codec(); AssertEqual( new byte[] { 0x6e }, // "n" codec.Encode(default(Null)) ); }
public void TestTransparent128() { UInt16[] color = new UInt16[128]; UInt16[] mask = new UInt16[128]; Codec codec = new Codec(); byte[] data = codec.Encode(1, 65, color, mask); Assert.AreEqual(new byte[] { 1, 0, 65, 0, 63, 63 }, data); }
public void SerializingAndDeserializng_Message_ShouldBeEqual() { var codec = new Codec(); var obj = TestHelper.CreateMessage(); var data = codec.Encode(obj); codec.Decode(data).Should().Be(obj); }
public void TestSame5() { UInt16[] color = new UInt16[] { 75, 75, 75, 75, 75 }; UInt16[] mask = new UInt16[] { 255, 255, 255, 255, 255 }; Codec codec = new Codec(); byte[] data = codec.Encode(1, 5, color, mask); Assert.AreEqual(new byte[] { 1, 0, 5, 0, 0x80 | (5 - 1), 75, 0 }, data); }
public void Encode() { Codec codec = new Codec(); AssertEqual( new byte[] { 0x75, 0x30, 0x3a }, // "u0:" codec.Encode(_empty) ); AssertEqual( new byte[] { 0x75, 0x36, 0x3a, 0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd, // "u6:\xe4\xbd\xa0\xe5\xa5\xbd" }, codec.Encode(_nihao) // "你好" ); }
public void Encode(ProtocolBuffer protocolBuffer, object data) { Command command = (Command)data; Type type = command.GetType(); CommandCode code = this.codeByType[type]; Codec codec = this.protocol.GetCodec(type); this.commandCodeCodec.Encode(protocolBuffer, code); codec.Encode(protocolBuffer, command); }
private byte[] Compress(IValue value) { using var buffer = new MemoryStream(); using (var deflate = new DeflateStream(buffer, CompressionLevel.Fastest)) { _codec.Encode(value, deflate); } return(buffer.ToArray()); }